Class: RuboCop::Cop::Sorbet::ForbidTBindInAssignment

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

Overview

Disallows assigning the result of T.bind.

T.bind changes the type of its first argument and returns that argument. Assigning its result can therefore unintentionally change the inferred type of both the assignment target and the first argument.

Examples:


# bad
foo = T.bind(self, Integer)

# good
foo = T.cast(self, Integer)

Cop Safety Information:

  • Auto-correction is unsafe because replacing T.bind with T.cast removes the scope-wide type rebind of the first argument. Code that relies on that narrowed type may no longer type-check.

Constant Summary collapse

MSG =
"Do not assign the result of `T.bind`; it also changes the type of its first argument."
RESTRICT_ON_SEND =
[:bind].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object Also known as: on_csend



34
35
36
37
38
39
40
41
# File 'lib/rubocop/cop/sorbet/forbid_t_bind_in_assignment.rb', line 34

def on_send(node)
  parent = node.parent
  return unless t_bind?(node) && parent&.assignment? && parent.children.last.equal?(node)

  add_offense(node) do |corrector|
    corrector.replace(node.loc.selector, "cast")
  end
end

#t_bind?(node) ⇒ Object



32
# File 'lib/rubocop/cop/sorbet/forbid_t_bind_in_assignment.rb', line 32

def_node_matcher(:t_bind?, "(send (const nil? :T) :bind _ _)")