How to create a type from Symbol in a macro


#1

module X
   export MM
   struct MM
   end
end
using X
Base.@pure get_module(::Type{T}) where T = T.name.module

macro mod_check(sym)
     amod = get_module(Type(sym))
end

@mod_check MM

My problem is to create a type from Symbol in the macro?
How can i do that?
Thanks


#2

eval, but you should really be retuning expressions from macros instead of values.


#3

Any side effect of eval for using Type Creation from Symbol?
What should i be aware of?
Thanks


#4

Why do you want this to be a macro?

Macros are called at compile-time. Functions are compiled once with only the types of the arguments known at compile-time, not the values. The global scope would have the values. So if what you’re evaling is based on the values of things, I would expect this to fail if you put it in a function. Things like that will trip you up. You really should only use macros to generate expressions, and use functions to return values.


#5

I am developing a trait system where i parse some super traits(more than one), here is an example:

@mixin MyMixin{T,N}(ST2,ST3) <: ST1
  #stuff goes here
end

I look up info for super traits like ST1 from a toptable which makes addressing using module info and then the name of the type. You can think of it as:

toptable[MODULE][NAME] , eg: toptable[XX][ST1]

In the mixin macro, i need to have access to the module where ST1 is defined. That’s why.
Returning a value is for the sake of a simple example, i am using the value in mixin macro.
Thanks


#6

You need to return an escaped expression that does what you want at run-time:

julia> macro mod_check(sym::Symbol)
            :(get_module(Type($sym))) |> esc
       end
@mod_check (macro with 1 method)

julia> @mod_check MM
X

#7

Don’t esc the whole thing. esc only user input.


#8

I was trying to find it in compile time (macro time) . That’s why i was using a pure function.
Thanks