Class: RuboCop::Cop::Codemod::RbsPrototype

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
IgnoredNode
Defined in:
lib/rubocop/oneoff_codemod/cops/rbs_prototype.rb

Overview

KeepUnique

Constant Summary collapse

MSG =
"Run rbs prototype and generates boilerplate signature declaration."
COMMAND =
"rbs-prototype"

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ RbsPrototype

Returns a new instance of RbsPrototype.



16
17
18
19
# File 'lib/rubocop/oneoff_codemod/cops/rbs_prototype.rb', line 16

def initialize(*args)
  super
  @commands = {}
end

Instance Method Details

#find_node_on_line(node, target_line) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/rubocop/oneoff_codemod/cops/rbs_prototype.rb', line 21

def find_node_on_line(node, target_line)
  if node.is_a?(RuboCop::AST::DefNode) && node.loc&.line == target_line
    node
  else
    finded = nil
    node.child_nodes.each do |child_node|
      finded = find_node_on_line child_node, target_line
      break if finded
    end
    finded
  end
end

#on_new_investigationObject



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/rubocop/oneoff_codemod/cops/rbs_prototype.rb', line 34

def on_new_investigation
  processed_source.comments.each do |comment|
    next unless comment.text == "# @#{COMMAND}"

    target_node = find_node_on_line(processed_source.ast, comment.location.line + 1)
    next if target_node.nil?

    target_method = target_node.method_name

    add_offense(comment.location.expression) do |corrector|
      parser = RBS::Prototype::RB.new
      parser.parse processed_source.raw_source
      string = []
      parser.decls.each do |decl|
        decl.members.each do |member|
          string << member.overloads.map(&:method_type).join(" | ") if target_method == member.name
        end
      end

      corrector.replace(comment.location.expression, "#: #{string.join}")
    end
  end
end