Skip to content

API Reference ​

Syntax Types ​

Convenient types for storing analysis results of a given Julia Expr, or for creating certain Julia objects easily. These types define some common syntax one would manipulate in Julia meta programming.

Expronicon.JLFunction Type
julia
mutable struct JLFunction <: JLExpr
JLFunction(;kw...)

Type describes a Julia function declaration expression.

Fields and Keyword Arguments

All the following fields are valid as keyword arguments kw in the constructor, and can be access via <object>.<field>.

The only required keyword argument for the constructor is name, the rest are all optional.

  • head: optional, function head, can be :function, :(=) or :(->).

  • name: optional, function name, can has type Nothing, Symbol or Expr, default is nothing.

  • args: optional, function arguments, a list of Expr or Symbol.

  • kwargs: optional, function keyword arguments, a list of Expr(:kw, name, default).

  • rettype: optional, the explicit return type of a function, can be a Type, Symbol, Expr or just nothing, default is nothing.

  • generated: optional, if this is a generated function.

  • whereparams: optional, type variables, can be a list of Type, Expr or nothing, default is nothing.

  • body: optional, function body, an Expr, default is Expr(:block).

  • line::LineNumberNode: a LineNumberNode to indicate the line information.

  • doc::String: the docstring of this definition.

Example

Construct a function expression

julia
julia> JLFunction(;name=:foo, args=[:(x::T)], body= quote 1+1 end, head=:function, whereparams=[:T])
function foo(x::T) where {T}
    #= REPL[25]:1 =#    
    1 + 1    
end

Decompose a function expression

julia
julia> ex = :(function foo(x::T) where {T}
           #= REPL[25]:1 =#    
           1 + 1    
       end)
:(function foo(x::T) where T
      #= REPL[26]:1 =#
      #= REPL[26]:3 =#
      1 + 1
  end)

julia> jl = JLFunction(ex)
function foo(x::T) where {T}
    #= REPL[26]:1 =#    
    #= REPL[26]:3 =#    
    1 + 1    
end

Generate Expr from JLFunction

julia
julia> codegen_ast(jl)
:(function foo(x::T) where T
      #= REPL[26]:1 =#
      #= REPL[26]:3 =#
      1 + 1
  end)
source
Expronicon.JLCall Type
julia
JLCall(func, args::Vector, kwargs::Maybe{Vector})
JLCall(; func, args=[], kwargs=nothing)

Represents a Julia function call expression.

Fields and Keyword Arguments

All the following fields are valid as keyword arguments kw in the constructor, and can be access via <object>.<field>.

  • func: the function being called

  • args: optional, function arguments, a list of Expr or Symbol.

  • kwargs: optional, function keyword arguments, a list of Expr(:kw, name, default).

source
Expronicon.JLStruct Type
julia
mutable struct JLStruct <: JLExpr

Type describes a Julia struct.

julia
JLStruct(;kw...)

Create a JLStruct instance.

Available Fields and Keyword Arguments

All the following fields are valid as keyword arguments kw in the constructor, and can be access via <object>.<field>.

The only required keyword argument for the constructor is name, the rest are all optional.

  • name::Symbol: name of the struct, this is the only required keyword argument.

  • ismutable::Bool: if the struct definition is mutable.

  • typevars::Vector{Any}: type variables of the struct, should be Symbol or Expr.

  • supertype: supertype of the struct definition.

  • fields::Vector{JLField}: field definitions of the struct, should be a JLField.

  • constructors::Vector{JLFunction}: constructors definitions of the struct, should be JLFunction.

  • line::LineNumberNode: a LineNumberNode to indicate the definition position for error report etc.

  • doc::String: documentation string of the struct.

  • misc: other things that happens inside the struct body, by definition this will just fall through and is equivalent to eval them outside the struct body.

Example

Construct a Julia struct.

julia
julia> JLStruct(;name=:Foo, typevars=[:T], fields=[JLField(;name=:x, type=Int)])
struct Foo{T}
    x::Int64
end

Decompose a Julia struct expression

julia
julia> ex = :(struct Foo{T}
           x::Int64
       end)
:(struct Foo{T}
      #= REPL[31]:2 =#
      x::Int64
  end)

julia> jl = JLStruct(ex)
struct Foo{T}
    #= REPL[31]:2 =#
    x::Int64
end

Generate a Julia struct expression

julia
julia> codegen_ast(jl)
:(struct Foo{T}
      #= REPL[31]:2 =#
      x::Int64
  end)
source
Expronicon.JLKwStruct Type
julia
mutable struct JLKwStruct <: JLExpr
JLKwStruct(;kw...)

Type describes a Julia struct that allows keyword definition of defaults. This syntax is similar to JLStruct except the the fields are of type JLKwField.

Fields and Keyword Arguments

All the following fields are valid as keyword arguments kw in the constructor, and can be access via <object>.<field>.

The only required keyword argument for the constructor is name, the rest are all optional.

  • name::Symbol: name of the struct, this is the only required keyword argument.

  • typealias::String: an alias of the JLKwStruct, see also the @option macro in Configurations.jl.

  • ismutable::Bool: if the struct definition is mutable.

  • typevars::Vector{Any}: type variables of the struct, should be Symbol or Expr.

  • supertype: supertype of the struct definition.

  • fields::Vector{JLField}: field definitions of the struct, should be a JLField.

  • constructors::Vector{JLFunction}: constructors definitions of the struct, should be JLFunction.

  • line::LineNumberNode: a LineNumberNode to indicate the definition position for error report etc.

  • doc::String: documentation string of the struct.

  • misc: other things that happens inside the struct body, by definition this will just fall through and is equivalent to eval them outside the struct body.

source
Expronicon.JLIfElse Type
julia
JLIfElse <: JLExpr
JLIfElse(;kw...)

JLIfElse describes a Julia if ... elseif ... else ... end expression. It allows one to easily construct such expression by inserting condition and code block via a map.

Fields and Keyword Arguments

All the following fields are valid as keyword arguments kw in the constructor, and can be access via <object>.<field>.

  • conds::Vector{Any}: expression for the conditions.

  • stmts::Vector{Any}: expression for the statements for corresponding condition.

  • otherwise: the else body.

Example

Construct JLIfElse object

One can construct an ifelse as following

julia
julia> jl = JLIfElse()
nothing

julia> jl[:(foo(x))] = :(x = 1 + 1)
:(x = 1 + 1)

julia> jl[:(goo(x))] = :(y = 1 + 2)
:(y = 1 + 2)

julia> jl.otherwise = :(error("abc"))
:(error("abc"))

julia> jl
if foo(x)
    x = 1 + 1
elseif goo(x)
    y = 1 + 2
else
    error("abc")
end

Generate the Julia Expr object

to generate the corresponding Expr object, one can call codegen_ast.

julia
julia> codegen_ast(jl)
:(if foo(x)
      x = 1 + 1
  elseif goo(x)
      y = 1 + 2
  else
      error("abc")
  end)
source
Expronicon.JLMatch Type
julia
JLMatch <: JLExpr

JLMatch describes a Julia pattern match expression defined by MLStyle. It allows one to construct such expression by simply assign each code block to the corresponding pattern expression.

Tip

JLMatch is not available in ExproniconLite since it depends on MLStyle's pattern matching functionality.

Example

One can construct a MLStyle pattern matching expression easily by assigning the corresponding pattern and its result to the map field.

julia
julia> jl = JLMatch(:x)
#= line 0 =#
nothing

julia> jl = JLMatch(:x)
#= line 0 =#
nothing

julia> jl.map[1] = true
true

julia> jl.map[2] = :(sin(x))
:(sin(x))

julia> jl
#= line 0 =#
@match x begin
    1 => true
    2 => sin(x)
    _ =>     nothing
end

to generate the corresponding Julia Expr object, one can call codegen_ast.

julia
julia> codegen_ast(jl)
:(let
      true
      var"##return#263" = nothing
      var"##265" = x
      if var"##265" isa Int64
          #= line 0 =#
          if var"##265" === 1
              var"##return#263" = let
                      true
                  end
              #= unused:1 =# @goto var"####final#264#266"
          end
          #= line 0 =#
          if var"##265" === 2
              var"##return#263" = let
                      sin(x)
                  end
              #= unused:1 =# @goto var"####final#264#266"
          end
      end
      #= line 0 =#
      begin
          var"##return#263" = let
                  nothing
              end
          #= unused:1 =# @goto var"####final#264#266"
      end
      (error)("matching non-exhaustive, at #= line 0 =#")
      #= unused:1 =# @label var"####final#264#266"
      var"##return#263"
  end)
source
Expronicon.JLFor Type
julia
JLFor <: JLExpr

Syntax type for Julia for loop.

source
Expronicon.JLField Type
julia
mutable struct JLField <: JLExpr
JLField(;kw...)

Type describes a Julia field in a Julia struct.

Fields and Keyword Arguments

All the following fields are valid as keyword arguments kw in the constructor, and can be access via <object>.<field>.

The only required keyword argument for the constructor is name, the rest are all optional.

  • name::Symbol: the name of the field.

  • type: the type of the field.

  • isconst: if the field is annotated with const.

  • line::LineNumberNode: a LineNumberNode to indicate the line information.

  • doc::String: the docstring of this definition.

source
Expronicon.JLKwField Type
julia
mutable struct JLKwField <: JLExpr

Type describes a Julia field that can have a default value in a Julia struct.

julia
JLKwField(;kw...)

Create a JLKwField instance.

Fields and Keyword Arguments

All the following fields are valid as keyword arguments kw in the constructor, and can be access via <object>.<field>.

The only required keyword argument for the constructor is name, the rest are all optional.

  • name::Symbol: the name of the field.

  • type: the type of the field.

  • isconst: if the field is annotated with const.

  • default: default value of the field, default is no_default.

  • line::LineNumberNode: a LineNumberNode to indicate the line information.

  • doc::String: the docstring of this definition.

source
Expronicon.NoDefault Type
julia
NoDefault

Type describes a field should have no default value.

source
Expronicon.no_default Constant
julia
const no_default = NoDefault()

Constant instance for NoDefault that describes a field should have no default value.

source
Expronicon.JLExpr Type
julia
abstract type JLExpr end

Abstract type for Julia syntax type.

source

Analysis ​

Functions for analysing a given Julia Expr, e.g splitting Julia function/struct definitions etc.

Expronicon.has_kwfn_constructor Function
julia
has_kwfn_constructor(def[, name = struct_name_plain(def)])

Check if the struct definition contains keyword function constructor of name. The constructor name to check by default is the plain constructor which does not infer any type variables and requires user to input all type variables. See also struct_name_plain.

source
Expronicon.has_plain_constructor Function
julia
has_plain_constructor(def, name = struct_name_plain(def))

Check if the struct definition contains the plain constructor of name. By default the name is the inferable name struct_name_plain.

Example

julia
def = @expr JLKwStruct struct Foo{T, N}
    x::Int
    y::N

    Foo{T, N}(x, y) where {T, N} = new{T, N}(x, y)
end

has_plain_constructor(def) # true

def = @expr JLKwStruct struct Foo{T, N}
    x::T
    y::N

    Foo(x, y) = new{typeof(x), typeof(y)}(x, y)
end

has_plain_constructor(def) # false

the arguments must have no type annotations.

julia
def = @expr JLKwStruct struct Foo{T, N}
    x::T
    y::N

    Foo{T, N}(x::T, y::N) where {T, N} = new{T, N}(x, y)
end

has_plain_constructor(def) # false
source
Expronicon.has_symbol Method
julia
has_symbol(ex, name::Symbol)

Check if ex contains symbol name.

source
Expronicon.is_datatype_expr Method
julia
is_datatype_expr(ex)

Check if ex is an expression for a concrete DataType, e.g where is not allowed in the expression.

source
Expronicon.is_field Method
julia
is_field(ex)

Check if ex is a valid field expression.

source
Expronicon.is_field_default Method
julia
is_field_default(ex)

Check if ex is a <field expr> = <default expr> expression.

source
Expronicon.is_for Method
julia
is_for(ex)

Check if ex is a for loop expression.

source
Expronicon.is_function Method
julia
is_function(def)

Check if given object is a function expression.

source
Expronicon.is_gensym Method
julia
is_gensym(s)

Check if s is generated by gensym.

Note

Borrowed from MacroTools.

source
Expronicon.is_ifelse Method
julia
is_ifelse(ex)

Check if ex is an if ... elseif ... else ... end expression.

source
Expronicon.is_kw_function Method
julia
is_kw_function(def)

Check if a given function definition supports keyword arguments.

source
Expronicon.is_literal Method
julia
is_literal(x)

Check if x is a literal value.

source
Expronicon.is_matrix_expr Method
julia
is_matrix_expr(ex)

Check if ex is an expression for a Matrix.

source
Expronicon.is_splat Method
julia
is_splat(ex)

Check if ex is a splat expression, i.e. :(f(x)...)

source
Expronicon.is_struct Method
julia
is_struct(ex)

Check if ex is a struct expression.

source
Expronicon.is_struct_not_kw_struct Method
julia
is_struct_not_kw_struct(ex)

Check if ex is a struct expression excluding keyword struct syntax.

source
Expronicon.is_tuple Method
julia
is_tuple(ex)

Check if ex is a tuple expression, i.e. :((a,b,c))

source
Expronicon.is_valid_typevar Method
julia
is_valid_typevar(typevar)

Check if the given typevar is a valid typevar.

Note

This function is based on this discourse post.

source
Expronicon.support_default Method
julia
support_default(f)

Check if field type f supports default value.

source
Expronicon.Variable Type
julia
struct Variable

Marks a Symbol as a variable. So that compare_expr will always return true.

source
Expronicon.assert_equal_expr Method
julia
assert_equal_expr(m::Module, lhs, rhs)

Assert that lhs and rhs are equal in m. Throw an ExprNotEqual if they are not equal.

source
Expronicon.compare_expr Method
julia
compare_expr([m=Main], lhs, rhs)

Compare two expression of type Expr or Symbol semantically, which:

  1. ignore the detail value LineNumberNode in comparision;

  2. ignore the detailed name of typevars declared by where;

  3. recognize inserted objects and Symbol, e.g :($Int) is equal to :(Int);

  4. recognize QuoteNode(:x) and Symbol("x") as equal;

  5. will guess module and type objects and compare their value directly instead of their expression;

Tips

This function is usually combined with prettify with preserve_last_nothing=true and alias_gensym=false.

This gives a way to compare two Julia expression semantically which means although some details of the expression is different but they should produce the same lowered code.

source
Expronicon.@test_expr Macro
julia
@test_expr <type> <ex>

Test if the syntax type generates the same expression ex. Returns the corresponding syntax type instance. Requires using Test before using this macro.

Example

julia
def = @test_expr JLFunction function (x, y)
    return 2
end
@test is_kw_fn(def) == false
source
Expronicon.@test_expr Macro
julia
@test_expr <expr> == <expr>

Test if two expression is equivalent semantically, this uses compare_expr to decide if they are equivalent, ignores things such as LineNumberNode generated Symbol in Expr(:curly, ...) or Expr(:where, ...).

Note

This macro requires one using Test to import the Test module name.

source
Expronicon.JLCall Method
julia
JLCall(ex::Expr)

Convert a Julia call expression to JLCall.

Examples

julia
ex = :(f(x, y; z=1))
jlcall = JLCall(ex)  # creates JLCall with func=:f, args=[:x, :y], kwargs=[:(z=1)]
source
Expronicon.JLFor Method
julia
JLFor(ex::Expr)

Create a JLFor from given Julia for loop expression.

Example

julia
julia> ex = @expr for i in 1:10, j in 1:j
           M[i, j] += 1
       end
:(for i = 1:10, j = 1:j
      #= REPL[3]:2 =#
      M[i, j] += 1
  end)

julia> jl = JLFor(ex)
for i in 1 : 10,
    j in 1 : j
    #= loop body =#
    begin
        #= REPL[3]:2 =#        
        M[i, j] += 1        
    end
end

julia> jl.vars
2-element Vector{Any}:
 :i
 :j

julia> jl.iterators
2-element Vector{Any}:
 :(1:10)
 :(1:j)
source
Expronicon.JLFunction Method
julia
JLFunction(ex::Expr)

Create a JLFunction object from a Julia function Expr.

Example

julia
julia> JLFunction(:(f(x) = 2))
f(x) = begin
    #= REPL[37]:1 =#    
    2    
end
source
Expronicon.JLIfElse Method
julia
JLIfElse(ex::Expr)

Create a JLIfElse from given Julia ifelse Expr.

Example

julia
julia> ex = :(if foo(x)
             x = 1 + 1
         elseif goo(x)
             y = 1 + 2
         else
             error("abc")
         end)
:(if foo(x)
      #= REPL[41]:2 =#
      x = 1 + 1
  elseif #= REPL[41]:3 =# goo(x)
      #= REPL[41]:4 =#
      y = 1 + 2
  else
      #= REPL[41]:6 =#
      error("abc")
  end)

julia> JLIfElse(ex)
if foo(x)
    begin
        #= REPL[41]:2 =#        
        x = 1 + 1        
    end
elseif begin
    #= REPL[41]:3 =#    
    goo(x)    
end
    begin
        #= REPL[41]:4 =#        
        y = 1 + 2        
    end
else
    begin
        #= REPL[41]:6 =#        
        error("abc")        
    end
end
source
Expronicon.JLKwStruct Type
julia
JLKwStruct(ex::Expr, typealias=nothing)

Create a JLKwStruct from given Julia struct Expr, with an option to attach an alias to this type name.

Example

julia
julia> JLKwStruct(:(struct Foo
           x::Int = 1
       end))
#= kw =# struct Foo
    #= REPL[39]:2 =#
    x::Int = 1
end
source
Expronicon.JLStruct Method
julia
JLStruct(ex::Expr)

Create a JLStruct object from a Julia struct Expr.

Example

julia
julia> JLStruct(:(struct Foo
           x::Int
       end))
struct Foo
    #= REPL[38]:2 =#
    x::Int
end
source
Expronicon.guess_module Method
julia
guess_module(m, ex)

Guess the module of given expression ex (of a module) in module m. If ex is not a module, or cannot be determined return nothing.

source
Expronicon.guess_type Method
julia
guess_type(m::Module, ex)

Guess the actual type of expression ex (of a type) in module m. Returns the type if it can be determined, otherwise returns the expression. This function is used in compare_expr.

source
Expronicon.gensym_name Method
julia
gensym_name(x::Symbol)

Return the gensym name.

Note

Borrowed from MacroTools.

source
Expronicon.@expr Macro
julia
@expr <type> <expression>

Return the expression in given type.

Example

julia
julia> ex = @expr JLKwStruct struct Foo{N, T}
           x::T = 1
       end
#= kw =# struct Foo{N, T}
    #= /home/roger/code/julia/Expronicon/test/analysis.jl:5 =#
    x::T = 1
end
source
Expronicon.@expr Macro
julia
@expr <expression>

Return the original expression object.

Example

julia
julia> ex = @expr x + 1
:(x + 1)
source
Expronicon.split_anonymous_function_head Method
julia
split_anonymous_function_head(ex::Expr) -> nothing, args, kw, whereparams, rettype

Split anonymous function head to arguments, keyword arguments and where parameters.

source
Expronicon.split_doc Method
julia
split_doc(ex::Expr) -> line, doc, expr

Split doc string from given expression.

source
Expronicon.split_field_if_match Function
julia
split_field_if_match(typename::Symbol, expr, default::Bool=false)

Split the field definition if it matches the given type name. Returns NamedTuple with name, type, default and isconst fields if it matches, otherwise return nothing.

source
Expronicon.split_function Method
julia
split_function(ex::Expr) -> head, call, body

Split function head declaration with function body.

source
Expronicon.split_function_head Method
julia
split_function_head(ex::Expr) -> name, args, kw, whereparams, rettype

Split function head to name, arguments, keyword arguments and where parameters.

source
Expronicon.split_kw_block_nothrow Method
julia
split_kw_block_nothrow(ex::Expr) -> nothing, args, kw, nothing, nothing

Split the argument list of (x; kw) -> body, which Julia parses as a block holding x and kw. The block also holds LineNumberNodes, which are ignored so that a block whose line numbers were removed is split too. Return nothing when ex is no such block.

source
Expronicon.split_struct Method
julia
split_struct(ex::Expr) -> ismutable, name, typevars, supertype, body

Split struct definition head and body.

source
Expronicon.split_struct_name Method
julia
split_struct_name(ex::Expr) -> name, typevars, supertype

Split the name, type parameters and supertype definition from struct declaration head.

source
Expronicon.uninferrable_typevars Method
julia
uninferrable_typevars(def::Union{JLStruct, JLKwStruct}; leading_inferable::Bool=true)

Return the type variables that are not inferrable in given struct definition.

source

Transform ​

Some common transformations for Julia Expr, these functions takes an Expr and returns an Expr.

Expronicon.Substitute Type
julia
Substitute(condition) -> substitute(f(expr), expr)

Returns a function that substitutes expr with f(expr) if condition(expr) is true. Applied recursively to all sub-expressions.

Example

julia
julia> sub = Substitute() do expr
           expr isa Symbol && expr in [:x] && return true
           return false
       end;

julia> sub(_->1, :(x + y))
:(1 + y)
source
Expronicon.alias_gensym Method
julia
alias_gensym(ex)

Replace gensym with <name>_<id>.

Note

Borrowed from MacroTools.

source
Expronicon.annotations_only Method
julia
annotations_only(ex)

Return type annotations only. See also name_only.

source
Expronicon.canonicalize_lambda_head Method
julia
canonicalize_lambda_head(ex)

Canonicalize the Expr(:function, Expr(:block, x, Expr(:(=), key, default)), body) to

julia
Expr(:function, Expr(:tuple, Expr(:parameters, Expr(:kw, key, default)), x), body)
source
Expronicon.eval_interp Method
julia
eval_interp(m::Module, ex)

evaluate the interpolation operator in ex inside given module m.

source
Expronicon.eval_literal Method
julia
eval_literal(m::Module, ex)

Evaluate the literal values and insert them back to the expression. The literal value can be checked via is_literal.

source
Expronicon.expr_map Method
julia
expr_map(f, c...; skip_nothing::Bool=false)

Similar to Base.map, but expects f to return an expression, and will concanate these expression as a Expr(:block, ...) expression.

Skip nothing if skip_nothing is true.

Example

julia
julia> expr_map(1:10, 2:11) do i,j
           :(1 + $i + $j)
       end
quote
    1 + 1 + 2
    1 + 2 + 3
    1 + 3 + 4
    1 + 4 + 5
    1 + 5 + 6
    1 + 6 + 7
    1 + 7 + 8
    1 + 8 + 9
    1 + 9 + 10
    1 + 10 + 11
end
source
Expronicon.flatten_blocks Method
julia
flatten_blocks(ex)

Remove hierachical expression blocks.

source
Expronicon.name_only Method
julia
name_only(ex)

Remove everything else leaving just names, currently supports function calls, type with type variables, subtype operator <: and type annotation ::.

Example

julia
julia> using Expronicon

julia> name_only(:(sin(2)))
:sin

julia> name_only(:(Foo{Int}))
:Foo

julia> name_only(:(Foo{Int} <: Real))
:Foo

julia> name_only(:(x::Int))
:x
source
Expronicon.nexprs Method
julia
nexprs(f, n::Int)

Create n similar expressions by evaluating f.

Example

julia
julia> nexprs(5) do k
           :(1 + $k)
       end
quote
    1 + 1
    1 + 2
    1 + 3
    1 + 4
    1 + 5
end
source
Expronicon.prettify Method
julia
prettify(ex; kw...)

Prettify given expression, remove all LineNumberNode and extra code blocks.

Options (Kwargs)

All the options are true by default.

  • rm_lineinfo: remove LineNumberNode.

  • flatten_blocks: flatten begin ... end code blocks.

  • rm_nothing: remove nothing in the begin ... end.

  • preserve_last_nothing: preserve the last nothing in the begin ... end.

  • rm_single_block: remove single begin ... end.

  • alias_gensym: replace ##<name>#<num> with <name>_<id>.

  • renumber_gensym: renumber the gensym id.

Tips

the LineNumberNode inside macro calls won't be removed since the macrocall expression requires a LineNumberNode. See also issues/#9.

source
Expronicon.renumber_gensym Method
julia
renumber_gensym(ex)

Re-number gensym with counter from this expression. Produce a deterministic gensym name for testing etc. See also: alias_gensym

source
Expronicon.rm_annotations Method
julia
rm_annotations(x)

Remove type annotation of given expression.

source
Expronicon.rm_lineinfo Method
julia
rm_lineinfo(ex)

Remove LineNumberNode in a given expression.

Tips

the LineNumberNode inside macro calls won't be removed since the macrocall expression requires a LineNumberNode. See also issues/#9.

source
Expronicon.rm_nothing Method
julia
rm_nothing(ex)

Remove the constant value nothing in given expression ex.

Keyword Arguments

  • preserve_last_nothing: if true, the last nothing will be preserved.
source
Expronicon.substitute Method
julia
substitute(ex::Expr, old=>new)

Substitute the old symbol old with new.

source

CodeGen ​

Code generators, functions that generates Julia Expr from given arguments, Expronicon types.

Expronicon.codegen_ast Method
julia
codegen_ast(def)

Generate Julia AST object Expr from a given syntax type.

Example

One can generate the Julia AST object from a JLKwStruct syntax type.

julia
julia> def = @expr JLKwStruct struct Foo{N, T}
                  x::T = 1
              end
#= kw =# struct Foo{N, T}
    #= REPL[19]:2 =#
    x::T = 1
end

julia> codegen_ast(def)|>rm_lineinfo
quote
    struct Foo{N, T}
        x::T
    end
    begin
        function Foo{N, T}(; x = 1) where {N, T}
            Foo{N, T}(x)
        end
        function Foo{N}(; x::T = 1) where {N, T}
            Foo{N, T}(x)
        end
    end
end
source
Expronicon.codegen_ast_fields Method
julia
codegen_ast_fields(fields; just_name::Bool=true)

Generate a list of Julia AST object for each field, only generate a list of field names by default, option just_name can be turned off to call codegen_ast on each field object.

source
Expronicon.codegen_ast_kwfn Function
julia
codegen_ast_kwfn(def[, name = nothing])

Generate the keyword function from a Julia struct definition.

Example

julia
julia> def = @expr JLKwStruct struct Foo{N, T}
                  x::T = 1
              end
#= kw =# struct Foo{N, T}
    #= REPL[19]:2 =#
    x::T = 1
end

julia> codegen_ast_kwfn(def)|>prettify
quote
    function Foo{N, T}(; x = 1) where {N, T}
        Foo{N, T}(x)
    end
    function Foo{N}(; x::T = 1) where {N, T}
        Foo{N, T}(x)
    end
end

julia> def = @expr JLKwStruct struct Foo
                  x::Int = 1
              end
#= kw =# struct Foo
    #= REPL[23]:2 =#
    x::Int = 1
end

julia> codegen_ast_kwfn(def)|>prettify
quote
    function Foo(; x = 1)
        Foo(x)
    end
    nothing
end
source
Expronicon.codegen_ast_kwfn_infer Function
julia
codegen_ast_kwfn_infer(def, name = nothing)

Generate the keyword function that infers the type.

source
Expronicon.codegen_ast_kwfn_plain Function
julia
codegen_ast_kwfn_plain(def[, name = nothing])

Generate the plain keyword function that does not infer type variables. So that one can use the type conversions defined by constructors.

source
Expronicon.codegen_ast_struct Method
julia
codegen_ast_struct(def)

Generate pure Julia struct Expr from struct definition. This is equivalent to codegen_ast for JLStruct. See also codegen_ast.

Example

julia
julia> def = JLKwStruct(:(struct Foo
           x::Int=1
           
           Foo(x::Int) = new(x)
       end))
struct Foo
    x::Int = 1
end

julia> codegen_ast_struct(def)
:(struct Foo
      #= REPL[21]:2 =#
      x::Int
      Foo(x::Int) = begin
              #= REPL[21]:4 =#
              new(x)
          end
  end)
source
Expronicon.codegen_ast_struct_body Method
julia
codegen_ast_struct_body(def)

Generate the struct body.

Example

julia
julia> def = JLStruct(:(struct Foo
           x::Int
           
           Foo(x::Int) = new(x)
       end))
struct Foo
    x::Int
end

julia> codegen_ast_struct_body(def)
quote
    #= REPL[15]:2 =#
    x::Int
    Foo(x::Int) = begin
            #= REPL[15]:4 =#
            new(x)
        end
end
source
Expronicon.codegen_ast_struct_head Method
julia
codegen_ast_struct_head(def)

Generate the struct head.

Example

julia
julia> using Expronicon

julia> def = JLStruct(:(struct Foo{T} end))
struct Foo{T}
end

julia> codegen_ast_struct_head(def)
:(Foo{T})

julia> def = JLStruct(:(struct Foo{T} <: AbstractArray end))
struct Foo{T} <: AbstractArray
end

julia> codegen_ast_struct_head(def)
:(Foo{T} <: AbstractArray)
source
Expronicon.struct_name_plain Method
julia
struct_name_plain(def)

Plain constructor name. See also struct_name_without_inferable.

Example

julia
julia> def = @expr JLKwStruct struct Foo{N, Inferable}
    x::Inferable = 1
end

julia> struct_name_plain(def)
:(Foo{N, Inferable})
source
Expronicon.struct_name_without_inferable Method
julia
struct_name_without_inferable(def; leading_inferable::Bool=true)

Constructor name that assume some of the type variables is inferred. See also struct_name_plain. The kwarg leading_inferable can be used to configure whether to preserve the leading inferable type variables, the default is true to be consistent with the default julia constructors.

Example

julia
julia> def = @expr JLKwStruct struct Foo{N, Inferable}
    x::Inferable = 1
end

julia> struct_name_without_inferable(def)
:(Foo{N})

julia> def = @expr JLKwStruct struct Foo{Inferable, NotInferable}
    x::Inferable
end

julia> struct_name_without_inferable(def; leading_inferable=true)
:(Foo{Inferable, NotInferable})

julia> struct_name_without_inferable(def; leading_inferable=false)
:(Foo{NotInferable})
source
Expronicon.xcall Method
julia
xcall(name, args...; kw...)

Create a function call to name.

source
Expronicon.xcall Method
julia
xcall(m::Module, name::Symbol, args...; kw...)

Create a function call to GlobalRef(m, name).

Tip

due to Revise/#616, to make your macro work with Revise, we use the dot expression Expr(:., <module>, QuoteNode(<name>)) instead of GlobalRef here.

source
Expronicon.xfirst Method
julia
xfirst(collection)

Create a function call expression to Base.first.

source
Expronicon.xgetindex Method
julia
xgetindex(collection, key...)

Create a function call expression to Base.getindex.

source
Expronicon.xiterate Method
julia
xiterate(it, st)

Create a function call expression to Base.iterate.

source
Expronicon.xiterate Method
julia
xiterate(it)

Create a function call expression to Base.iterate.

source
Expronicon.xlast Method
julia
xlast(collection)

Create a function call expression to Base.last.

source
Expronicon.xmap Method
julia
xmap(f, xs...)

Create a function call expression to Base.map.

source
Expronicon.xmapreduce Method
julia
xmapreduce(f, op, xs...)

Create a function call expression to Base.mapreduce.

source
Expronicon.xnamedtuple Method
julia
xnamedtuple(;kw...)

Create a NamedTuple expression.

source
Expronicon.xprint Method
julia
xprint(xs...)

Create a function call expression to Base.print.

source
Expronicon.xprintln Method
julia
xprintln(xs...)

Create a function call expression to Base.println.

source
Expronicon.xpush Method
julia
xpush(collection, items...)

Create a function call expression to Base.push!.

source
Expronicon.xtuple Method
julia
xtuple(xs...)

Create a Tuple expression.

source
Expronicon.codegen_match Function
julia
codegen_match(f, x[, line::LineNumberNode=LineNumberNode(0), mod::Module=Main])

Generate a zero dependency match expression using MLStyle code generator, the syntax is identical to MLStyle.

Tip

codegen_match is not available in ExproniconLite since it depends on MLStyle's pattern matching functionality.

Example

julia
codegen_match(:x) do
    quote
        1 => true
        2 => false
        _ => nothing
    end
end

This code generates the following corresponding MLStyle expression

julia
@match x begin
    1 => true
    2 => false
    _ => nothing
end
source
Expronicon.@syntax_pattern Macro
julia
@syntax_pattern <syntax type> <syntax checker>

Bundle a syntax type as MLStyle pattern.

Tip

this is not available in ExproniconLite since it depends on MLStyle's pattern matching functionality.

Example

julia
struct MyFunction
    ex :: Expr
    test_field :: Any
end

is_xxx(ex::Expr) = Meta.isexpr(ex, :function)
is_xxx(_) = false

julia> MyFunction(ex::Expr) = MyFunction(ex, :aaa)
julia> @syntax_pattern(MyFunction, is_xxx)

julia> @match :(function f() end) begin
        MyFunction(;test_field) => test_field
    end
:aaa
source

Printings ​

Pretty printing functions.

Expronicon.print_inline Method
julia
print_expr([io::IO], ex; kw...)

Print a given expression within one line. ex can be a Expr or a syntax type JLExpr.

source
Expronicon.print_expr Method
julia
print_expr([io::IO], ex; kw...)

Print a given expression. ex can be a Expr or a syntax type JLExpr.

source
Expronicon.sprint_expr Method
julia
sprint_expr(ex; context=nothing, kw...)

Print given expression to String, see also print_expr.

source

Algebra Data Type ​

Algebra data type

Expronicon.ADT.@adt Macro
julia
@adt name begin
    variant1
    variant2(field1, field2)

    <mutable> struct variant3
        field1
        field2 = <default>
    end
end

Create an algebra data type (ADT).

Arguments

  • <name>: the name of the ADT, can be just a name or name with supertype.

  • <body>: the body of the ADT, a list of variants in begin ... end block.

Introduction

The ADT is a type that can have multiple variants. Each variant can have different fields. The fields can be of different types. The ADT is immutable by default. To make it mutable, use mutable struct instead of struct in the definition.

The ADT is implemented as a tagged union. The tag is stored in the first field. The rest of the fields are the actual data. The data is stored in a compact way so that the size of the ADT is the size of the largest variant.

Use of multiple variants will not effect type stability, unlike Union types.

The variants must be used with the variant interface instead of the type interface from Julia Base, and the pattern match must be MLStyle's pattern match. It is recommended to use pattern match as much as possible.

Pretty Printing

A default inline pretty printing is generated for Base.show(io::IO, x::<your ADT type>). If you want to customize inline text printing, overload Expronicon.ADT.variant_show_inline(io::IO, x::<your ADT type>) method. For other MIME types, you can overload the normal Base.show(::IO, ::MIME, x::<your ADT type>) method.

source
Expronicon.ADT.adt_type Method
julia
adt_type(variant_type)

Returns the algebra data type type of a variant type variant_type.

source
Expronicon.ADT.is_adt Method
julia
is_adt(variant)

Returns true if variant is an instance of an algebra data type.

source
Expronicon.ADT.is_adt Method
julia
is_adt(::Type{T}) where T

Returns true if T is an algebra data type.

source
Expronicon.ADT.is_variant Method
julia
is_variant(variant)
is_variant(variant_type)

Returns true if T is a variant type or an instance of an algebra data type.

source
Expronicon.ADT.variant_field_default Method
julia
variant_field_default(variant_type, idx)

Returns the idx-th field default of a variant type.

source
Expronicon.ADT.variant_field_defaults Method
julia
variant_field_defaults(variant_type)

Returns the field defaults of a variant type.

source
Expronicon.ADT.variant_fieldname Method
julia
variant_fieldname(variant_type, idx)

Returns the idx-th field name of a variant type.

source
Expronicon.ADT.variant_fieldnames Method
julia
variant_fieldnames(variant_type)

Returns the field names of a variant type.

source
Expronicon.ADT.variant_fieldtype Method
julia
variant_fieldtype(variant_type, idx)

Returns the idx-th field type of a variant type.

source
Expronicon.ADT.variant_fieldtypes Method
julia
variant_fieldtypes(variant_type)

Returns the field types of a variant type.

source
Expronicon.ADT.variant_masks Method
julia
variant_masks(variant_type)

Returns the masks of a variant type.

source
Expronicon.ADT.variant_type Method
julia
variant_type(variant)

Returns the variant type of an algebra data type instance variant.

source
Expronicon.ADT.variants Method
julia
variants(::Type{T}) where T

Returns the variant types of an algebra data type T.

source
Expronicon.ADT.@const_use Macro
julia
@const_use <name>: <variant>
@const_use <name>: <variant>, <variant>, ...
@const_use <name>: *

Import the variant of a ADT into current namespace.

julia
@const_use Message: Write
source
Expronicon.ADT.@export_use Macro
julia
@export_use <name>: <variant>

Import the variant of a ADT into current namespace, and export it.

julia
@export_use Message: Write
source
Expronicon.ADT.@use Macro
julia
@use <name>: <variant>
@use <name>: <variant>, <variant>, ...
@use <name>: *

Import the variant of a ADT into current namespace.

julia
@use Message: Write

Tips

This macro does not create a constant binding so that you can use it inside a function, if you wish to use this macro in the global scope, use @const_use instead.

source

Released under the MIT License.