tomekowal
I’d like to understand macro expansion rules, so I created this piece of code:
lib/my_macro.ex:
defmodule MyMacro do
defmacro print_module_attribute(attribute) do
IO.inspect "ATTRIBUTE:"
IO.inspect attribute
IO.inspect "EXPANDED VALUE"
IO.inspect Macro.expand attribute, __CALLER__
quote do
nil
end
end
end
lib/main.ex
defmodule Main do
require MyMacro
@my_attr :asdf
MyMacro.print_module_attribute(@my_attr)
def in_function do
MyMacro.print_module_attribute(@my_attr)
end
end
When running mix compile, I get the following output:
Compiling 2 files (.ex)
"ATTRIBUTE:"
{:@, [line: 4], [{:my_attr, [line: 4], nil}]}
"EXPANDED VALUE"
{:with, [],
[{:<-, [],
[{:when, [],
[{{:_, [], Kernel}, {:doc, [counter: -576460752303423485], Kernel}},
false]},
{{:., [],
[{:__aliases__, [alias: false, counter: -576460752303423485], [:Module]},
:get_attribute]}, [],
[{:__MODULE__, [counter: -576460752303423485], Kernel}, :my_attr,
[{:{}, [], [Main, :__MODULE__, 0, [file: "lib/main.ex", line: 4]]}]]}]},
[do: {:doc, [counter: -576460752303423485], Kernel}]]}
"ATTRIBUTE:"
{:@, [line: 6], [{:my_attr, [line: 6], nil}]}
"EXPANDED VALUE"
:asdf
Generated macro_problem app
It is a little bit surprising to me. When I call the macro in the module scope, it can’t expand the module attribute but when I call it from the function scope it can.
I wonder why is that? I am guessing that there are multiple expansion phases and compiler firstly expands the macro in module scope, secondly module attributes and thirdly function definitions.
However, defmodule and def are macros themselves so I am not sure if my theory makes sense.
Could you point me to a piece of documentation that explains it in details?
Trending in Questions
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
Hello,
I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
Hi everyone,
I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding.
I sta...
New
Documentation
While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
So my question is quite simple and i have found no conclusive answer on forum, google or AI.
Should we use :erlang.float for Integer to ...
New
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New
Other Trending Topics
Edit: 2026 May 15 - This post is archived.
Mob is alive!!
Main docs: mob v0.7.11 — Documentation
A bit of explanation for the slightly c...
New
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
New
Hi there! We created Gust: A task orchestrator inspired by Airflow.
For those who have never heard about Aiflow, it’s a Python-based wor...
New
Hi everyone!
The first release candidate for the Expert language server project is now available!
We’ve published a press release detai...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #ai
- #elixirconf-us
- #blog-post
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #elixirconf-eu
- #metaprogramming
- #hex










Showing Posts 1 to 10- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
LostKobrakai
Module attributes are macros as well: Kernel — Elixir v1.20.2 and It seems one case does expand to what the
@/1macro expands to in terms of AST, while the other seems to expand to the result value. The difference might come from the difference between howdefmodulehandles it’sdo: blockvs. what thedefmacro does with it.tomekowal
Can you elaborate on the difference between handling
do: blockin both? Is it documented somewhere or is it just a wild guess like mine?LostKobrakai
There are differences like this one, but I’m not sure if they are really related to what you’re seeing:
josevalim
I believe the information you are missing is that
defis a macro that stores some AST to be expanded and evaluated. So when a function body is expanded, the module body has been expanded and executed.You can imagine your module, after expansion, becomes this:
Generally speaking, we should avoid doing work inside expansion.
And the reason why we delay expanding function bodies is because we don’t want to expand them if they are not meant to be compiled. Imagine you wrap your functions in an
ifblock that does not evaluate to true. By postponing it, we avoid doing unnecessary work. The late expansion is also what allows dynamic definitions.7stud
In another post, Jose Valim stated that all macros are expanded in order–before any executable code contained in a macro is executed. After all the macros have been expanded, then any executable code in each macro is executed. As a result, inside the macro expansions that follow the macro
@my_attr :whatever, the value:whateverwill not have been set yet (by the executable code contained in the@macro), so the subsequent macro expansions use the value nil.So the def macro is expanded at compile time, but the macros inside a def are not? Are you saying that the macros found inside a def are not expanded until the function is actually called at runtime?
In
Metaprogramming Elixiron p. 13 it says:The whole reason we programmers buy metaprogramming books is to learn the details not provided in the guides. In
Metaprogramming Elixir, there is no mention of the delayed evaluation of macros inside a def.tomekowal
defmacros need to expand at compile time. The compilation has a couple of phases and module attributes are available only after the compilation finished. If I understood Jose’s answer correctly, it works like this:require MyMacromakes sure thatMyMacromodule is already fully compiled@my_attr: :asdfbecomes “hey! register this attribute when evaluating final AST”MyMacro.print_module_attribute(@my_attr); at current point, attributes are not calculated (it prints “ATTRIBUTE: …” and "EXPANDED VALUE: "defmacro but it is kind of special. It usesMacro.escapeunder the hood so it is not yet fully expanded. Again, it is something likeregister that AST under that function namenilso nothing happens)I hope I get it right now
I’d love to see this mechanism explained in greater detail in “Metaprogramming Elixir”!
7stud
Yes! And another thing the book omits: ALL the differences between
bind_quoted()andunquote(), which is something that really tripped me up. For instance,bind_quoted()does NOT make the specified variables available inside adefin the quote block, whereunquote()does. I don’t think I’ll ever usebind_quoted()because of that feature. The book makes it seem likebind_quoted()is a drop in replacement forunquote(), whereas, as far as I can tell,bind_quoted()is merely equivalent to:I see no reason to use
bind_quoted()when it can cause so much pain when used as a drop in replacement forunquote(). I’ll just use the longcut above, so that I’ll know what’s going on.LostKobrakai
The problem here is not that bind_quoted is not working, but that unquote fragments within macros quote do need „two levels“ of unquoting (outside quote → inside quote and inside quote → inside function). That‘s exactly the place you even need bind_quoted to resolve the ambiguity of which task unquote is fulfilling.
josevalim
I believe @sasajuric talks about this in his series but it has been a while since I last read it: The Erlangelist - Understanding macros, part 1
bind_quoted actually disables unquoting for the current
quote, this is mentioned in the docs. There are actual use cases for it, such as handling two level of unquotes, as mentioned by @LostKobrakai.7stud
I’m not sure what you are trying to say there, but I don’t need two levels of unquoting here: