nmichel

nmichel

Module aliasing in macros

Hi

There is something I don’t get about macros, modules and aliasing.
Consider the following code snippets.

Module Foo exports macro show/1 that just log the received AST fragment on standard output.

defmodule Foo do
    defmacro show(frag) do
        IO.puts "#{inspect frag}"
        frag
    end
end

Then consider the following two useless modules Outer and Outer.Inner.

defmodule Outer do
    defmodule Inner do
        def foo do
            :foo
        end
    end
end

Now lets play with aliasing.

defmodule Test do
    import Foo

    alias Outer, as: A
    alias Outer.Inner, as: B
    alias A.Inner, as: C
    
    show A
    show B
    show C
    show C.foo()
    
    ast = quote do: A
    IO.puts "ast #{inspect ast}"
end

Here is the console log when I compile the code.

iex(1)> c("./test/demo.ex")
{:__aliases__, [counter: 0, line: 23], [:A]} # No aliasing info
{:__aliases__, [counter: 0, line: 24], [:B]}
{:__aliases__, [counter: 0, line: 25], [:C]}
{{:., [line: 26], [{:__aliases__, [counter: 0, line: 26], [:C]}, :foo]}, [line: 26], []}
ast {:__aliases__, [alias: Outer], [:A]} # quote => Aliasing info !
[Test, Outer, Outer.Inner, Foo]
iex(2)> 

What puzzles me, is that in show/1 macro calls, module fragments do not hold any aliasing information, while when quoted, it does.

Why don’t I have aliasing information during macro expansion ?

Many thanks !

Nicolas -

Most Liked

nmichel

nmichel

Hi,

I pursued my investigations further, and modified the Foo.show/1 function as follow.

defmodule Foo do
    defmacro show(frag = {:__aliases__, _, refs}) do
        resolved = Macro.expand(frag, __CALLER__)
        IO.puts """
        Alias
        frag \t #{inspect frag}
        resolved #{inspect resolved}
        """
        frag
    end

    defmacro show(frag = {{:., _, [path, target]}, _, _}) do
        resolved = Macro.expand(path, __CALLER__)
        IO.puts """
        Call
        path \t #{inspect path}
        resolved #{inspect resolved}#{inspect target}
        """
        frag
    end
end

Basically I catch fragments bearing aliasing information to make some experiments.

Here is the output

Alias
frag     {:__aliases__, [counter: 0, line: 38], [:A]}
resolved Outer

Alias
frag     {:__aliases__, [counter: 0, line: 39], [:B]}
resolved Outer.Inner

Alias
frag     {:__aliases__, [counter: 0, line: 40], [:C]}
resolved Outer.Inner

Call
path     {:__aliases__, [counter: 0, line: 41], [:C]}
resolved Outer.Inner:foo

ast {:__aliases__, [alias: Outer], [:A]}

We can see that, though fragments do not bear aliasing information, Macro.expand resolves aliases at compile time.

Cheers

Nicolas -

P.S. The question may rise of knowing WHY I needed to have those resolved symbols. Well, I wanted to be able to take some decisions based on the knowledge that a function is exported by a certain module … it proved to be a wrong way, but the underlying purely technical is still interesting :slight_smile:

Where Next?

Popular in Questions Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
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
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
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
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

Other popular topics Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
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
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
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement