Module Generation from macros


#1

I am trying to generate modules using a macro, but it keeps failing. I am not sure how to handle this.
EG.

julia> macro mymodule(name)
                quote
                  module ($name)
                  end
                end
              end
@mymodule (macro with 1 method)

julia> @mymodule Foo
ERROR: syntax: module expression not at top level

So Julia does not seem to want to accept this. However, I found and closed issues on that very same topic


#2

You can @eval the module to get around this.

julia> macro mymodule(name)
           quote
               @eval module $(esc(name))
               end
           end
       end
@mymodule (macro with 1 method)

julia> @mymodule Foo
Foo

julia> Foo
Foo

#3

Try:

macro mymodule(name)
  Expr(:toplevel,
    :(module ($name)
      end))
end

#4

@fengyang.wang Thank you! Your solution worked very nicely.
@MikeInnes Your solution worked for 0.5, but not 0.6, I am not sure why.


#5

The name (and in general, all user inputs) has to be escaped.