I want to write a macro in Julia that generates a number of macros
@register_attribute foo
should generate the macros
@set_foo
@get_foo
which in turn should be defined as
@set_foo x 5 == set_attr!(x, :foo, 5)
I've managed to get the first part of this down fine, however @macroexpand shows that the inner variable x is not escaped properly, resulting in UndefVarErrors if I call the method with a local variable.
@macroexpand @set_foo x 5 =
:(Main.set_attr!(Main.x, (Symbol)("foo"), 5))
whereas what I want is
@macroexpand @set_foo x 5 =
:(set_attr!(x, (Symbol)("foo"), 5))
My code is
macro register_attribute(name)
setn = Symbol("set_", string(name))
getn = Symbol("get_", string(name))
arg = gensym()
arg2 = gensym()
nsym = string(name)
return Expr(:block,
esc(:(
macro $(setn)($arg, $arg2)
:(set_attr!($$arg, $$Symbol($$nsym), $$arg2))
end)
),
esc(:(
macro $(getn)($arg, $arg2)
:(get_attr!($$arg, $$Symbol($$nsym), $$arg2))
end)
))
e2
end