machdocs
Home Ecosystem Changelog

Decorators

A decorator attaches metadata to a declaration. It can carry a source-use notice, confine a declaration to tests, acknowledge a warning, or control how the compiler emits the symbol: its linker name, alignment, layout, section or image placement, inlining, dynamic import or export, constant-time obligations, or exclusion from auto-vectorization.

Note

Visibility (pub / ext) is a separate concern. #[export] builds on pub and never replaces it.

Surface

A decorator is written as an attribute clause. A bare flag takes no arguments, and a decorator with arguments takes constant expressions.

#[name]            # bare flag (e.g. naked)
#[name(args)]      # decorator with constant arguments
#[gpu.name(args)]  # a decorator of the GPU set

Every name is lowercase, with snake_case where it is several words. Only the GPU set is dotted: it is a large domain that applies only to shader stages and uses generic words such as input and shared.

Restriction

A line comment that begins #[ with no space opens a decorator. Write such a comment with a separating space: # [...].

Placement

Decorators appear before the declaration they target, one per line or space-separated on the same line. They attach to the immediately following declaration only and do not bleed across declarations. Each decorator stands at most once on a declaration, and a second of the same name is refused.

#[inline("always")]
#[symbol("big")]
fun big(a: i64, b: i64) i64 { ret a + b; }

#[align(64)] #[symbol("g_lit64")]
pub var g_lit64: u8 = 7;

Constant arguments

Every argument is a constant expression: a number is an integer, and every name, mode or path is a string. No decorator takes a bare word, and a mode is an argument of one decorator, never a sibling decorator: inline("never"), not noinline. A literal is a constant, and so is a val, one an $if arm selects, or one imported from another module. A val gated by comptime is how one declaration names a different symbol per target:

$if ($mach.build.sys == $mach.sys.windows) {
    val SPIN: *u8 = "spin_win32";
}
$or {
    val SPIN: *u8 = "spin";
}

#[symbol(SPIN)]
pub fun spin() i64 {
    ret 0;
}

An argument that is not a constant expression, such as a var or a call, is refused. A string only type checking can compute, such as $type_name(T), is accepted by section, inline, vectorize, extension, intrinsic, handle, abi_type, gpu.stage and gpu.builtin. The other decorators are read before type checking, so their strings must be known when the module loads.

The decorator set

The set is closed, and new decorators require a compiler change. A name outside it is refused, and the refusal lists every decorator.

deprecated / deprecated(str) - deprecation notice

Marks a declaration or tag case as deprecated. An optional string argument supplies guidance for consumers. A use from another source module warns at the identifier, carrying the message. Value references, calls and type references are covered, including through imports, re-exports and generic instantiation. The declaring module does not warn on its own uses. On a tag case it is the only decorator the case accepts, and construction, the sel test and the payload place all warn.

# file: src/legacy.mach
#[deprecated("use replacement")]
pub fun old() i32 {
    ret replacement();
}

pub fun replacement() i32 {
    ret 1;
}

pub tag Reply: u8 {
    empty;
    #[deprecated("use fresh")]
    value: i64;
    fresh: i64;
}

A caller in src/bin/main.mach, in project scratch, and the warning mach check prints for it:

use std.runtime;
use scratch.legacy;

fun caller() i32 {
    ret legacy.old();
}

#[symbol("main")]
fun main(argc: i64, argv: **u8) i64 {
    ret caller()::i64;
}
warning[decl.deprecated] `old` is deprecated. use replacement
  @ src/bin/main.mach:5:16
5 |     ret legacy.old();
  |                ^^^

testing - test-only declaration

Marks a declaration as existing only for tests, giving a helper or fixture the semantics a test block already has. It takes no arguments.

# file: src/queue.mach
rec Queue { n: u32; }

#[testing]
pub fun filled(n: u32) Queue { ret Queue{n: n}; }

test queue__drains_in_order {
    var q: Queue = filled(3);              # a test body may use the fixture
}

#[testing]
fun drained() Queue { ret filled(0); }     # so may another testing declaration

pub fun reset() Queue { ret filled(0); }
# error[testing.use] `filled` is a `#[testing]` declaration. only a test body or
# another `#[testing]` declaration may reference it

The mark follows imports. A plain use of a testing declaration is itself testing, so every reference through it is checked, and a #[testing] use confines its alias even when the target is an ordinary declaration. A module the build reaches only through #[testing] use is checked in every build and emitted only by mach test. A fwd of a testing declaration must itself be marked #[testing]. pub #[testing] is valid, and a dependency's testing helper is usable from a dependent's tests.

expect(key, ...) - acknowledge a warning

Acknowledges warnings a declaration raises on purpose. Each argument is a string naming a warning key, or a family of keys, from the diagnostic key table. A warning of a named kind raised inside the declaration, its doc comment and body included, is neither printed nor counted. Warnings elsewhere, and warnings of other kinds, still report.

#[expect("float")]
test float__rounding {
    val x: f32 = 3.14159265358979;   # float.inexact, acknowledged by its family
}

An acknowledgement cannot rot silently: when a key the source alone decides names no warning raised inside the declaration, that is itself a warning. It applies to fun, rec, uni, tag, val, var and test. There is no module-wide form: a profile's allow key silences a warning across the build. A key that covers only errors is refused, since an error is never acknowledged.

symbol(str) - linker name

Overrides the emitted or imported symbol name. Applies to functions and globals. Without it the compiler mangles the mach name, except on an ext declaration, which takes the target's C symbol name. symbol gives the C name, and the linker sees it with the target's C symbol prefix, so #[symbol("main")] is _main on Darwin and the source never spells the underscore.

#[symbol("main")]
fun entry(argc: i64, argv: **u8) i64 { ret 0; }

#[symbol("write")]
ext fun libc_write(fd: i64, buf: *u8, n: i64) i64;

The mangled name is the source FQN as the source spells it, std.types.string.str_len, with generic arguments after a $, so a profile, a crash report and a disassembly all read the name you wrote. A test's symbol is its qualified name, <module path>#<identifier>. There is no prefix: a mangled name always contains a . or a #, and a C identifier never can. A symbol keeps nothing alive by itself: the link keeps a function or global exactly while something it keeps refers to it.

weak(str) - a link-time default

Emits the function under the name given, as a weak definition: the program runs it unless the link holds a strong definition of the name. The replacement is an ordinary strong definition, a #[symbol("name")] function in another module or a definition in a C or asm object the link takes.

# file: src/spawn.mach
#[weak("mach_thread_backend")]
fun backend(entry: *u8) i64 {
    ret -1;
}

The compiler does not check the pairing: it compares no signatures, and a default nothing replaces is never reported. Every call is a call of the symbol, never inlined, so the link's choice holds at each one. It applies to a function with a body, it cannot combine with symbol, inline("always") or testing, and a generic, comptime-parameter or pack function is refused because its instances have no one symbol. A SPIR-V module refuses it.

library(str) - dynamic import attribution

Pins an ext import to a specific dependency in the link set. Applies to ext declarations only, and composes with symbol: the import is emitted under the renamed symbol within the named dependency.

#[library("ws2_32")] #[symbol("WSAStartup")]
ext fun wsa_startup(ver: u16, data: *u8) i32;

export - a shared library's export

Exports a function or global from a shared library under its symbol name. It requires pub (`export` needs `pub`, because a library exports only its public interface), it is refused on an ext declaration, and it is refused on a generic, comptime-parameter or pack function, whose instances have no one symbol. pub alone states a module's interface to other mach modules and never exports. Every definition without export is seen from no other image.

#[export]
pub fun version() u32 { ret 7; }

inline(mode) - force or forbid inlining

Takes one mode, "always" or "never", and applies to functions only. It may stand once on a function, so the two modes never meet.

#[inline("always")]
fun fast_path(x: i64) i64 { ret x * 2; }

#[inline("never")]
fun cold_path(code: i64) i64 { ret code * 100; }

inline("always") expands a function at every direct call the inliner may expand, whatever its size. Without a decorator, an optimizing build expands a direct call where the callee is small. inline("never") forbids inlining a function into any caller. Use it to keep a function's frame and symbol real, for a profiler to attribute its cost, to keep a cold path out of a hot caller, or to hold code size down.

align(expr) - alignment override

Sets the alignment of a global variable, a record, union or tag type, or a function's entry. expr must be a comptime integer: a literal, or a comptime expression such as $size_of(T) or $align_of(T).

rec Pair { a: u64; b: u64; }

#[align(64)]
pub var cache_line: u8 = 0;

#[align($size_of(Pair))]
pub var g_cmp: u8 = 0;

#[align(32)]
rec Over { a: u8; }

#[align(64)]
fun hot(n: i64) i64 { ret n + 1; }

packed - no padding

Lays a rec or uni out with no padding: every field sits immediately after the previous one, there is no padding at the tail, and the type takes no alignment from its fields. On a tag it places the payload immediately after the discriminator. Takes no arguments.

align only ever raises alignment. packed is the inverse, and it exists for the case where the layout is not mach's to choose: a C struct, a file header, a wire frame, a vertex whose stride a buffer fixes.

#[packed]
rec Header {
    magic:    u8;    # offset 0
    version:  u16;   # offset 1
    length:   u32;   # offset 3
    checksum: u64;   # offset 7
}                    # $size_of == 15, $align_of == 1

Naturally the same shape is 16 bytes, aligned to 8. $size_of, $align_of, and $offset_of all report the packed layout, and so does the code that reads and writes the fields.

It composes with align rather than conflicting, and each owns one question: packed decides padding (none between fields, none at the tail) and align(N) decides the record's own alignment, rounding its size up to a multiple of N.

#[packed] #[align(8)]
rec Frame { a: u8; b: u32; }   # fields at 0 and 1, $align_of == 8, $size_of == 8

Packing is not transitive. A packed record packs its own fields. A record it contains keeps its own internal padding and is merely placed without padding, so an inner type's layout does not change depending on who holds it. If the inner record must be packed too, write #[packed] on it as well.

rec Point { x: u8; y: u32; }   # natural: y at 4, size 8

#[packed]
rec Msg { tag: u8; p: Point; } # p at offset 1, still 8 bytes, $size_of(Msg) == 9

What is refused

Target note

Every access to a packed field states the alignment its offset admits. x86-64 and aarch64 do unaligned scalar access in hardware, so on hosted targets a packed field access is one load or store. Freestanding aarch64, riscv64 and riscv32, which fault on such an access, split it into the widest accesses the alignment admits. On riscv64 Linux an unaligned access may trap and be emulated by the kernel, which is correct and slow.

volatile - every access to the type is volatile

On a rec, uni or tag, makes every load and store of that type's storage volatile: the optimizer keeps each one, in program order, at the width written. Takes no arguments, and applies to nothing else. Volatility is a property of a declared type, so a memory-mapped device is a volatile record whose address is cast to a pointer to it:

#[volatile]
rec Fb {
    status: u32;
    px:     [1024]u32;
}

fun fill(c: u32) {
    val fb: *Fb = 0xB8000::*Fb;
    var i:  u64 = 0;
    for (i < 1024) {
        fb.px[i] = c;   # one volatile store per iteration
        i        = i + 1;
    }
    fb.status = 1;      # a volatile store, ordered after the loop
}

The access decides by the storage it reaches. A member, an index, a dereference, a whole-record copy and a field of a plain record stored inside a volatile one are all volatile. An indirection ends the walk: what a pointer field points at is ordinary storage unless its own type says otherwise. volatile is compatible with packed and align.

section(str) - object section placement

Places a function or global variable in a named section instead of the default .text / .data. The section is created if absent, and cross-section calls and accesses use ordinary relocations.

#[section(".hottext")] #[symbol("f_hot")]
fun f_hot(x: i64) i64 { ret x + 1; }

#[section(".machsec")] #[symbol("g_sec")]
pub var g_sec: u64 = 100;

A named section is one unit to the link: it keeps all of it while anything it keeps refers to any symbol in it. Naming a section keeps nothing, so a table the hardware reads by address is stated with #[at] or referred to from the entry's code.

at(offset) - placement in the image

Places a module val or var at an integer offset in the image, counted from the start of the memory region it runs in, or from the image base. The global becomes a section of its own, and the link keeps it whether or not anything references it. It cannot combine with section or thread.

#[at(510)]
val SIGNATURE: [2]u8 = [2]u8{0x55, 0xaa};

It works on a flat image and on a freestanding ELF image. A system whose loader maps the image places it where it chooses, so there the link refuses it: the system's loader places the image it maps, so a stated offset is refused.

thread - a thread-local module var

Gives each thread its own copy of a module-level var. Applies to a var only, and its constant initializer is the template each thread's copy starts from. Nothing runs when a thread exits.

#[thread]
var depth: u32 = 0;

An executable reaches its thread-locals at offsets its link fixes, and a shared library at offsets its loader fixes when the process starts. The address of a thread-local is no constant, so a module binding cannot be initialized with one.

constant_time(mode) - constant-time boundary

Marks a function as a constant-time boundary. It takes one mode, "soft" or "hard", which is required. Inside it, in either mode, the emitted code may not branch on a secret, use a secret as an address, or run a variable-time instruction on a secret, and a callee that receives a secret must be constant time itself. The build proves this on the encoded code.

#[constant_time("hard")]
fun ct_eq(a: ^[8]u8, b: ^[8]u8) ^u8 {
    var d: ^u8 = 0;
    var i: u64 = 0;
    for (i < 8) {
        d = d | (a[i] ^ b[i]);
        i = i + 1;
    }
    ret d;
}

It applies only to a function with a body, since the build proves the mark by walking the code it compiles. No function is required to carry it: a function that computes on a secret without it compiles with no promise about its timing. Inline asm inside such a function is validated rather than rejected. The mark is refused on a SPIR-V target and warned on wasm, where the instructions that run are decided downstream. On a def of a function type it marks the type with the mode instead, so a value of the alias holds only a function declared constant time in that mode or a stronger one:

rec Key { k: [32]u8; }

#[constant_time("soft")]
def Seal: fun(^Key, *u8) u64;

See Secrecy for the model.

vectorize("never") - opt out of auto-vectorization

Excludes a function from loop auto-vectorization, so its loops compile to scalar code even in an optimizing build on a vector-capable target. Applies to functions only, and takes one mode, "never".

use std.types.size.usize;

#[vectorize("never")]
fun reference_sum(a: *i64, n: usize) i64 {
    var s: i64   = 0;
    var i: usize = 0;
    for (i < n) {
        s = s + a[i];
        i = i + 1;
    }
    ret s;
}

A #[vectorize("never")] function is declined by the inliner both ways: it is not expanded into a caller, and no call inside it is expanded. Use it for a scalar reference twin in a differential test, or where vectorized code is undesirable for one function. For a whole build, vectorise = false under a profile's [profile.For a whole build, vectorise = false in a profile's [profile.<name>.passes] table leaves vectorization out.lt;nameFor a whole build, vectorise = false in a profile's [profile.<name>.passes] table leaves vectorization out.gt;.passes] table leaves vectorization out.

naked - no prologue, no epilogue, body as written

Emits the function's body exactly as written and nothing else: no frame-pointer record, no stack allocation, no callee-save stores, no argument moves, and no return. Applies to functions only and takes no arguments.

#[naked] #[symbol("_start")]
fun start() {
    $if ($mach.build.arch == $mach.arch.x86_64) {
        asm x86-64 {
            mov rdi, [rsp]
            lea rsi, [rsp+8]
            call main
        }
    }
    $or ($mach.build.arch == $mach.arch.aarch64) {
        asm armv8-a {
            ldr x0, [sp]
            add x1, sp, #8
            bl main
        }
    }
}

The programmer owns the frame, the stack alignment, the link register, and the return: a reset vector, an interrupt handler that must return with iret / rti, a syscall or context-switch stub, or a thread entry point whose register state at entry is the interface.

Merely containing an asm block does not suppress a frame: a function that also makes a call gets one.

noreturn - control never comes back

A function marked #[noreturn] never returns to its caller, and an asm block marked #[noreturn] never falls through to the statement after it. Takes no arguments.

#[noreturn]
pub fun exit(code: i32) {
    $if ($mach.build.arch == $mach.arch.x86_64) {
        #[noreturn]
        asm x86-64 {
            mov edi, {code}
            mov eax, 60
            syscall
        }
    }
    $or { $error("no exit for this architecture"); }
}

extension(names) - an outlier function

Lets one function use instruction-set extensions the target does not select. Applies to a function with a body, once, and takes one or more extension names, each a string, spelled as the manifest's ext key spells them.

#[extension("sha", "ssse3")]
fun compress_sha_ni(state: *[8]u32, block: *[64]u8) {
    asm x86-64 {
        sha256msg1 xmm0, xmm1
    }
}

fun compress_portable(state: *[8]u32, block: *[64]u8) {}

fun compress(state: *[8]u32, block: *[64]u8, has_sha_ni: u1) {
    if (has_sha_ni) { compress_sha_ni(state, block); }
    or              { compress_portable(state, block); }
}

Inside the function, inline asm may use every instruction the named extensions admit, and the compiler builds the function's own code under the same widened selection. The caller owns the run-time check. Calling an outlier on a processor that lacks one of its extensions is undefined behaviour, typically an illegal-instruction trap. The compiler neither inserts the check nor verifies that one precedes the call.

embed(str) - compile-time file embedding

Sources a val's bytes from a file at compile time: the file's content is the initializer. Applies to val only, not var (the storage is read-only data) and not an ext data import. Takes one constant string.

#[embed("assets/logo.qoi")]
val LOGO: [_]u8;          # length taken from the file's byte count

#[embed("boot/sector.bin")]
val SECTOR: [512]u8;      # length pinned, a size change fails the build

abi_type(name) - a C type whose layout the target declares

A bodyless def carrying this decorator declares a C type whose size and alignment come from the selected target and whose contents the program never reaches. va_list is the only name. A value of one may be received as a parameter and passed on, and nothing else. See External functions.

#[abi_type("va_list")]
pub def VaList;

GPU decorators

The gpu. decorators shape a pipeline stage and its workgroup, the shader interface and specialization constants: gpu.stage, gpu.workgroup, gpu.input, gpu.output, gpu.builtin, gpu.uniform, gpu.storage, gpu.sampler, gpu.attachment, gpu.push, gpu.spec and gpu.shared. With them stand handle, which declares a type the target mints, and intrinsic, which makes a function a target instruction. They are accepted on every target, because which target a module is built for is not a property of its source. Each is documented on GPU shaders.

Applicability

Where each decorator stands. A decorator written anywhere else is refused.

DecoratorStands onOnly on
deprecatedfun, rec, uni, tag, def, val, var, use, fwd, a tag case
testingfun, rec, uni, tag, def, val, var, use, fwdnot an ext declaration
expectfun, rec, uni, tag, val, var, test
symbol, sectionfun, val, var
weakfuna function with a body
libraryext
exportfun, val, vara pub declaration that is not ext
inline, vectorize, nakedfun
alignfun, rec, uni, tag, val, var
packedrec, uni, tagnot a GPU interface block
volatilerec, uni, tag
atval, varnot ext, section or thread
threadvarno shader interface role
constant_timefun, defa function with a body, or an alias of a function type
noreturnfun, ext, an asm statementa function that states no result
extensionfuna function with a body
embedvalnot ext
intrinsicfun
handle, abi_typedefa def with no type
gpu.stagefun
gpu.workgroupfunwith #[gpu.stage("compute")]
gpu.input, gpu.output, gpu.builtin, gpu.uniform, gpu.storage, gpu.sampler, gpu.attachment, gpu.pushval, varan input is a var
gpu.spec, gpu.sharedvar

v6 spellings

A v6 spelling is refused naming its v7 spelling, and mach migrate rewrites each one.

v6v7
#[inline]#[inline("always")]
#[noinline]#[inline("never")]
#[scalar]#[vectorize("never")]
#[oblivious]#[constant_time("soft")] or #[constant_time("hard")], and mach migrate writes the first
#[ext(a, b)], #[extensions(a, b)]#[extension("a", "b")]
#[op(tgt, set, name)]#[intrinsic(tgt, set, name)]
#[stage] ... #[shared]#[gpu.stage] ... #[gpu.shared]

See also

  • Testing - test blocks, whose semantics testing gives a declaration
  • Visibility - pub / ext, the separate concern decorators never touch
  • Intrinsics - $size_of and $align_of as align arguments
  • Secrecy - the ^ qualifier and the constant_time contract
  • Inline assembly - what a naked function's body may contain, and what extension admits
  • GPU shaders - the gpu.* decorators, handle and intrinsic
  • Manifest - the [link.X] requirements a library pin resolves against