Trouble with macro expression escaping

This code:

macro mymacro(ast)
    println("ast outside = ", ast, "---\n")
    :(function generated()
        println("ast inside = ", $ast, "---\n")
    end
    )
end

@mymacro function func()
    return 123
end

generated()

outputs:

ast outside = function func()
#= /home/volker/Sync/DatenVolker/UNI/Masterarbeit/src/juliatest.jl:23 =#
#= /home/volker/Sync/DatenVolker/UNI/Masterarbeit/src/juliatest.jl:24 =#
return 123
end—

ast inside = #343#func—

How can I make it output

ast outside = function func()
#= /home/volker/Sync/DatenVolker/UNI/Masterarbeit/src/juliatest.jl:23 =#
#= /home/volker/Sync/DatenVolker/UNI/Masterarbeit/src/juliatest.jl:24 =#
return 123
end—

ast inside = function func()
#= /home/volker/Sync/DatenVolker/UNI/Masterarbeit/src/juliatest.jl:23 =#
#= /home/volker/Sync/DatenVolker/UNI/Masterarbeit/src/juliatest.jl:24 =#
return 123
end—

Ok. That much furious with julia but care to ask. I would love to answer but you can find answer in the documentation.

2 Likes

The documentation did not help me, but this code does exactly what I want:

struct AstWrapper
    inner::Expr
end

macro mymacro(ast)
    println("ast outside = ", ast, "---\n")
    wast = AstWrapper(ast)
    :(function generated()
        println("ast inside = ", $wast.inner, "---\n")
    end
    )
end

@mymacro function func()
    return 123
end

generated()

I think the canonical solution to this is to use a QuoteNode or Meta.quot:

macro mymacro(ast)
    println("ast outside = ", ast, "---\n")
    :(function generated()
        println("ast inside = ", $(QuoteNode(ast)), "---\n")
    end
    )
end
2 Likes