addrummond

addrummond

Is it possible to detect if code is executing at compile time?

Can Elixir code detect whether it is executing at compile time? I would like to write something like the following macro:

defmacro foo() do
  quote do
    if is_compile_time? do
      one_thing()
    else
      another_thing()
    end
  end
end

It’s presumably obvious how the code that the macro expands to can execute at runtime. It can execute at compile time in a scenario such as the following:

defmodule Bar do
  def bar() do
    foo() # invoke the macro
  end
end

defmodule Amp do
  @attr Bar.bar() # code that 'foo' macro expands to is executed at compile time
end

I have tried examining __ENV__, but unless I’m missing something, it offers no reliable diagnostic for compile time vs. runtime. I wonder if there is any other way. For anyone familiar with Common Lisp, I suppose I am looking for something that works a bit like eval-when.

By the way, I am asking largely out of curiosity. I’m aware that in general one should not need to perform such a check :slight_smile:

Marked As Solved

hst337

hst337

compiling? = is_list(Process.get(:elixir_module_binaries))
But as @hauleth pointed out, difference between runtime and compile time is ephemeral. Compilation can happen in runtime, and anything can be called during compilation

Also Liked

kip

kip

ex_cldr Core Team

I use the following code in ex_cldr to detect if Elixir is compiling. The mechanism changed from Elixir 1.11, hence the conditional check:

  def compiling? do
    # TODO: When we depend on Elixir v1.11+ only, remove function_exported and elixir_compiler_pid
    process_alive?(:can_await_module_compilation?) ||
      process_alive?(:elixir_compiler_pid)
  end

  defp process_alive?(:can_await_module_compilation?) do
    Code.ensure_loaded?(Code) &&
      function_exported?(Code, :can_await_module_compilation?, 0) &&
      apply(Code, :can_await_module_compilation?, [])
  end

  defp process_alive?(name) do
    case Process.get(name) do
      nil -> false
      pid when is_pid(pid) -> true
    end
  end
josevalim

josevalim

Creator of Elixir

Please do not do this:

This is relying on internal compiler behaviour. Use the suggestions from @kip instead, which uses public APIs. :slight_smile:

dimitarvp

dimitarvp

That distinction doesn’t change anything he said though, you can still generate a module at runtime and compile it and for it what is happening will be “compile time”. You really should revise what you really want to achieve with this and consider other ways, this can very easily bite you in the rear in the most inopportune moment in the future.

hauleth

hauleth

The problem is that it is pretty hard to differentiate between “compile time” and “run time” as “compile time” is “run time with saving created modules to .beam files”.

You can check __CALLER__.function to detect whether macro was called within function body or outside of it.

mudasobwa

mudasobwa

Creator of Cure

BEAM does not create files on its own, Elixir and Erlang compiler do if run under some special conditions (e. g. from the command line.)

If you are compiling files manually, you are responsible for persisting them, if you wish. Here I do it, because Common Test needs tests to be available as beams.

Basically, it’s

{module, code} = Code.compile_file(file)
beam = Path.join(Path.dirname(file), to_string(module) <> ".beam")
:ok = File.write!(Path.join(Path.dirname(file), to_string(module) <> ".beam"), code)

Where Next?

Popular in Questions Top

bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
Mooodi
Given a string, how can I get access to its character by index? Enum.at("my_string", 2) doesn't work. Or rather, not char, but a substr...
New

Other popular topics Top

yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 42633 214
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New

We're in Beta

About us Mission Statement