Class: RuboCop::Cop::RBS::Style::ClassicType

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

Overview

Examples:

default

# bad
def foo: () -> TrueClass

# bad
def bar: () -> NilClass

# good
def foo: () -> true

# good
def bar: () -> nil

Constant Summary collapse

Types =
::RBS::Types

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_class, #on_rbs_interface, #on_rbs_module, #on_rbs_new_investigation, #on_rbs_parsing_error, #on_rbs_private, #on_rbs_public, #parse_rbs, #rbs_buffer, #tokenize, #walk

Methods included from RBS::OnTypeHelper

#on_not_type, #on_type

Instance Method Details

#check_type(type) ⇒ Object



41
42
43
44
45
46
47
48
# File 'lib/rubocop/cop/rbs/style/classic_type.rb', line 41

def check_type(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)
    end
  end
end

#find_replacement(type, &block) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/rubocop/cop/rbs/style/classic_type.rb', line 50

def find_replacement(type, &block)
  case type
  when Types::Record,
       Types::Tuple,
       Types::Union,
       Types::Intersection,
       Types::Optional,
       Types::Proc,
       Types::Alias,
       Types::Interface
    type.each_type do |t|
      find_replacement(t, &block)
    end
  when Types::ClassInstance
    case type.name.to_s
    when 'TrueClass', '::TrueClass'
      block.call([type, 'true'])
    when 'FalseClass', '::FalseClass'
      block.call([type, 'false'])
    when 'NilClass', '::NilClass'
      block.call([type, 'nil'])
    end
    type.each_type do |arg|
      find_replacement(arg, &block)
    end
  end
end

#on_rbs_constant(decl) ⇒ Object Also known as: on_rbs_global, on_rbs_type_alias, on_rbs_attribute, on_rbs_var



32
33
34
# File 'lib/rubocop/cop/rbs/style/classic_type.rb', line 32

def on_rbs_constant(decl)
  check_type(decl.type)
end

#on_rbs_def(decl) ⇒ Object



24
25
26
27
28
29
30
# File 'lib/rubocop/cop/rbs/style/classic_type.rb', line 24

def on_rbs_def(decl)
  decl.overloads.each do |overload|
    overload.method_type.each_type do |type|
      check_type(type)
    end
  end
end