Skip to content

Commit a94af7c

Browse files
committed
Template out a comment_targets method
1 parent 3be8272 commit a94af7c

File tree

3 files changed

+16
-9
lines changed

3 files changed

+16
-9
lines changed

lib/yarp/parse_result/comments.rb

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -100,18 +100,14 @@ def nearest_targets(node, comment)
100100
comment_end = comment.location.end_offset
101101

102102
targets = []
103-
node.deconstruct_keys(nil).each do |key, value|
104-
next if key == :location
105-
103+
node.comment_targets.map do |value|
106104
case value
107105
when StatementsNode
108106
targets.concat(value.body.map { |node| NodeTarget.new(node) })
109107
when Node
110108
targets << NodeTarget.new(value)
111109
when Location
112110
targets << LocationTarget.new(value)
113-
when Array
114-
targets.concat(value.map { |node| NodeTarget.new(node) }) if value.first.is_a?(Node)
115111
end
116112
end
117113

@@ -166,6 +162,8 @@ def nearest_targets(node, comment)
166162
end
167163
end
168164

165+
private_constant :Comments
166+
169167
# Attach the list of comments to their respective locations in the tree.
170168
def attach_comments!
171169
Comments.new(self).attach!

lib/yarp/parse_result/newlines.rb

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ class ParseResult
1717
# Note that the logic in this file should be kept in sync with the Java
1818
# MarkNewlinesVisitor, since that visitor is responsible for marking the
1919
# newlines for JRuby/TruffleRuby.
20-
class MarkNewlinesVisitor < Visitor
20+
class Newlines < Visitor
2121
def initialize(newline_marked)
2222
@newline_marked = newline_marked
2323
end
@@ -50,12 +50,11 @@ def visit_statements_node(node)
5050
end
5151
end
5252

53-
private_constant :MarkNewlinesVisitor
53+
private_constant :Newlines
5454

5555
# Walk the tree and mark nodes that are on a new line.
5656
def mark_newlines!
57-
newline_marked = Array.new(1 + source.offsets.size, false)
58-
value.accept(MarkNewlinesVisitor.new(newline_marked))
57+
value.accept(Newlines.new(Array.new(1 + source.offsets.size, false)))
5958
end
6059
end
6160
end

templates/lib/yarp/node.rb.erb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,16 @@ module YARP
4848
}.compact.join(", ") %>]
4949
end
5050

51+
# def comment_targets: () -> Array[Node | Location]
52+
def comment_targets
53+
[<%= node.fields.map { |field|
54+
case field
55+
when YARP::NodeField, YARP::LocationField then field.name
56+
when YARP::OptionalNodeField, YARP::NodeListField, YARP::OptionalLocationField then "*#{field.name}"
57+
end
58+
}.compact.join(", ") %>]
59+
end
60+
5161
# def copy: (**params) -> <%= node.name %>
5262
def copy(**params)
5363
<%= node.name %>.new(

0 commit comments

Comments
 (0)