Macros

Compile-time code that writes code — the same in T and Ty, in both syntaxes

Macros run before anything is parsed into a language. Both syntaxes of both languages first produce the same intermediate language — a tree of symbols and lists — and the macro expander rewrites that tree. Because it works below T and below Ty, everything on this page applies unchanged to .c.t, .sln.t, .c.ty and .sln.ty files. Only the way a definition is written differs between the two syntaxes.

A macro is not a text substitution and not a template. Its body is ordinary code that is executed at compile time, and whatever code that execution returns replaces the call. This is what makes a macro able to loop, branch and recurse over its arguments, so a macro can build a control structure or a small language of its own rather than only filling holes in a fixed shape.

Defining and Calling

A definition names the macro, lists its parameters and gives a body. A call looks like any other call.

C syntaxSLN syntax
Definitionmacro square(n) { qq($n * $n) }macro square (n) (qq (* $n $n))
Callsquare(5)(square 5)
Variadicmacro sum(xs...) { … }macro sum (xs...) …

Arguments arrive as code, not as values. Calling square(1 + 2) hands the macro the expression 1 + 2 itself, so the result is (1 + 2) * (1 + 2) and not 3 * 3. A macro that wants a number instead of an expression has to compute one — the body runs at compile time, so macro computed() { 2 + 3 } returns the number 5 and the call site sees a literal.

Quasiquote

qq is the form that turns code into a value. Everything inside it is kept as it is written; the holes are marked with $.

FormMeaning
$nameInsert the value bound to name
$(expr) / ($ expr)Evaluate expr and insert the result
$...nameSplice a list — its elements become siblings, not a nested list
$...(expr) / ($... expr)Evaluate expr and splice the resulting list

The difference between insert and splice matters wherever a list is built. Inserting a three-element list into a call gives that call one argument which happens to be a list; splicing it gives the call three arguments.

Values

A macro body computes with four kinds of value: integers, booleans, code (a single tree, what qq produces and what an argument is) and lists of code. The forms available are the ones the intermediate language already has — let, var, if, do, while, :=, += and its siblings, return, arithmetic, comparisons and the bit operators &, |, ^, <<, >> — plus a handful of functions for taking lists apart.

FunctionResult
list(a, b, …)A list of the given items
cons(item, rest)rest with item put in front
head(xs)The first element
tail(xs)Everything but the first element
count(xs)The number of elements
is_empty(xs)Whether the list has no elements
is_symbol(x) / is_list(x)Which of the two shapes a piece of code has
symbol(a, b, …)One name, written by joining the given items
error(a, b, …)Abort the expansion, reporting the given items as the message

An argument arrives as code, but code that reads as a number is a number wherever a number is called for: inc(5) with a body of n + 1 expands to 6, and so does inc(2 + 3) — an argument that is a whole expression is evaluated at the point of use, as long as it is built from literals and the functions on this page. The same holds for true and false, and for comparison: n == 2 is true for the argument 2 however it was written. This is what makes computation over arguments possible at all, including recursion over a counter. An argument that mentions a runtime variable stays code, which is what lets the same argument be inserted into a template instead.

A macro that checks its arguments needs a way to reject them. Without error, the only answer to a bad call is some result, and a macro that quietly returns the wrong code is worse than one that fails:

macro bit_of(s) {
    if (s == qq(e1)) { 1 } else { if (s == qq(e2)) { 2 } else { error("not a blade:", s) } }
}

A rejection is reported at the call the user wrote, not at the check inside the macro, even when the failing check sits several macros deep. The position of the check follows on a second line, so a library can name the offending argument and the caller still sees the line to change.

symbol goes the other way and writes a name instead of recognising one. A name that follows a pattern need not be spelled out once per case: symbol(qq(e), index + 1) yields e3 for an index of 2. Note the qq — a bare e would be looked up as a variable. Names can be built but not taken apart; there is no way to ask what characters e12 is made of.

Meta Functions

Ordinary fn declarations in the same file are callable from a macro body as meta functions, in both T and Ty. This is useful for integer arithmetic a macro needs; a function that manipulates code is not, because its parameters would have no runtime type.

In Ty a const fn is callable the same way, and that is the case worth reaching for. A function the compiler already evaluates at compile time — for an array length, an index, a constant — is exactly what a macro body wants, so the same rule can serve both instead of being written twice. Bit arithmetic over a mask is the usual example: the compiler sizes an array with it, the macro names the fields.

const fn popcount(n: u64) -> u64 {
    var count: u64 = 0;
    var rest: u64 = n;
    while rest > 0 {
        count := count + (rest & 1);
        rest := rest >> 1;
    }
    count
}

const grade_of_22: u64 = popcount(22);
macro grade(mask) { popcount(mask) }

A newtype conversion is understood as well, in each of its three spellings — d.u64, u64: d and grade: 1 — so a function whose parameters are newtypes can still do arithmetic on them at expansion time. A conversion of a literal is the literal itself; a conversion of a runtime expression stays in the code the macro returns.

The body runs in the same interpreter as a macro body, so it is limited to the forms listed under Values. A meta function that reads a runtime variable, indexes an array or calls into a backend cannot be evaluated during expansion, and the call is reported as an error rather than silently skipped.

Recursion and Variadics

A parameter written xs... collects every remaining argument into one list. Together with recursion this is what lifts macros above templates: a macro can walk its argument list and fold it into a tree of any depth. sum(1, 2, 3, 4) below expands to 1 + (2 + (3 + (4 + 0))), a shape no fixed template could produce, because the number of additions is not known until the call is seen.

Hygiene

A name that a macro binds inside qq — with let, var, ref or label — is renamed to something unique every time the macro is expanded. A macro that uses tmp internally therefore cannot shadow a caller's tmp, and code the caller passes in still refers to the caller's variable. The double macro in the examples relies on exactly this: it is called with a variable named tmp while binding tmp itself, and both keep their meaning.

Renaming happens before the holes are filled, so only the names the template itself writes are affected; names that arrive through $ are left alone.

Examples

The same six results in T, in both syntaxes:

macro square (n) (qq (* $n $n))

macro computed () (+ 2 3)

macro double (v)
    qq
        do
            let tmp $v
            + tmp tmp

macro sum_list (xs)
    if (is_empty xs)
        (qq 0)
        (qq (+ ($ (head xs)) ($ (sum_list (tail xs)))))

macro sum (xs...) (sum_list xs)

print (square 5)
print (square (+ 1 2))

print (computed)

let tmp 7
print (double tmp)
print tmp

print (sum 1 2 3 4)
macro square(n) { qq($n * $n) }

macro computed() { 2 + 3 }

macro double(v) { qq({ let tmp = $v; tmp + tmp }) }

macro sum_list(xs) {
    if (is_empty(xs)) { qq(0) } else { qq($(head(xs)) + $(sum_list(tail(xs)))) }
}

macro sum(xs...) { sum_list(xs) }

print(square(5));
print(square(1 + 2));

print(computed());

let tmp = 7;
print(double(tmp));
print(tmp);

print(sum(1, 2, 3, 4));

The Ty version of the same file is character for character the T version — nothing about a macro is specific to either language:

macro square(n) { qq($n * $n) }

macro computed() { 2 + 3 }

macro double(v) { qq({ let tmp = $v; tmp + tmp }) }

macro sum_list(xs) {
    if (is_empty(xs)) { qq(0) } else { qq($(head(xs)) + $(sum_list(tail(xs)))) }
}

macro sum(xs...) { sum_list(xs) }

print(square(5));
print(square(1 + 2));

print(computed());

let tmp = 7;
print(double(tmp));
print(tmp);

print(sum(1, 2, 3, 4));

Limits

The exact forms the expander accepts are specified in docs/il-spec.md in the repository.