Returning a module expression from a macro to be evaluated at a different module

Hi Fellows,

I was trying to return a module expression to be evaluated at the top module of where i do the macrocall. Here is an example:

module X
  export @cmodule
  is_module(a) = false
  is_module(e::Expr) = e.head == :module

  function make_top_level(e::Expr) 
      if e.head == :block && any( is_module.(e.args) )
        Expr(:toplevel, e.args...)
      elseif e.head == :block
        Expr(:block, make_top_level.(e.args)...)
      else
        e
      end
  end


  function create_module(name)
           quote
               module $name
               end
           end |> make_top_level
   end

   macro cmodule(name)
   		esc(create_module(name))
   end

   module Y
   		module Z
   			using X
   			#here if i do the following the new module will be X.Y.Z.MDD, but i want it to be X.MDD, How can i do that?
   			@cmodule MDD
   		end
   end
end

You can’t do that. A macro cannot do more than you could by typing code. And you cannot define a module in Y and expect it to be in X. You could eval into any other module, as you found out in the other thread. But as stated there, that is bad style. I’m pretty sure that there is another solution to you problem though…

1 Like