LukasKnuth
How do I unquote a sigil parameter to a macro?
Consider the following simple example:
defmodule Test.Foo do
defmacro foo(regex) do
IO.inspect(regex)
end
end
defmodule Test do
require Test.Foo
Test.Foo.foo(~r/test/)
end
{:sigil_r, [delimiter: "/", line: 10], [{:<<>>, [line: 10], ["test"]}, []]}
iex>
Here, the sigil passed to Test.Foo.foo becomes a quoted expression. When using the macro for code generation, one would simple call unquote/1 on arg and get the sigil representation again.
However, if I do this in the above example (IO.inspect(unquote(regex))), I get the following error:
warning: variable “regex” does not exist and is being expanded to “regex()”, please use parentheses to remove the ambiguity or change the variable name
macro_why.exs:3: Test.Foo
** (CompileError) macro_why.exs:3: undefined function regex/0 (there is no such import)
Note that I don’t have a quote block in my macro. The actual code I’m working on parses the AST directly into an internal representation, so there is no need to quote anything. This is whats kinda throwing me for a loop here.
Most Liked
benwilson512
Hey @LukasKnuth that isn’t how that works. You can think of quote and unquote as similar to "" and #{}. You can’t use #{} outside of a string "" it just doesn’t make any sense. And when you use unquote inside of quote it is not turning it “back into” a sigil, it’s still AST. AST is all there is at the macro level. It’s just interpolating that ast inside of other AST.
Can you show an example of the code you’re trying to get to work in general? Tangentially there is another thread about the use of ~p that is pretty similar Using `~p` dynamically inside a macro - #5 by 0xG it may have some useful pointers for you.







