Class: RuboCop::Cop::RBS::Lint::AmbiguousKeywordArgumentKey

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

Overview

Checks keyword argument keys that are not local variable names.

Examples:

default

# bad
def foo: (option?: bool, option!: bool, Option: bool) -> void

Instance Attribute Summary

Attributes inherited from RBS::CopBase

#processed_rbs_source

Instance Method Summary collapse

Methods inherited from RBS::CopBase

documentation_url, #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

#on_rbs_def(decl) ⇒ Object



17
18
19
20
21
22
23
24
25
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
56
57
# File 'lib/rubocop/cop/rbs/lint/ambiguous_keyword_argument_key.rb', line 17

def on_rbs_def(decl)
  decl.overloads.each do |overload|
    func = overload.method_type.type
    next unless func.kind_of?(::RBS::Types::Function)
    next unless !func.required_keywords.empty? || !func.optional_keywords.empty?

    base_pos = overload.method_type.location.start_pos
    lex_result = ::RBS::Parser.lex(overload.method_type.location.source)
    buf = []
    lex_result.value.each do |token|
      case token.type
      when :pLPAREN, :pRPAREN, :tTRIVIA
        # skip
      when :pCOLON
        next if buf.empty?

        case buf.last.type
        when :pQUESTION
          buf.shift if buf.first.type == :pQUESTION
          actual = buf.map { |t| t.location.source }.join
          did_you_mean = buf.reject { |t| t.location.source == '?' }.map { |t| t.location.source }.join
          message = +"`#{actual}` is not local variable name."
          if did_you_mean.length > 0
            message << " Did you mean `?#{did_you_mean}` for optional keyword argument?"
          end
          range = range_between(buf.first.location.start_pos + base_pos, buf.last.location.end_pos + base_pos)
          add_offense(range, message: message)
        when :tBANGIDENT, :tUIDENT
          buf.shift if buf.first.type == :pQUESTION
          actual = buf.map { |t| t.location.source }.join
          range = range_between(buf.first.location.start_pos + base_pos, buf.last.location.end_pos + base_pos)
          add_offense(range, message: "`#{actual}` is not local variable name.")
        end
      when :pCOMMA
        buf.clear
      else
        buf << token
      end
    end
  end
end