Class: RuboCop::Cop::RBS::Lint::AmbiguousOperatorPrecedence

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

Overview

Checks for ambiguity of Union and Intersection operators.

Examples:

default

# bad
def foo: (A | B & C) -> void

# good
def foo: (A | (B & C)) -> void

Constant Summary collapse

MSG =
'Wrap expressions with varying precedence with parentheses to avoid ambiguity.'

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



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/rubocop/cop/rbs/lint/ambiguous_operator_precedence.rb', line 37

def check_type(type)
  on_type([::RBS::Types::Union], type) do |union|
    union.types.each do |t|
      case t
      when ::RBS::Types::Intersection
        next unless t.location

        start_index = bsearch_token_index(t.location.start_pos)
        end_index = bsearch_token_index(t.location.end_pos)
        before = processed_rbs_source.tokens[start_index - 1]
        after = processed_rbs_source.tokens[end_index]
        unless before.type == :pLPAREN && after.type == :pRPAREN
          range = location_to_range(t.location)
          add_offense(range) do |corrector|
            corrector.wrap(range, '(', ')')
          end
        end
      end
    end
  end
end

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



29
30
31
# File 'lib/rubocop/cop/rbs/lint/ambiguous_operator_precedence.rb', line 29

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

#on_rbs_def(decl) ⇒ Object



21
22
23
24
25
26
27
# File 'lib/rubocop/cop/rbs/lint/ambiguous_operator_precedence.rb', line 21

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