>> I can get the module of an exported method like so:
>> ```
>> julia> module BB 
>>        export B2, cc, f
>>        type B2
>>            a
>>        end
>>        f(x) = x+3
>>        cc = 5
>>        end
>>
>> julia> using BB
>>
>> julia> Base.function_module(f)
>> BB
>> ```
>> How can I do the same for the datatype `B2` and the variable `cc`?  (as
>> a bonus, what about macros?)
>
> For the datatype it is:
> julia> B2.name.module
>
> For variable bindings, Julia knows about it, as it displays a warning:
>
> julia> cc = 1
> Warning: imported binding for cc overwritten in module Main
>
> This originates from the function `jl_get_binding_wr` in `src/module.c`,
> which shows that a binding as a `owner`.  I'll try and figure out how to
> get to it.
>
> For marcos it seems impossible to get hold of them without them being
> evaluated.

For posterity here a method to find the origin of variable bindings.
Adding to module.c:
```
// return module of binding
DLLEXPORT jl_module_t *jl_get_module_of_binding(jl_sym_t *var)
{
    jl_binding_t *b = (jl_binding_t*)ptrhash_get(&jl_current_module->bindings, 
var);
}
```

and defining in reflection.jl:
```
function binding_module(var::Symbol)
    if isdefined(var) # this returns true for 'used' bindings
        mod = ccall(:jl_get_module_of_binding, Any, (Any,), var)
    else
        error("Symbol $var is not bound in the current module 
$(current_module()) and not exported in any 'used' module.")
    end
end

macro binding_module(var)
    :(binding_module(symbol($(string(var)))) )
end
```
(is there a better way to write that macro? I.e. how to get to the
Symbol of var?)


Now I can do:
```
julia> Base.@binding_module isa
Core

julia> module B3
       export b3, t
       b3 = 5
       t() = 5
       end

julia> Base.@binding_module t
ERROR: Symbol t is not bound in the current module Main and not exported in any 
'used' module.
 in error at error.jl:21
 in binding_module at reflection.jl:171

julia> using B3

julia> Base.@binding_module t
B3

julia> b = B3.b3
5

julia> Base.@binding_module b
Main

julia> Base.@binding_module b3
B3
```

Reply via email to