Axle v0.22.0

Annotations reference

An annotation is a @ word placed above a declaration or a loop. It is read by the compiler and never by the program, so it can change how code is compiled or bound, but not what a line computes.

There are two families, and they sit in different places:

  • Loop annotations sit immediately above a for, while or do-while loop. They steer how LLVM vectorises or unrolls the loop body. Anywhere else the parser refuses them.
  • Declaration annotations sit immediately above a function, method, class, struct, enum, trait, field or extern block. Each one applies to some of those sites only. Writing an unknown name is E0011, and writing a known name on a site it does not concern is E0012.
  @vectorize                     ◀── loop family: directly above for / while
  for (i of 0..n) { … }

  @float(fast)                   ◀── declaration family: above fn / method / class …
  fn sum(values : f64[]) : f64 { … }

What this page covers: the four loop annotations · the declaration annotations one by one (@link, the @float, @heat, @inline and @layout axes, @upsert, @derive, @target) · where each is accepted · what an unknown or misplaced one earns · the values each takes.

Loop annotations

Each loop annotation goes directly above a loop. The loop keeps its parentheses, as in for (i of 0..n).

AnnotationEffectRefused when
@vectorizeasks LLVM to vectorise the loopnever, above a loop
@vectorize(disable)forces the loop to stay scalarnever
@vectorize(width: N)pins the vector width to N lanesN is over the lane count of the build’s target CPU (E0292)
@unroll(N)sets the unroll factor to NN is not a positive integer literal

@vectorize

fn addInto(out : i32[], a : i32[], b : i32[], n : i32) {
    @vectorize
    for (i of 0..n) { out[i] = a[i] + b[i]; }
}

Enables the loop vectoriser on this loop. LLVM picks the vector width from the host’s SIMD level and from the cost of the body. The compiler’s own sema pass may already have rewritten a loop of this shape before LLVM sees it. See SIMD and auto-vectorisation.

@vectorize(disable)

fn fold(table : i32[], n : i32) : i32 {
    let mut state : i32 = 0;
    @vectorize(disable)
    for (i of 0..n) { state = state * 31 + table[i]; }
    return state;
}

Forces the loop to stay scalar. Use it when the vectoriser would produce strided scatter or gather code that runs slower than the plain form.

@vectorize(width: N)

fn mulInto(out : i32[], a : i32[], b : i32[], n : i32) {
    @vectorize(width: 8)
    for (i of 0..n) { out[i] = a[i] * b[i]; }
}

Pins the vector width. N must be a positive integer literal no larger than the widest lane count the build’s target CPU can execute. A larger request is rejected with E0292, and the message names the maximum. The ceiling follows the CPU and features the build targets (128-bit vectors by default), raised by --target-cpu, --target-features or native. See SIMD for the table of caps.

@unroll(N)

fn total(values : i32[], count : i32) : i32 {
    let mut accum : i32 = 0;
    @unroll(4)
    for (i of 0..count) { accum = accum + values[i]; }
    return accum;
}

Sets the unroll factor to N, so LLVM copies the body N times per trip.

Declaration annotations

Each declaration annotation has a set of sites it may sit on. Anywhere else it is refused with E0012, because nothing would read it there.

AnnotationApplies toValueNotes
@target(…)any declaration, method, class, struct, enum, trait, global, type alias, use, and an extern "C" from "…" blocka predicate: os = …, arch = …compiles the item only for matching targets
@link(…)a function and a foreign (bodiless extern "C") functionnamed fields; symbolbinds the declaration to a linker symbol
@float(…)a function, a method, a foreign methodfast, strict or contractthe floating-point mode
@heat(…)a function, a method, a foreign methodcoldthe function runs rarely
@inline(…)a function, a method, a foreign methodalways or neveroverrides the inlining decision
@layout(…)a class, a structpackedrefuses padding in an extern "C" record
@upsert(…)a method, a foreign methoda role stringmarks a container method’s part in a lookup-then-insert
@derive(…)a classtrait namessynthesises trait implementations

@wait(…) also exists, but only the stdlib may write it. It marks a native function that can park the calling task, and a program that writes it is refused as an unknown name (E0011).

Each annotation states its value once per declaration:

  • A second @float, @heat or @inline naming a different word is refused (E0001).
  • A @link or @layout field may sit in a second annotation of the same name as long as the fields do not repeat, but writing the same field twice is refused (E0001).
  • @derive is the exception: a second @derive lists more traits.
  • A second @target or @upsert is refused (E0001). Write one @target(os = …, arch = …) that states the whole predicate.

@link(field = …)

@link(symbol = "write")
extern "C" fn libc_write(fd : i32, buf : ptr<i8>, n : i64) : i64;

@link says how a declaration binds to the world outside the program. Its fields are named, and each one is optional:

FieldValueEffect
symbola non-empty string literalthe linker symbol this declaration resolves to, in place of the Axle identifier

A field that @link does not have is refused with E0011, and the closest name is suggested. A @link that names no field, a positional value, a field written twice, or a symbol that is not a non-empty string literal is E0001. See FFI.

Axes: @float(…), @heat(…), @inline(…), @layout(…)

Some annotations answer one question about a declaration and take the answer as a single bare word from a closed set. Two different words on the same axis are a conflict (E0001). A word the axis does not have is refused (E0011), with the closest one suggested. Writing a word on its own, as in @fast, @cold or @packed, is refused the same way, and the suggestion is the axis form.

@float(fast | strict | contract)

@float(fast)
fn sum(values : f64[]) : f64 {
    let mut total : f64 = 0.0;
    for (i of 0..values.length) {
        total = total + values[i];
    }
    return total;
}

The floating-point mode of the function. The three words differ in what LLVM may change.

WordMeaning
fastevery IEEE-754 relaxation: reassociation, no NaN, no infinity, and the rest. This is what lets a float sum vectorise, and what lets a loop of x.sin() or x.cos() on f32 values compute four at a time: the vector routine rounds within a few units in the last place of the scalar one.
strictnone of them, not even fusing a multiply and an add
contractthe default: a fused multiply-add is allowed, and nothing else

See LLVM attributes: floating-point fast-math.

@heat(cold)

@heat(cold)
fn reportCorruptHeader(offset : i32) : i32 {
    println("corrupt header at " + offset);
    return -1;
}

Declares the function rarely run. It is kept out of line, and the function is marked cold for LLVM. A branch that calls it is laid out as the unlikely one, so the hot loop around it keeps its code tight. A function whose every path throws is already treated as cold. @heat(cold) says so for a function that returns.

The call stays a real call, with its calling convention. Values live across it in a loop must survive in callee-saved registers or on the stack. Mark the function you expect to run once in a long while, not one on the loop’s common path.

@inline(always | never)

@inline(always)
fn clamp(x : i32, lo : i32, hi : i32) : i32 {
    let mut v : i32 = x;
    if (v < lo) { v = lo; }
    if (v > hi) { v = hi; }
    return v;
}

@inline(never)
fn tripled(x : i32) : i32 {
    return x * 3;
}

Overrides the compiler’s own inlining decision, which otherwise follows the size of the body. always asks for the body in every caller, however large it is. never keeps the function a call, however small it is. Without the annotation, the compiler decides, and that is the right default in most code.

always is a request, and the compiler will not fold a body where folding is unsafe. A function that calls itself directly or through a cycle, or that uses the arena, keeps an inlining hint instead of being folded. The annotation is accepted in both cases, and the compiler reports no error.

@inline(always) beside @heat(cold) is a contradiction. One asks for the body in every caller and the other for it out of the hot path, so the pair is refused (E0001).

@layout(packed)

@layout(packed)
extern "C" struct WireHeader {
    tag : u8;
    length : u32;
}

On an extern "C" record, packed refuses padding: every field sits directly after the previous one, and the record aligns to one byte. Use it when the bytes are the contract, as with a wire format or an on-disk header.

Without extern there is nothing outside the program to read those bytes, so @layout(packed) on an ordinary class or struct is refused (E0751). See FFI: extern "C" struct.

@upsert("role")

class Index {
    @upsert("probe")
    pub fn find(self, key : string) : i64 { … }
}

@upsert tells the compiler what a container method does within a lookup-then-insert sequence. The role is a string. The roles are probe, slot_read, slot_write, lookup and insert. When a program performs a lookup and then an insert with the same key, the compiler can fuse both into a single probe of the table. See Loop and idiom rewrites: upsert fusion.

@derive(Trait, …)

@derive(Eq, Ord, Hashable, ToString, Clone)
class Point {
    x : i32;
    y : i32;
    constructor(x : i32, y : i32) {
        self.x = x;
        self.y = y;
    }
}

On a class, asks the compiler to synthesise a standard, field-by-field implementation of each listed trait:

TraitSynthesises
Eqequals
OrdcompareTo
HashablehashCode
ToStringtoString
Cloneclone

A class’s clone is what copy calls to duplicate an object held by a struct (Structs: copy and own).

The expansion happens at parse time, so the generated methods go through normal lowering and stay correct as the class gains fields. The arguments are bare trait names. An unknown name, a quoted argument such as @derive("Eq"), or a collision with a hand-written method of the same name is rejected at parse time. See Generics and traits: @derive.

@target(…)

@target(os = linux)
fn fastPath() : i32 {
    return 1;
}

@target compiles a declaration only for the targets its predicate names. Other targets never see it, so a declaration can carry a platform-specific body without breaking the build elsewhere. The values are bare words, as in os = windows, and the predicate is written once: os = … and arch = … inside one @target(…).

Unknown and misplaced annotations

The two families refuse a bad name through different mechanisms:

  • Declaration sites (above a declaration, method or field) accept any @Name or @Name(args) at parse time, then check the name against the closed vocabulary:

    • an unknown name is E0011, and the closest recognised annotation is named when the misspelling is plausible;
    • a recognised name on a site it does not concern is E0012;
    • a recognised name with a value outside its set is E0011 or E0001.

    An annotation that nothing reads would compile away with its intent unapplied, so it is refused rather than ignored.

  • Loop sites (above a for, while or do-while) accept only four spellings: @vectorize, @vectorize(disable), @vectorize(width: N) and @unroll(N). Any other name there is a parse error.

Limits / Uncabled

LimitWhy it holds
Every annotation value is a literal@unroll(N) and @vectorize(width: N) take a positive integer literal, and @link(symbol = "…") a non-empty string literal. A named constant is not read.
The loop slot accepts four spellings and nothing elseany other annotation above a loop is a parse error
An annotation applies to the declaration it sits aboveit is read where it is written. Nothing propagates it to callers, or to the code a declaration is inlined into.
@vectorize(width: N)’s ceiling follows the target CPUthe check reads the CPU and features the build targets (128-bit by default), not the machine running the compiler
The loop annotations steer LLVM onlythey set a loop metadata flag. A loop with a loop-carried dependence stays scalar whatever it is annotated with.
@inline(always) is a requesta recursive or arena function keeps a hint instead of being folded
@wait is stdlib-onlya program that writes it is refused as an unknown name (E0011)
An unknown name is refused, not ignoredan annotation nothing reads would compile away with its intent unapplied (E0011)

See also

annotationsattributesvectorizereference