Skip to content

Commit 329ce7d

Browse files
committed
Only create fresh environment for a MethodAddBlock block
The call part of a MethodAddBlock node occurs in the same environment. Only the block portion of it occurs in a fresh environment.
1 parent 07ac277 commit 329ce7d

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

lib/syntax_tree/visitor/with_environment.rb

+5-1
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,12 @@ def visit_module(node)
4444
with_new_environment { super }
4545
end
4646

47+
# When we find a method invocation with a block, only the code that happens
48+
# inside of the block needs a fresh environment. The method invocation
49+
# itself happens in the same environment
4750
def visit_method_add_block(node)
48-
with_new_environment { super }
51+
visit(node.call)
52+
with_new_environment { visit(node.block) }
4953
end
5054

5155
def visit_def(node)

test/visitor_with_environment_test.rb

+27
Original file line numberDiff line numberDiff line change
@@ -506,5 +506,32 @@ def test_aref_on_a_method_call_with_arguments
506506
assert_equal(1, variable.definitions[0].start_line)
507507
assert_equal(2, variable.usages[0].start_line)
508508
end
509+
510+
def test_double_aref_on_method_call
511+
tree = SyntaxTree.parse(<<~RUBY)
512+
object = MyObject.new
513+
object["attributes"].find { |a| a["field"] == "expected" }["value"] = "changed"
514+
RUBY
515+
516+
visitor = Collector.new
517+
visitor.visit(tree)
518+
519+
assert_equal(1, visitor.arguments.length)
520+
assert_equal(1, visitor.variables.length)
521+
522+
variable = visitor.variables["object"]
523+
assert_equal(1, variable.definitions.length)
524+
assert_equal(1, variable.usages.length)
525+
526+
assert_equal(1, variable.definitions[0].start_line)
527+
assert_equal(2, variable.usages[0].start_line)
528+
529+
argument = visitor.arguments["a"]
530+
assert_equal(1, argument.definitions.length)
531+
assert_equal(1, argument.usages.length)
532+
533+
assert_equal(2, argument.definitions[0].start_line)
534+
assert_equal(2, argument.usages[0].start_line)
535+
end
509536
end
510537
end

0 commit comments

Comments
 (0)