Class: RuboCop::Cop::Sorbet::ForbidTAnyWithNil

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

Overview

Detect and autocorrect ‘T.any(…, NilClass, …)` to `T.nilable(…)`

Examples:


# bad
T.any(String, NilClass)
T.any(NilClass, String)
T.any(NilClass, Symbol, String)

# good
T.nilable(String)
T.nilable(String)
T.nilable(T.any(Symbol, String))

Constant Summary collapse

MSG =
"Use `T.nilable` instead of `T.any(..., NilClass, ...)`."
RESTRICT_ON_SEND =
[:any].freeze

Instance Method Summary collapse

Instance Method Details

#nil_const_node?(node) ⇒ Object



31
32
33
# File 'lib/rubocop/cop/sorbet/forbid_t_any_with_nil.rb', line 31

def_node_matcher :nil_const_node?, "(const nil? :NilClass)\n"

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



35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/rubocop/cop/sorbet/forbid_t_any_with_nil.rb', line 35

def on_send(node)
  args = t_any_call?(node)
  return unless args

  nil_args, non_nil_args = args.partition { |a| nil_const_node?(a) }
  return if nil_args.empty? || non_nil_args.empty?

  add_offense(node) do |corrector|
    replacement = build_replacement(non_nil_args)

    corrector.replace(node, replacement)
  end
end

#t_any_call?(node) ⇒ Object



26
27
28
# File 'lib/rubocop/cop/sorbet/forbid_t_any_with_nil.rb', line 26

def_node_matcher :t_any_call?, "(send (const nil? :T) :any $...)\n"