Julia Metaprogramming
Julia represents its own code as data structures in the language, so that we can write programs that manipulate programs.
Metaprogramming can also be simply understood as writing code that generates code.
Metaprogramming (English: Metaprogramming) refers to the writing of a certain class of computer programs that write or manipulate other programs (or themselves) as their data, or that do work at compile time which would otherwise be done at run time. In most cases, compared with writing all code by hand, programmers can achieve greater productivity, or give programs greater flexibility to handle new situations without recompilation.
The language in which a metaprogram is written is called the metalanguage. The language of the program being manipulated is called the "target language". The ability of a programming language to be its own metalanguage is called "reflection" or "reflexivity".
-- Wikipedia
Stages of Julia Source Code Execution
1. Parse the raw Julia code: The Julia parser first parses the source string into an Abstract Syntax Tree (AST), a structure that contains all the code in a format that is easy to manipulate.
2. Execute the parsed Julia code: At this stage, the parsed Julia code is executed.
When we type code in the REPL and press Enter, the above two stages are executed in sequence.
Using metaprogramming tools, we can access the Julia code between these two stages, that is, after the source is parsed but before it is executed.
Note:Metaprogramming is a powerful tool, but it also makes code harder to understand. The official recommendation is to use macros and eval only when higher-order functions and closures are insufficient; most functionality should be implemented with ordinary functions first.
Program Representation
Julia provides the Meta module; you can use Meta.parse(str) to parse a string into an expression object, and the result is of type Expr:
Example
julia
prog =
"1 + 1"
"1 + 1"
julia
ex1 = Meta.
parse
(
prog
)
:
(
1
1
)
julia
typeof
(
ex1
)
Expr
An Expr object contains two parts (ex1 has the head and args attributes):
One is a Symbol object that identifies the type of the expression:
Example
julia
ex1.
head
:call
The other is the arguments of the expression, which may be symbols, other expressions, or literals:
Example
julia
ex1.
args
3
-element
Vector
{
Any
}
:
:+
1
1
Expressions can also be constructed directly with Expr:
Example
julia
ex2 =
Expr
(
:call, :+,
1
,
1
)
:
(
1
1
)
The two expressions, obtained by parsing and by direct construction, are equivalent
julia
ex1 == ex2
true
Nested Expressions
julia
ex3 = Meta.
parse
(
"(4 + 4) / 2"
)
:
(
(
4
4
)
/
2
)
View the nested structure with S-expressions
julia
Meta.
show_sexpr
(
ex3
)
(
:call, :/,
(
:call, :+,
4
,
4
)
,
2
)
Symbols and Quoting
The colon : prefix has two uses in Julia; be careful to distinguish them:
First, :name creates a Symbol. A Symbol is an "interned string" that represents a name itself rather than its value:
Example
julia
ABC =
100
100
julia
:ABC
returns the symbol :ABC, not 100
:ABC
julia
typeof
(
:ABC
)
Symbol
Second, :(expression) creates an unevaluated expression object (quoting):
Example
julia
:
(
100
50
)
:
(
100
50
)
julia
ex = :
(
a + b
c +
1
)
:
(
a + b
c +
1
)
julia
typeof
(
ex
)
Expr
Three equivalent ways of construction
julia
:
(
a + b
c +
1
)
== Meta.
parse
(
"a + b*c + 1"
)
==
Expr
(
:call, :+, :a,
Expr
(
:call, :
, :b, :c
)
,
1
)
true
To quote multiple expressions you can quote ... end include a code block in:
Example
julia
ex =
quote
x =
1
y =
2
x + y
end
quote
#= none:2 =#
x =
1
#= none:3 =#
y =
2
#= none:4 =#
x + y
end
julia
typeof
(
ex
)
Expr
Executing Expressions
After an expression is parsed, we can use the eval() function to execute it in the global scope:
Example
julia
ex1 = :
(
1
2
)
:
(
1
2
)
julia
eval
(
ex1
)
3
Symbols in the expression are looked up only at eval time
julia
ex = :
(
a + b
)
:
(
a + b
)
julia
eval
(
ex
)
ERROR: UndefVarError:
`
b
`
not defined
in
`
Main
`
julia
a =
1
;
b =
2
;
julia
eval
(
ex
)
3
Abstract Syntax Tree (AST)
An abstract syntax tree is an abstract representation of the syntactic structure of source code; it represents the syntax of a programming language in tree form, and each node on the tree represents a construct in the source code.
We can view the hierarchy of an expression with the dump() function:
Example
julia
dump
(
:
(
1
cos
(
pi/
2
)
)
)
Expr
head
:
Symbol
call
args:
Array
{
Any
}
(
(
3
,
)
)
1
:
Symbol
2
:
Int64
1
3
:
Expr
head
:
Symbol
call
args:
Array
{
Any
}
(
(
2
,
)
)
1
:
Symbol
cos
2
:
Expr
head
:
Symbol
call
args:
Array
{
Any
}
(
(
3
,
)
)
1
:
Symbol
/
2
:
Symbol
pi
3
:
Int64
2
Interpolation
Directly constructing Expr objects is powerful but tedious to write. Julia allows literals or expressions to beValueinserted into a quoted expression; interpolation is denoted by the $ prefix:
Example
julia
a =
1
;
the value of a is interpolated into the expression
julia
ex = :
(
$a + b
)
:
(
1
- b
)
Interpolation into an unquoted expression is not supported and causes a compile-time error:
julia> $a + b
ERROR: syntax: "$" expression outside quote
To interpolate a tuple, use the $((1,2,3)) form:
julia> ex = :(a in $:((1,2,3)) )
:(a in (1, 2, 3))
The $ in expression interpolation is deliberately consistent with string and command interpolation; it makes the programmatic construction of complex Julia expressions convenient and readable.
macro
Macros provide a mechanism to include generated code in the final body of a program. A macro maps a set of arguments (expressions) to a returned expression, which is compiled directly without a run-time eval call. Macro arguments can include expressions, literals, and symbols.
Here is a very simple macro:
Example
julia
macro
sayhello
(
)
return
:
(
println
(
"Hello, world!"
)
)
end
@sayhello
(
macro
with
1
method
)
Macros have a dedicated character @ (at-sign) in Julia's syntax, immediately followed by the macro name. In this example, the compiler replaces every @sayhello with:
:( println("Hello, world!") )
When @sayhello is entered in the REPL, the interpreter immediately executes the expanded code, so we only see the computed result:
julia> @sayhello()
Hello, world!
For macros with arguments, use $ to interpolate the arguments into the returned expression:
Example
julia
macro
sayhello
(
name
)
return
:
(
println
(
"Hello, "
, $name
)
)
end
@sayhello
(
macro
with
1
method
)
julia
@sayhello
(
"human"
)
Hello, human
Viewing Macro Expansion
We can use @macroexpand to see the expanded expression; it is the most useful tool for debugging macros:
Example
julia
@macroexpand @sayhello
(
"human"
)
:
(
println
(
"Hello, "
,
"human"
)
)
Expansion of the @assert macro: the expression is kept verbatim, and on error the expression text can still be printed
julia
@macroexpand @assert
1
==
2
:
(
if
1
==
2
nothing
else
throw
(
AssertionError
(
"1 == 2"
)
)
end
)
The key difference between macros and functions:Macros run at code-parse time, functions run at run time. A macro receives the code itself (an expression), while a function receives computed values, so macros can do things functions cannot, such as showing the original expression in an error message.
Macro Hygiene
When a macro is expanded, variables defined inside the macro are automatically renamed so they do not conflict with variables at the call site; this is called macro hygiene. If a macro needs to manipulate variables at the call site, it must be declared explicitly with esc():
Example
This macro sets x at the call site to 0
julia
macro
zerox
(
)
return
esc
(
:
(
x =
0
)
)
end
@zerox
(
macro
with
1
method
)
julia
function
foo
(
)
x =
1
@zerox
return
x
end
foo
(
generic
function
with
1
method
)
julia
foo
(
)
0
The Principle Behind Non-Standard String Literals
The non-standard string literals used in earlier chapters, such as r"..." (regex) and b"..." (byte array), are actually the macro mechanism: the prefix name plus the _str suffix is the corresponding macro name. For example, the implementation of the regex literal is a single line:
Example
macro
r_str
(
p
)
Regex
(
p
)
end
r"^\s*$" is parsed as an @r_str macro call; the macro turns the string into a Regex object at compile time, which is more efficient than calling Regex("...") each time at run time.
Code generation
When a large amount of repetitive boilerplate code is needed, you can use the @eval macro to generate definitions inside the program. For example, to add methods to a custom type in bulk:
Example
julia
struct MyNumber
x::
Float64
end
Define sin/cos/tan/log/exp methods for MyNumber in bulk
julia
for
op =
(
:sin, :cos, :tan, :log, :exp
)
@
eval
Base.$op
(
a::MyNumber
)
= MyNumber
(
$op
(
a.
x
)
)
end
julia
x = MyNumber
(
pi
)
MyNumber
(
3.141592653589793
)
julia
sin
(
x
)
MyNumber
(
1.2246467991473532e-16
)
julia
cos
(
x
)
MyNumber
(
1.0
)
This pattern lets Julia act as its own preprocessor, completing code generation inside the language.