Skip to content

Commit 142c2f1

Browse files
committed
Handle for _ in _ procs in Prism.node_for
1 parent 3c0b91c commit 142c2f1

File tree

3 files changed

+22
-2
lines changed

3 files changed

+22
-2
lines changed

lib/prism/parse_result.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -946,10 +946,12 @@ def self.node_for(callable)
946946
when CallNode
947947
# Proc#source_location returns start_column 5 for `proc { ... }` (the `{`)
948948
node.block.is_a?(BlockNode) && node.block.opening_loc.start_offset == start_offset && node.end_offset == end_offset
949+
when ForNode
950+
node.start_offset == start_offset && node.end_offset == end_offset
949951
else
950952
false
951953
end
952-
end #: DefNode | LambdaNode | CallNode
954+
end #: DefNode | LambdaNode | CallNode | ForNode
953955

954956
raise ArgumentError, "Could not find node for #{callable} in #{file} at (#{start_line},#{start_column})-(#{end_line},#{end_column})" unless found
955957
found

templates/sig/prism.rbs.erb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,5 +94,5 @@ module Prism
9494

9595
def self.scope: (?locals: Array[Symbol], ?forwarding: Array[Symbol]) -> Scope
9696

97-
def self.node_for: (Method | UnboundMethod | Proc callable) -> (DefNode | LambdaNode | CallNode)
97+
def self.node_for: (Method | UnboundMethod | Proc callable) -> (DefNode | LambdaNode | CallNode | ForNode)
9898
end

test/prism/ruby/node_for_test.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,17 @@ def return_block(&block)
2424
block
2525
end
2626

27+
iter = Object.new
28+
def iter.each(&block)
29+
block.call(block)
30+
end
31+
32+
for pr in iter
33+
42
34+
end
35+
FOR_BODY_PROC = pr
36+
FOR_BODY_PROC_LOCATION = [__LINE__-4, 4, __LINE__-2, 7]
37+
2738
def with_location(callable, locs, file = __FILE__)
2839
source_location = [file, *locs]
2940
if RUBY_VERSION >= "4.0"
@@ -95,6 +106,13 @@ def test_method_to_proc
95106
assert_equal "def inline_method = 42", node.slice
96107
end
97108

109+
def test_for
110+
node = Prism.node_for(with_location(FOR_BODY_PROC, FOR_BODY_PROC_LOCATION))
111+
assert_instance_of(Prism::ForNode, node)
112+
assert_equal "for pr in iter\n#{INDENT} 42\n#{INDENT}end", node.slice
113+
assert_equal "42", node.statements.slice
114+
end
115+
98116
def test_eval
99117
l = with_location(eval("-> { 42 }"), [1, 2, 1, 9], "(eval at #{__FILE__}:#{__LINE__})")
100118
e = assert_raise(ArgumentError) { Prism.node_for(l) }

0 commit comments

Comments
 (0)