ContextualMacros.ContextualMacrosModule

ContextualMacros

GitHub Actions

ContextualMacros.jl is a package for implementing contextual macro expansion.

Examples

module MyAbstractMacroPackage
    using ContextualMacros
    @contextualmacro @f
end

module MyPackageA
    export @f, @context_a

    using ContextualMacros
    using ..MyAbstractMacroPackage: @f

    macro context_a(ex)
        ContextualMacros.expandwith(
            __module__,
            ex;
            f = ctx -> Expr(:call, +, ctx.args...),
        )
    end
end

module MyPackageB
    export @f, @context_b

    using ContextualMacros
    using ..MyAbstractMacroPackage: @f

    macro context_b(ex)
        ContextualMacros.expandwith(
            __module__,
            ex;
            f = ctx -> Expr(:call, *, ctx.args...),
        )
    end
end

using .MyPackageA
using .MyPackageB

(@context_a @f 1 2 3 4), (@context_b @f 1 2 3 4), (@context_b @context_a @f 1 2 3 4)

# output

(10, 24, 10)
ContextualMacros.defMethod
ContextualMacros.def(macroname::Symbol) -> f

Return a function callable as f(__source__, __module__, args...).

ContextualMacros.expandwithMethod
ContextualMacros.expandwith(module, expression; definitions...)

Macro-expand expression with contextual macro @f whose definition is given by definitions[:f].

Each value of definitions is a function that takes a single argument with a "context" object with (at least) following properties:

  • __module__::Module: module in which the macro is expanded
  • __source__::LineNumberNode: line at which the macro is expanded
  • args: arguments to the macro
ContextualMacros.withMethod
ContextualMacros.with(f; definitions...)

Run function f while using the definitions of the macros specified by definitions. See also expandwith.

ContextualMacros.@defMacro
ContextualMacros.@def @macroname

Define a contextual macro @macroname whose identity is solely determined by the name of the macro.

Unstable

This is an experimental API.