From bd454e286dbd5d854043b613be99b9ee4b1663cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Mon, 28 Aug 2023 13:14:08 +0200 Subject: [PATCH] Ensure dbg module is a compile-time dependency Related to #12892. --- lib/elixir/lib/kernel.ex | 2 +- lib/elixir/lib/macro.ex | 14 ++++++++++- .../elixir/kernel/lexical_tracker_test.exs | 25 +++++++++++++++++++ 3 files changed, 39 insertions(+), 2 deletions(-) diff --git a/lib/elixir/lib/kernel.ex b/lib/elixir/lib/kernel.ex index 4e61345bd7..a8c8ca5018 100644 --- a/lib/elixir/lib/kernel.ex +++ b/lib/elixir/lib/kernel.ex @@ -6022,7 +6022,7 @@ defmodule Kernel do @doc since: "1.14.0" defmacro dbg(code \\ quote(do: binding()), options \\ []) do {mod, fun, args} = Application.compile_env!(__CALLER__, :elixir, :dbg_callback) - apply(mod, fun, [code, options, __CALLER__ | args]) + Macro.compile_apply(mod, fun, [code, options, __CALLER__ | args], __CALLER__) end ## Sigils diff --git a/lib/elixir/lib/macro.ex b/lib/elixir/lib/macro.ex index 8d402b7201..bb6883e226 100644 --- a/lib/elixir/lib/macro.ex +++ b/lib/elixir/lib/macro.ex @@ -1758,6 +1758,18 @@ defmodule Macro do end end + @doc """ + Applies a `mod`, `function`, and `args` at compile-time in `caller`. + + This is used when you want to programatically invoke a macro at + compile-time. + """ + @doc since: "1.16.0" + def compile_apply(mod, fun, args, caller) do + :elixir_env.trace({:remote_macro, [], mod, fun, length(args)}, caller) + Kernel.apply(mod, fun, args) + end + @doc """ Receives an AST node and expands it once. @@ -2322,7 +2334,7 @@ defmodule Macro do ## Atom handling @doc """ - Classifies a runtime `atom` based on its possible AST placement. + Classifies an `atom` based on its possible AST placement. It returns one of the following atoms: diff --git a/lib/elixir/test/elixir/kernel/lexical_tracker_test.exs b/lib/elixir/test/elixir/kernel/lexical_tracker_test.exs index bed98b6b1c..64a838ef11 100644 --- a/lib/elixir/test/elixir/kernel/lexical_tracker_test.exs +++ b/lib/elixir/test/elixir/kernel/lexical_tracker_test.exs @@ -334,6 +334,31 @@ defmodule Kernel.LexicalTrackerTest do assert URI in runtime end + test "dbg adds a compile dependency" do + {{compile, exports, runtime, _}, _binding} = + Code.eval_string(""" + defmodule Kernel.LexicalTrackerTest.Dbg do + def foo, do: dbg(:ok) + Kernel.LexicalTracker.references(__ENV__.lexical_tracker) + end |> elem(3) + """) + + assert Macro in compile + refute Macro in exports + refute Macro in runtime + + {{compile, exports, runtime, _}, _binding} = + Code.eval_string(""" + defmodule Kernel.LexicalTrackerTest.NoDbg do + Kernel.LexicalTracker.references(__ENV__.lexical_tracker) + end |> elem(3) + """) + + refute Macro in compile + refute Macro in exports + refute Macro in runtime + end + test "imports adds an export dependency" do {{compile, exports, runtime, _}, _binding} = Code.eval_string("""