thojanssens1

thojanssens1

Why is __after_compile__/2 called before __before_compile__/1?

defmodule Bar do
  @after_compile __MODULE__

  defmacro __before_compile__(_env) do
    IO.inspect("#{__MODULE__}.__before_compile__")
  end

  def __after_compile__(_env, _bytecode) do
    IO.inspect("#{__MODULE__}.__after_compile__")
  end
end

defmodule Foo do
  require Bar

  @before_compile Bar
  @after_compile __MODULE__

  def __after_compile__(_env, _bytecode) do
    IO.inspect("#{__MODULE__}.__after_compile__")
  end
end

Will print:

“Elixir.Bar.after_compile
“Elixir.Bar.before_compile
“Elixir.Foo.after_compile
[Bar, Foo]

Why is after_compile called before before_compile for the Bar module?

Marked As Solved

NobbZ

NobbZ

  1. Bar is compiled, you see its output of Bar.__after_compile__
  2. Foo is going to get compiled, it calls Bar.__before_compile__, you see the output Bar.__before_compile__, because __MODULE__ is Bar in that context. You wan’t to check env.mod to see the callers module.
  3. Foo gets actuially compiled, its after compile gets called and you see its Foo.__after_compile__.

Also Liked

ityonemo

ityonemo

Because you are compiling Foo after Bar.

LostKobrakai

LostKobrakai

Baz is already compiled when used in MyApp. MyApp is not yet compiled. In macros it’s important to be aware if you‘re working in the context of the macro (__MODULE__ is the module with the macro definition) or if you‘re working on the AST of the macros result, which is effectively becoming part of the module calling the macro (__MODULE__ refers to the module calling the macro).

NobbZ

NobbZ

Again, you need to look into the callers environment. Macros get passed __CALLER__ as a magic variable, so you probably want to Module.register_attribute(__CALLER__.mod, :attr, []) or in this case even more appropriate, as you do not make it accumulating or persistent:

defmacro __using__(_opts) do
  quote do
    @attr []
  end
end

Or instead of the empty list use any other default value you prefer.

Beeing aware of the current context you are in is important for macros.

Perhaps give Metaprogramming Elixir by @chrismccord a read? I only skimmed about the first quarter of it, but it helped me to understand macros enough for my usecase.

ityonemo

ityonemo

defmodule A do
  defmacro __using__(opts) do
    otp_app = opts[:otp_app]      # this gets set to :foo
    quote do                           # note 'use' is called by B, so the next two lines live in B.
      @otp_app unquote(otp_app)  # becomes @otp_app :foo
      @before_compile A 
    end
  end

  defmacro __before_compile__(_) do
    __CALLER__.module
    |> IO.inspect(label: "module")
    |> Module.get_attribute(:otp_app)
    |> IO.inspect(label: "otp app")
    quote do end
  end
end

defmodule B do
  use A, otp_app: :foo
end

compile-time output:

module: B
otp app: :foo

If it’s clearer, this is effectively equivalent:

defmodule A do
  defmacro __using__(opts) do
    otp_app = opts[:otp_app]
    quote do
      @otp_app unquote(otp_app)
    end
  end

  defmacro __before_compile__(_) do
    __CALLER__.module
    |> IO.inspect(label: "module")
    |> Module.get_attribute(:otp_app)
    |> IO.inspect(label: "otp app")
    quote do end
  end
end

defmodule B do
  use A, otp_app: :foo
  @before_compile A
end

Where Next?

Popular in Questions Top

srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
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
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
Codball
Mix format works fine if run from the cmd. I’ve followed this to facilitate the implementation into VSC which involves downloading an ext...
New

Other popular topics Top

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
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

We're in Beta

About us Mission Statement