Class: RuboCop::Cop::Sorbet::BindingConstantWithoutTypeAlias

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/sorbet/binding_constant_without_type_alias.rb

Overview

Disallows binding the return value of ‘T.any`, `T.all`, `T.enum` to a constant directly. To bind the value, one must use `T.type_alias`.

Examples:


# bad
FooOrBar = T.any(Foo, Bar)

# good
FooOrBar = T.type_alias { T.any(Foo, Bar) }

Constant Summary collapse

MSG =
"It looks like you're trying to bind a type to a constant. " \
"To do this, you must alias the type using `T.type_alias`."
WITHOUT_BLOCK_MSG =
"It looks like you're using the old `T.type_alias` syntax. " \
"`T.type_alias` now expects a block." \
'Run Sorbet with the options "--autocorrect --error-white-list=5043" ' \
"to automatically upgrade to the new syntax."

Instance Method Summary collapse

Instance Method Details

#on_casgn(node) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/rubocop/cop/sorbet/binding_constant_without_type_alias.rb', line 65

def on_casgn(node)
  expression = node.expression
  return if expression.nil? # multiple assignment

  type_alias_without_block(expression) do |type|
    return add_offense(expression, message: WITHOUT_BLOCK_MSG) do |corrector|
      corrector.replace(expression, "T.type_alias { #{type.source} }")
    end
  end

  return if type_alias_with_block?(expression)

  requires_type_alias?(send_leaf(expression)) do
    return add_offense(expression) do |corrector|
      corrector.replace(expression, "T.type_alias { #{expression.source} }")
    end
  end
end

#requires_type_alias?(node) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/rubocop/cop/sorbet/binding_constant_without_type_alias.rb', line 48

def_node_matcher :requires_type_alias?, "(send\n  (const {nil? cbase} :T)\n  {\n    :all\n    :any\n    :class_of\n    :nilable\n    :noreturn\n    :proc\n    :self_type\n    :untyped\n  }\n  ...\n)\n"

#type_alias_with_block?(node) ⇒ Object



38
39
40
41
42
43
44
45
# File 'lib/rubocop/cop/sorbet/binding_constant_without_type_alias.rb', line 38

def_node_matcher :type_alias_with_block?, "(block\n  (send\n    (const {nil? cbase} :T)\n  :type_alias)\n  ...\n)\n"

#type_alias_without_block(node) ⇒ Object



29
30
31
32
33
34
35
# File 'lib/rubocop/cop/sorbet/binding_constant_without_type_alias.rb', line 29

def_node_matcher :type_alias_without_block, "(send\n  (const {nil? cbase} :T)\n  :type_alias\n  $_\n)\n"