[Proposal] Explicit indication of the execution mode in %Macro.Env{}

32 views
Skip to first unread message

Ivan Rublev

unread,
Dec 9, 2021, 2:37:48 PM12/9/21
to elixir-lang-core
Hi folks,
After delivering the library generating code from type specs, I realised that I'm missing the explicit indication of whether the function/macro is executed within the mix compile task, the mix test task, or interactively (iex / live book) during the compile-time.

Here is the code to illustrate the use case:
defmacro __using__(opts) do
  ...
   cond do
      in_mix_compile? ->
        # plan the code generation when mix compile finishes to resolve type dependencies between BEAM files.
      in_mix_test? ->
        # raise an error and suggest compiling the module as an .ex file for the test environment.
      true ->
        # we're in iex / live book, generate code immediately because type dependencies are resolved during the sequential definition of the modules.
   end
end


Currently, I use the following hacks to get to know the execution mode:
def in_mix_compile?(module_env) do        
  tracers = Map.get(module_env || %{}, :tracers, [])        
  Enum.member?(tracers, Mix.Compilers.ApplicationTracer)
end

 
def in_mix_test?(_module_env) do
  not is_nil(GenServer.whereis(ExUnit.Server))          
end


Is it an absurd idea to add the explicit field indicating execution mode like the following?:
%Module.Env{
   execution_mode: :compile | :test | :interactive
}

that can be returned by __CALLER__ in a macro or by __EVN__ in a function.

Warm regards,
Ivan.

José Valim

unread,
Dec 9, 2021, 2:40:12 PM12/9/21
to elixir-lang-core
Can you please explain why you need to know the execution mode.

The fact a library can compile different code depending if it is compile, test, or something else is not something we should encourage.

--
You received this message because you are subscribed to the Google Groups "elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-co...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-lang-core/cb990143-1498-4ccc-b982-73515656f91an%40googlegroups.com.

José Valim

unread,
Dec 9, 2021, 2:43:44 PM12/9/21
to elixir-lang-core
Oh, doh! It is there in your comments. :) Who reads code comments anyway? :D

You want Code.can_await_module_compilation?, available since v1.11. mix test, livebook, iex, are all the same (and all return false).

Ivan Rublev

unread,
Dec 9, 2021, 3:17:31 PM12/9/21
to elixir-lang-core
Ha-ha, turns out sometimes comments have value :D
Thanks for pointing to the correct function. It's much less hacky.
Reply all
Reply to author
Forward
0 new messages