Class: RuboCop::Cop::RBS::Style::OptionalNil

Inherits:
RBS::CopBase
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/rbs/style/optional_nil.rb

Overview

Examples:

default

# bad
def foo: (nil?) -> void

# good
def foo: (nil) -> void

Instance Attribute Summary

Attributes inherited from RBS::CopBase

#processed_rbs_source

Instance Method Summary collapse

Methods inherited from RBS::CopBase

#investigation_rbs, #location_to_range, #on_new_investigation, #on_other_file, #on_rbs_attribute, #on_rbs_class, #on_rbs_constant, #on_rbs_global, #on_rbs_interface, #on_rbs_module, #on_rbs_new_investigation, #on_rbs_parsing_error, #on_rbs_private, #on_rbs_public, #on_rbs_type_alias, #on_rbs_var, #parse_rbs, #rbs_buffer, #tokenize, #walk

Methods included from RBS::OnTypeHelper

#on_not_type, #on_type

Instance Method Details

#find_replacement(type, &block) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/rubocop/cop/rbs/style/optional_nil.rb', line 31

def find_replacement(type, &block)
  case type
  when ::RBS::Types::Optional
    case type.type
    when ::RBS::Types::Bases::Nil
      block.call([type, ::RBS::Types::Bases::Nil.new(location: nil)])
    else
      find_replacement(type.type, &block)
    end
  else
    type.each_type do |type|
      find_replacement(type, &block)
    end
  end
end

#on_rbs_def(decl) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/rubocop/cop/rbs/style/optional_nil.rb', line 17

def on_rbs_def(decl)
  decl.overloads.each do |overload|
    overload.method_type.each_type do |type|
      find_replacement(type) do |t, replaced|
        range = location_to_range(t.location)
        add_offense(range, message: "Use `#{replaced}` instead of `#{t}`") do |corrector|
          corrector.replace(range, replaced.to_s)
        end
      end
    end
  end
end