Julep: Taking multiple dispatch,export,import,binary compilation seriously

@jlperla was interested in having a macro for merging function definitions automatically.

https://github.com/chakravala/ForceImport.jl/issues/1

this is actually not that difficult to write a macro for so I created the @merge macro, but note that macros cannot be used for code generation, so the eval method must be called on the output of the macro.

Here is an example

julia> using ForceImport

julia> module Mod
           export fun
           fun(x) = x
       end
Mod

julia> using Mod

julia> eval(@merge fun(x::String) = String)
fun (generic function with 2 methods)

julia> fun(1)
1

julia> fun("1")
String

So with the eval(@merge fun...) macro, the Mod.fun method is automatically imported if necessary.

Here is the macro definition

macro merge(expr)
    if !( (expr.head == :function) | ( (expr.head == :(=)) &&
            (typeof(expr.args[1]) == Expr) && (expr.args[1].head == :call) ) )
        throw(error("ForceImport: $expr is not a function definition"))
    end
    fun = expr.args[1].args[1]
    return Expr(:quote,quote
        for name in names(current_module())
            try
                eval(ForceImport.imp($(string(fun)),name))
            end
        end
        eval($(Expr(:quote,expr)))
    end)
end

function imp(fun::String,name::Symbol)
    :(Symbol($fun) ∈ names($name) && (import $name.$(Symbol(fun))))
end
1 Like