Generating a macro call from a macro with the macro name as a symbol

Hello @awiersdorf, and welcome to the Julia community!

Your initial implementation was almost right, with one small mistake. The Expr constructor expects the arguments of the expression to be passed in splatted form, not as a single list. So with a simple modification, i.e., just remove the brackets, we can make your solution work:

macro make_time_call(expr)
  time_macro = Symbol("@time")
  return Expr(:macrocall, time_macro, LineNumberNode(1), 42)
end

julia> @make_time_call 42
  0.000001 seconds
42

That being said, I would probably pass __source__ instead of LineNumbeNode(1) as the first argument, like so:

macro make_time_call(expr)
  time_macro = Symbol("@time")
  return Expr(:macrocall, time_macro, __source__, 42)
end

HTH!

2 Likes