5

For some reason, I had to put quote...end block in the macro and ex is generated programmatically. This code works.

macro addsum_out()
  quote
    ex = :(x+y)
    sum(eval(ex))
  end
end

x = [1 1 1]
y = [2 2 2]

z2 = @addsum_out

When the macro is put inside a module, it no longer works:

module MyModule

export @addsum

macro addsum()
  quote
    ex = :(x+y)
    sum(eval(ex))
  end
end

end

using MyModule
x = [1 1 1]
y = [2 2 2]    
z = @addsum

It says:

ERROR: LoadError: UndefVarError: x not defined

I think I should put esc somewhere, to evaluate the expression ex in the main scope outside the module. What should I handle this?

2
  • 4
    eval should not be used in macros. What are you trying to do? Commented Feb 17, 2017 at 14:34
  • 2
    eval operates at module-global scope. Look at macroexpand( :(@addsum) ) and notice the MyModule.eval. Anyway, it is completely unnecessary. You should return esc(:(x + y) ) instead. Commented Feb 17, 2017 at 16:47

1 Answer 1

5

The problem here is that a macro (inside a module) referencing x will look for x in that module, e.g. MyModule.x

This is part of macro hygiene.

To prevent macro hygiene from happening, you need to esc(x) -- that means it will use whatever x is in-scope at the call-site.

Your complete solution might look like:

macro addsum_out()
  quote
    esc(x) + esc(y)
  end
end

or more concisely:

macro addsum_out()
  :(  esc(x) + esc(y)  )
end

Note that this is slightly different from doing esc( :(x+y) ) which would be a escaping the + function also. i.e. the module containing this macro might contain an overload for +, and if you want to use this then don't escape the +, otherwise do!

There is a little discussion about this subject in a guide I put together:
https://github.com/p-i-/MetaGuideJulia/wiki#example-swap-macro-to-illustrate-esc

Sign up to request clarification or add additional context in comments.

2 Comments

You mean :( $(esc(:x)) + $(esc(:y)) ).
Alternatively, you can use esc(Expr(:call, +, :x, :y)).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.