vshesh

vshesh

Composing macros (using a macro inside another macro)

I’m trying to use one macro inside another macro and running into issues:

defmodule Test do
  defmacro somemacro(arg1, do: block) do
    quote do
      defmodule unquote(arg1) do 
        def unquote(arg1), do: 1
        unquote_splicing(elem(block, 2))
      end
    end
  end

  defmacro othermacro(arg2, arg1, do: block) do
    __MODULE__.somemacro arg1, do: quote do
      def unquote(arg2), do: 2
    end
  end
end

I get that I can’t unquote inside othermacro so how do I do this?
Another try:

defmodule Test do
  defmacro somemacro(arg1, do: block) do
    quote do
      defmodule unquote(arg1) do 
        def unquote(arg1), do: 1
        unquote_splicing(elem(block, 2))
      end
    end
  end

  defmacro othermacro(arg2, arg1, do: block) do
     newblock = quote do
       def unquote(arg2), do: 2
     end
     __MODULE__.somemacro arg1, do: newblock
  end
end
ERROR: you must require Test before invoking the macro Test.somemacro/2

requiring Test within Test causes another error:

(CompileError) you are trying to use the module AEnum which is currently being defined.

This may happen if you accidentally override the module you want to use. For example:

    defmodule MyApp do
      defmodule Supervisor do
        use Supervisor
      end
    end

In the example above, the new Supervisor conflicts with Elixir's Supervisor. This may be fixed by using the fully qualified name in the definition:

    defmodule MyApp.Supervisor do
      use Supervisor
    end

Basically othermacro is the same as somemacro except it adds some extra functions to the module
I am trying to use the do block to make a composition of the bits of the module … any help welcome

Most Liked

al2o3cr

al2o3cr

Removing the __MODULE__. from othermacro fixes the require issue, but exposes a bigger problem:

defmodule Test do
  defmacro somemacro(arg1, do: block) do
    quote do
      defmodule unquote(arg1) do 
        def unquote(arg1), do: 1
        unquote_splicing(elem(block, 2))
      end
    end
  end

  defmacro othermacro(arg2, arg1, do: block) do
    newblock = quote do
      def unquote(arg2), do: 2
    end

    somemacro arg1, do: newblock
  end
end

which fails with:

** (ArgumentError) expected a list with quoted expressions in unquote_splicing/1, got: nil
    (elixir 1.11.2) src/elixir_quote.erl:185: :elixir_quote.argument_error/1
    (elixir 1.11.2) src/elixir_quote.erl:166: :elixir_quote.list/2

This happens because when othermacro calls somemacro, the value somemacro sees in block is {:newblock, [line: 17], nil}.

One way to avoid this problem is to keep the defmacro parts simple and depend on plain functions to generate the actual AST fragments:

defmodule Test do
  defmacro somemacro(arg1, do: block) do
    # wrapped block in a list because unquote_splicing expects a list of quoted expressions
    build_ast(arg1, [block])
  end

  defmacro othermacro(arg2, arg1, do: block) do
    newblock = quote do
      def unquote(arg2)(), do: 2
    end

    # the old code didn't use block (?) 
    build_ast(arg1, [block, newblock])
  end

  defp build_ast(arg1, block) do
    quote do
      defmodule unquote(arg1) do 
        def unquote(arg1)(), do: 1
        unquote_splicing(block)
      end
    end
  end
end

defmodule FooMod do
  require Test

  Test.othermacro(:foo, :bar, do: "not used")
end

BUT BEWARE SOME GOTCHAS

The module defined by Test.somemacro is not nested - so in the example, it generates a top-level module named :bar:

iex(26)> :"Elixir.FooMod.bar".foo
** (UndefinedFunctionError) function :"Elixir.FooMod.bar".foo/0 is undefined (module :"Elixir.FooMod.bar" is not available)
    :"Elixir.FooMod.bar".foo()

iex(26)> :bar.foo                
2

This may not be what you want.

Last Post!

vshesh

vshesh

Right this makes sense it’s about what’s there at compile time.
I guess when othermacro is compiled somemacro is already expanded so there’s no opportunity to evaluate the unquote.
In that case though, shouldn’t this work?

defmodule Test do
  defmacro somemacro(arg1, do: block) do
    quote do
      defmodule unquote(arg1) do 
        def unquote(arg1), do: 1
        unquote(block)
      end
    end
  end

  defmacro othermacro(arg2, arg1, do: block) do
    somemacro arg1 do
      def unquote(arg2), do: 2
      unquote(block)
    end
  end
end

That should expand to an AST that has further unquote definitions in it which are evaluated in the context of othermacro, right? (this isn’t right, it throws an error). I guess what I want to do is quote an unquote operation, so that the expanded macro has an unquote operation in it? Not sure how to do that.

I don’t understand how using functions helps - it’s the same issue where I want to compose ASTs. So I want, ideally, to have a function that returns an AST and then another function that adds some extra stuff to that AST. because there is no way to do that directly (is there some AST function I don’t know about), I’m left with composing macros.

Is this what Macro.escape is for? I can define the value of the block and escape it into the macro.

defmodule Test do
  defmacro somemacro(arg1, do: block) do
    quote do
      defmodule unquote(arg1) do 
        def unquote(arg1), do: 1
        unquote(block)
      end
    end
  end

  defmacro othermacro(arg2, arg1, do: block) do
    newblock = quote do
      def unquote(arg2), do: 2
      unquote(block)
    end
    somemacro arg1, do: Macro.escape(newblock)
  end
end

I end up with an invalid quoted expression though

** (CompileError) iex: invalid quoted expression: {:module, :one, <<70, 79, 82, 49, 0, 0, 4, 176, 66, 69, 65, 77, 65, 116, 85, 56, 0, 0, 0, 127, 0, 0, 0, 14, 3, 111, 110, 101, 8, 95, 95, 105, 110, 102, 111, 95, 95, 10, 97, 116, 116, 114, 105, 98, 117, 116, 101, ...>>, {:{}, [], [:__block__, [], [{:{}, [], [:def, [context: Test, import: Kernel], [:two, [do: 2]]]}, {:{}, [], [:__block__, [], []]}]]}}

Please make sure your quoted expressions are made of valid AST nodes. If you would like to introduce a value into the AST, such as a four-element tuple or a map, make sure to call Macro.escape/1 before
    expanding macro: Test.othermacro/3
    iex:31: (file)

Where Next?

Popular in Questions Top

rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
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
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
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
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
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 130286 1222
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 54006 488
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
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
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

We're in Beta

About us Mission Statement