Skip to content

Commit

Permalink
Allow assignment to _ inside macro expressions (#14452)
Browse files Browse the repository at this point in the history
  • Loading branch information
HertzDevil committed Apr 16, 2024
1 parent fc3352c commit 5297fd0
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
25 changes: 25 additions & 0 deletions spec/compiler/semantic/macro_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -1688,6 +1688,12 @@ describe "Semantic: macro" do
method.location.not_nil!.expanded_location.not_nil!.line_number.should eq(9)
end

it "assigns to underscore" do
assert_no_errors <<-CRYSTAL
{% _ = 1 %}
CRYSTAL
end

it "unpacks block parameters inside macros (#13742)" do
assert_no_errors <<-CRYSTAL
macro foo
Expand All @@ -1707,6 +1713,16 @@ describe "Semantic: macro" do
CRYSTAL
end

it "unpacks to underscore within block parameters inside macros" do
assert_type(<<-CRYSTAL) { bool }
{% begin %}
{% x = nil %}
{% [{1, true, 'a', ""}].each { |(_, y, _, _)| x = y } %}
{{ x }}
{% end %}
CRYSTAL
end

it "executes OpAssign (#9356)" do
assert_type(<<-CRYSTAL) { int32 }
{% begin %}
Expand Down Expand Up @@ -1740,6 +1756,15 @@ describe "Semantic: macro" do
CRYSTAL
end

it "assigns to underscore in MultiAssign" do
assert_type(<<-CRYSTAL) { tuple_of([char, bool]) }
{% begin %}
{% _, x, *_, y = [1, 'a', "", nil, true] %}
{ {{x}}, {{y}} }
{% end %}
CRYSTAL
end

describe "@caller" do
it "returns an array of each call" do
assert_type(<<-CRYSTAL) { int32 }
Expand Down
2 changes: 2 additions & 0 deletions src/compiler/crystal/macros/interpreter.cr
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,8 @@ module Crystal
when Var
node.value.accept self
@vars[target.name] = @last
when Underscore
node.value.accept self
else
node.raise "can only assign to variables, not #{target.class_desc}"
end
Expand Down

0 comments on commit 5297fd0

Please sign in to comment.