Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support global variable target in for loop #2136

Merged
merged 2 commits into from
Jun 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions lib/natalie/compiler/args.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ def transform_arg(arg)
transform_instance_variable_arg(arg)
when ::Prism::ClassVariableTargetNode
transform_class_variable_arg(arg)
when ::Prism::GlobalVariableTargetNode
transform_global_variable_arg(arg)
when ::Prism::ConstantTargetNode
transform_constant_arg(arg)
when ::Prism::RequiredParameterNode
Expand Down Expand Up @@ -174,6 +176,11 @@ def transform_class_variable_arg(arg)
@instructions << ClassVariableSetInstruction.new(arg.name)
end

def transform_global_variable_arg(arg)
@instructions << ArrayShiftInstruction.new
@instructions << GlobalVariableSetInstruction.new(arg.name)
end

def transform_constant_arg(arg)
@instructions << ArrayShiftInstruction.new
@instructions << PushSelfInstruction.new
Expand Down
1 change: 1 addition & 0 deletions lib/natalie/compiler/pass1.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2671,6 +2671,7 @@ def maximum_arg_count(args)
%i[
class_variable_target_node
constant_target_node
global_variable_target_node
instance_variable_target_node
local_variable_target_node
multi_target_node
Expand Down
12 changes: 12 additions & 0 deletions spec/language/for_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,18 @@ class OFor
end
end

it "allows a global variable as an iterator name" do
old_global_var = $var
m = [1,2,3]
n = 0
for $var in m
n += 1
end
$var.should == 3
n.should == 3
$var = old_global_var
end

# 1.9 behaviour verified by nobu in
# http://redmine.ruby-lang.org/issues/show/2053
it "yields only as many values as there are arguments" do
Expand Down
Loading