How to use typespecs inside a macro?

Hello, if I get a typespecs from macro entry like this

field(:title, String.t())

I can use it like this:

  defmacro field(name, type, opts \\ []) do
    quote bind_quoted: [name: name, type: Macro.escape(type), opts: opts] do
      GuardedStruct.__field__(name, type, opts, __ENV__)
    end
  end

or

type = Macro.escape(type)

but if I want to use like this, I have an error:

  defmacro sub_field(name, _type, opts \\ [], do: block) do
    ast = register_struct(block, opts)
    type = Macro.escape(struct()) # struct() I have error for this

for example I want to skip macro _type and do it always struct() one.

The output is {:struct, [line: 521], []} when I print macro entry! how can I do it?

Thank you in advance

Macro.escape is a plain function, but you want to pass it the AST representation of struct().

You need to supply your own quote:

Macro.escape(quote do: struct())

# => 

{:{}, [], [:struct, [context: Elixir, imports: [{1, Kernel}, {2, Kernel}]], []]}
2 Likes