Julia Macros
A macro is a function that runs at parse time: it receives the code of its arguments as expressions and returns new code, which is then compiled in place of the macro call. Macro names start with @. You've used many already: @show, @printf, @assert, @view, @..
Useful built-in macros
| Macro | What it does |
|---|---|
@show expr |
prints expr = value |
@assert cond |
throws AssertionError if cond is false |
@time expr |
runs expr and prints time and allocations |
@elapsed expr |
returns the run time in seconds |
@view A[...] |
a view instead of a copy |
@. |
dots every operation |
@inbounds |
skips bounds checks (use with care) |
@kwdef |
keyword constructor for a struct |
@info, @warn, @error |
logging (from Logging) |
@macroexpand |
shows the code a macro produces |
x = [1, 2, 3]
@show x
@show sum(x) / length(x)
@assert length(x) == 3
y = @. x^2 + 1
@show y
try
@assert isempty(x) "x should be empty here"
catch e
println(sprint(showerror, e))
endx = [1, 2, 3]
sum(x) / length(x) = 2.0
y = [2, 5, 10]
AssertionError: x should be empty here
Notice what @show does: it prints the source text of its argument. A function could never do that — by the time a function is called, it only sees the value. A macro sees the code.
Writing a macro
Define a macro with macro name(args) ... end. It returns an expression, usually built with quote and $ interpolation:
macro twice(ex)
return quote
$(esc(ex))
$(esc(ex))
end
end
@twice println("hello")
counter = 0
@twice global counter += 1
println(counter)hello
hello
2
esc ("escape") tells Julia that the user's expression should be evaluated in the caller's scope. Without it, macro hygiene renames variables to avoid accidental clashes, and counter would refer to something else.
Seeing the generated code
@macroexpand shows what a macro call turns into, which is the best way to understand and debug macros:
macro unless(cond, body)
return :(if !$(esc(cond)); $(esc(body)); end)
end
ready = false
@unless ready println("not ready yet")
println(Base.remove_linenums!(@macroexpand @unless ready println("x")))not ready yet
if !ready
println("x")
end
A practical macro: @check
Macros can capture the expression text as a string with string(ex). This @check macro reports which condition failed — like @assert, but it prints instead of throwing:
macro check(ex)
text = string(ex)
return quote
result = $(esc(ex))
println(result ? "PASS " : "FAIL ", $text)
result
end
end
a, b = 3, 4
@check a + b == 7
@check a * b > 20
@check startswith("julia", "ju")PASS a + b == 7
FAIL a * b > 20
PASS startswith("julia", "ju")
The variable result inside the macro is not escaped, so hygiene gives it a hidden unique name — it can't overwrite a result variable in your code.
The Test standard library
Test is built on exactly this idea. @test records whether an expression is true, and @testset groups tests and prints a summary:
using Test
square(x) = x * x
@testset "square" showtiming=false begin
@test square(3) == 9
@test square(-2) == 4
@test square(0.5) ≈ 0.25
@test_throws MethodError square(nothing)
end;Test Summary: | Pass Total
square | 4 4
showtiming=false hides the time column, which would differ from run to run. When a test fails, @test prints the original expression and the evaluated values, which it can only do because it is a macro.
Macros vs functions
| Function | Macro | |
|---|---|---|
| Runs | when the program runs | when code is parsed (before it runs) |
| Receives | values | expressions (code) |
| Returns | a value | code that replaces the call |
| Use for | almost everything | new syntax, capturing source text, code generation |
Tip: Always try a function first. Write a macro only when you need something a function can't do.
Test yourself
What does a macro receive as its arguments?
- The evaluated values
- The unevaluated expressions (code)
- Strings
- Types
Why does a macro use esc(ex)?
- To make it run faster
- So the user's code is evaluated in the caller's scope instead of being renamed by hygiene
- To convert it to a string
- To prevent it from running
Which macro shows the code a macro call expands to?
- @show
- @code
- @macroexpand
- @eval