Skip to content

Commit a78c920

Browse files
committed
Fix: Macro.expand/2 should not expand __ENV__ on :match context (#13807)
1 parent b3bfa51 commit a78c920

File tree

3 files changed

+34
-2
lines changed

3 files changed

+34
-2
lines changed

Diff for: lib/elixir/lib/macro.ex

+2-2
Original file line numberDiff line numberDiff line change
@@ -1832,13 +1832,13 @@ defmodule Macro do
18321832
defp do_expand_once({:__DIR__, _, atom}, env) when is_atom(atom),
18331833
do: {:filename.dirname(env.file), true}
18341834

1835-
defp do_expand_once({:__ENV__, _, atom}, env) when is_atom(atom) do
1835+
defp do_expand_once({:__ENV__, _, atom}, env) when is_atom(atom) and env.context != :match do
18361836
env = update_in(env.versioned_vars, &maybe_escape_map/1)
18371837
{maybe_escape_map(env), true}
18381838
end
18391839

18401840
defp do_expand_once({{:., _, [{:__ENV__, _, atom}, field]}, _, []} = original, env)
1841-
when is_atom(atom) and is_atom(field) do
1841+
when is_atom(atom) and is_atom(field) and env.context != :match do
18421842
if Map.has_key?(env, field) do
18431843
{maybe_escape_map(Map.get(env, field)), true}
18441844
else

Diff for: lib/elixir/test/elixir/macro_test.exs

+10
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,16 @@ defmodule MacroTest do
190190
assert Code.eval_quoted(expanded) == {env.versioned_vars, []}
191191
end
192192

193+
test "env in :match context does not expand" do
194+
env = %{__ENV__ | line: 0, lexical_tracker: self(), context: :match}
195+
196+
expanded = Macro.expand_once(quote(do: __ENV__), env)
197+
assert expanded == quote(do: __ENV__)
198+
199+
expanded = Macro.expand_once(quote(do: __ENV__.file), env)
200+
assert expanded == quote(do: __ENV__.file)
201+
end
202+
193203
defmacro local_macro(), do: raise("ignored")
194204

195205
test "vars" do

Diff for: lib/ex_unit/test/ex_unit/assertions_test.exs

+22
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,28 @@ defmodule ExUnit.AssertionsTest do
256256
end
257257
end
258258

259+
test "assert match with __ENV__ in the pattern" do
260+
message =
261+
ExUnit.CaptureIO.capture_io(:stderr, fn ->
262+
assert_raise CompileError, fn ->
263+
Code.eval_string("""
264+
defmodule EnvMatch do
265+
import ExUnit.Assertions
266+
267+
def run do
268+
assert __ENV__ = %{}
269+
end
270+
end
271+
""")
272+
end
273+
end)
274+
275+
assert message =~ "invalid pattern in match, __ENV__ is not allowed in matches"
276+
after
277+
:code.purge(EnvMatch)
278+
:code.delete(EnvMatch)
279+
end
280+
259281
test "assert match?" do
260282
true = assert match?({2, 1}, Value.tuple())
261283

0 commit comments

Comments
 (0)