Skip to content

Commit

Permalink
Support bitstring specifies as map keys in pattern, closes #12586
Browse files Browse the repository at this point in the history
  • Loading branch information
josevalim committed May 22, 2023
1 parent 8d5b213 commit 90c8327
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
2 changes: 2 additions & 0 deletions lib/elixir/src/elixir_map.erl
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ clean_struct_key_from_map_assocs(Meta, Assocs, E) ->

validate_match_key(Meta, {Name, _, Context}, E) when is_atom(Name), is_atom(Context) ->
file_error(Meta, E, ?MODULE, {invalid_variable_in_map_key_match, Name});
validate_match_key(Meta, {'::', _, [Left, _]}, E) ->
validate_match_key(Meta, Left, E);
validate_match_key(_, {'^', _, [{Name, _, Context}]}, _) when is_atom(Name), is_atom(Context) ->
ok;
validate_match_key(_, {'%{}', _, [_ | _]}, _) ->
Expand Down
30 changes: 29 additions & 1 deletion lib/elixir/test/elixir/kernel/expansion_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -483,7 +483,7 @@ defmodule Kernel.ExpansionTest do
quote(do: %{a: after_expansion = 1, b: a()})
end

test "with variables on keys" do
test "with variables on keys inside patterns" do
ast =
quote do
%{(x = 1) => 1}
Expand Down Expand Up @@ -516,6 +516,34 @@ defmodule Kernel.ExpansionTest do
end)
end

test "with binaries in keys inside patterns" do
before_ast =
quote do
%{<<0>> => nil} = %{<<0>> => nil}
end

after_ast =
quote do
%{<<0::integer>> => nil} = %{<<0::integer>> => nil}
end

assert expand(before_ast) |> clean_meta([:alignment]) == clean_bit_modifiers(after_ast)
assert expand(after_ast) |> clean_meta([:alignment]) == clean_bit_modifiers(after_ast)

ast =
quote do
x = 8
%{<<0::integer-size(x)>> => nil} = %{<<0::integer>> => nil}
end

assert expand(ast) |> clean_meta([:alignment]) ==
clean_bit_modifiers(ast) |> clean_meta([:context, :imports])

assert_compile_error(~r"cannot use variable x as map key inside a pattern", fn ->
expand(quote(do: %{<<x::integer>> => 1} = %{}), [])
end)
end

test "expects key-value pairs" do
assert_compile_error(~r"expected key-value pairs in a map, got: :foo", fn ->
expand(quote(do: unquote({:%{}, [], [:foo]})))
Expand Down

0 comments on commit 90c8327

Please sign in to comment.