Returning module from a macro: why do we need :toplevel?

This may have worked in the early days, and as claimed here worked in Julia 1.4:

macro mymodule(name)
    modname = esc(name)
    return :(module $modname end)
end
@mymodule MyMod

But then it didn’t work in 1.5, and doesn’t work now.

The only way I know to make that work is to wrap the returned Expr in a :toplevel Expr:

macro mymodule(name)
    modname = esc(name)
    return Expr(:toplevel, :(module $modname end))
end
@mymodule MyMod

Why is this? I can @macroexpand the original, and it doesn’t appear to be hiding the module in some block or anything. Why isn’t the first version allowed? Is there something better I should be doing?

1 Like