Class: RuboCop::Cop::RBS::Layout::SpaceAroundArrow

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

Overview

Examples:

default

# bad
def foo: ()->void

# bad
def bar: () { ()->void } -> void

# good
def foo: () -> void

# good
def bar: () { () -> void } -> void

Constant Summary collapse

MSG_BEFORE =
'Use one space before `->`.'
MSG_AFTER =
'Use one space after `->`.'

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

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



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/rubocop/cop/rbs/layout/space_around_arrow.rb', line 26

def on_rbs_def(decl)
  base = decl.location.start_pos
  tokens = ::RBS::Parser.lex(decl.location.source).value.reject { |t| t.type == :tTRIVIA }
  ([nil] + tokens).each_cons(3) do |before, token, after|
    next unless token&.type == :pARROW

    loc = token&.location
    next unless loc

    if before && (before.location.end_pos + 1 != loc.start_pos)
      next unless before.location.end_line == loc.start_line

      arrow = location_to_range(loc).adjust(begin_pos: base, end_pos: base)
      add_offense(arrow, message: MSG_BEFORE) do |corrector|
        range = range_between(before.location.end_pos, loc.start_pos)
        corrector.replace(range.adjust(begin_pos: base, end_pos: base), ' ')
      end
    end

    if loc.end_pos + 1 != after.location.start_pos
      next unless loc.end_line == after.location.start_line

      arrow = location_to_range(loc).adjust(begin_pos: base, end_pos: base)
      add_offense(arrow, message: MSG_AFTER) do |corrector|
        range = range_between(loc.end_pos, after.location.start_pos)
        corrector.replace(range.adjust(begin_pos: base, end_pos: base), ' ')
      end
    end
  end
end