Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

yaffle IR: semantics

The types live in packages/compiler/src/ir/ir.ts. This document says what they mean. It is the contract between the frontend (which produces IR) and the backends (which turn IR into code). Both sides must follow it.

1. What the frontend has already done

  • Monomorphized. Generic structs are instantiated per distinct type argument list, type aliases are inlined, pure fn declarations and let bindings are inlined, constants are folded, and imports are resolved. Every struct referenced anywhere is in program.structs.
  • Lowered scoping. Bound values ($version) become implicit parameters (origin: "bound"). Each use site passes them explicitly in IrStructType.args. $endian is the implicit endian parameter (origin: "endian", value type { kind: "endian" }). A struct with usesEndian: false may ignore it.
    • Parameter order. IrStruct.params is always: endian (default le) first, then the declared parameters in declaration order (explicit, and declared $ parameters with origin bound), then implicit bound parameters sorted by name. Every struct has the endian parameter, even with usesEndian: false.
    • Implicit names. A lowered $version is the parameter version (boundName: "version"), suffixed with _bound if a declared parameter already has that name. A use site passes a field of the current struct if it binds the value before the use, and the current struct’s own implicit parameter otherwise.
  • Resolved derivation. Every value the writer computes (derived, computed and constant fields) has a derive expression, except the bytes of from stream sources (§3.7). Pointer fields (T *p : S) lower uniformly to a hidden slot _ptr_<name> (type S, derived as the target offset) plus the target field <name> carrying placement.
  • Normalized expressions.
    • Constants are folded where the operands are literals, including enum and const references and sizeof(Type) of fixed-size types.
    • Arithmetic (+ - * / % << >> & | ^, unary - and ~) always has type bigint or float (f64), and both operands have exactly the result type: the frontend inserts convert on integer fields. Comparisons don’t convert when both sides already have the same type. An integer literal compared with an int field takes that field’s type (version >= 3 compares two u32).
    • String lengths are never len(<string>). Derived string lengths and s.length use encodedLength(s, unit, encoding), divided by unit for 2- and 4-byte units. len is used for arrays and bytes.
    • x == null is isNull(x) and x != null is !isNull(x). There is no null literal.
  • Inferred value types. The value type of an integer transform is the smallest standard integer type (u8/u16/u32/u64, i8/…/i64) holding the read expression’s static range (interval analysis); unbounded or beyond 64 bits gives i64 (u64 if non-negative). The read expression’s own type stays bigint. Untyped constants (const N = 4) get a type the same way.
  • Complete bit units. Every IrBits unit’s fields cover the whole storage unit: bits not declared become an implicit reserved field (name: null), so strict checks are well defined.
  • Checked: names, types, bindings on every path, layout paths, invertibility, and layout cycles. A program that reaches a backend is valid.

2. Reading

2.1 Context

A read happens in a context with:

buffer / sourcethe bytes (sync or async, random access)
posabsolute position of the next inline byte
baseabsolute position of the current base. The file start (0) at the root, changed by @base structs
endabsolute end of the current region: the source size at the root, narrowed by @size layers and by the extent of a codec’s decoded output
indexthe index of the element being read, inside arrays
strictwhether strict checks are on (root option, struct strict, or a strict layer)
paramsthe struct’s parameter values

$offset = pos - base, $end = end - base, $index = index, $count = enclosing array element count. All offsets in expressions are relative to the base. Absolute positions never appear in values. On read, sizeof(f), offsetof(f) and bytesof(f) of an earlier field measure its bytes as read; encode(f) of a field behind a codec is its plain encoding (the value read, encoded without the field’s layers), not its bytes on disk.

2.2 Members in order

Members are read in declaration order. Each field’s value becomes visible to later expressions under its name. Blocks and switches don’t introduce a scope: their fields are visible after them, as if declared inline. A field from a branch not taken is “absent”: reading it in an expression is a frontend error unless the expression is guarded. The frontend guarantees this.

A name may be declared again in an exclusive branch (another case of the same switch, the other branch of an if/else). Those are distinct fields sharing one key: each has its own type, checks, derive and input. A field reference means the declaration whose branch the reference sits in; from outside the branches it means whichever declaration was taken (the frontend allows that only when their value types agree).

  • Inline field: read its type at pos and advance pos by the bytes consumed.
  • placement: evaluate nullWhen (if present): when true, yield null (or [] with emptyIsNull) without reading or moving pos. Otherwise evaluate offset and read the type at base + offset without moving pos (after inline members finish when deferred: true, e.g. @origin(offsetof(laterField))). The region’s end stays the same, except for a target at or past the end of the @size windows being read (where the writer lays targets out, after the base’s inline bytes): it is read up to the end of the byte space (the source, a codec’s decoded output or a stream). Identity: within one parse, the same target address and the same target type yield the same value object (struct arguments, lengths and the target’s own size window sizes are part of the type). Reading a @ref (ownership: "ref") target must not expand the referring @base struct’s maxEnd.
  • from: build the stream (§2.8) and read the type from it as a fresh region (base = 0, end = stream length). pos doesn’t move.
  • virtual: the field occupies no bytes. Evaluate virtual.read (type bigint, earlier fields only) and range-check the value against the field’s declared type, which is an integer prim (RANGE, like any typed location, §6). Nothing is read with the prim.
  • Checks: after reading the value, evaluate every check with it = the value. A false check is a CHECK error (CONFORMANCE.md §Errors). Strict-only checks run only in strict mode. A deferred check (@verify on a computed field: it == formula) is evaluated once the struct’s members are read, so the formula may read later fields; with zeroSelf, bytesof(this) / encode(this) inside it zeros this field’s own bytes and any later zeroSelf fields in dependency order. Its error has the field’s path, and inside a union variant it rejects the variant. Writers skip checks marked deferred and store the formula.

2.3 Types

TypeRead
primlittle/big endian per endian (inherit = the endian param). u24…i56 are N-byte integers; signed values are two’s complement and sign-extended. f16 is IEEE half.
dynIntdynamic-width integer (width 0..8 bytes, signed, endian). width == 0 reads 0; out-of-range widths are RANGE.
boolone byte; nonzero → true (strict: anything other than 0 or 1 is a CHECK error).
stringsee IrStringType in ir.ts: count, until (arbitrary code-unit delimiter expression), or rest ($end - reserveEnd). Invalid UTF-8/16/32 is a CHECK error. ascii rejects bytes ≥ 0x80. latin1 maps bytes 1:1 to U+0000–U+00FF.
bytescount, until (terminator byte or untilPredicate), while, or rest up to end - (reserveEnd ?? 0).
arrayelements per length. until: read an element, stop if it equals the terminator (compared as values). untilPredicate: read an element, stop if the predicate holds for it (it = the element); that element is included. while: evaluate condition before reading each element (including peek<T>(delta) lookahead) and stop when false. rest: read elements while pos < end - (reserveEnd ?? 0). If an element crosses end, that’s EOF. With elementPlacement, element i obeys nullWhen (yielding null or [] if emptyIsNull), else reads at base + elementPlacement.offset($index = i); with rest, stops when that offset ≥ $end. Inside element types/arguments, $count is the count and arr[0..$index] slices previously decoded elements.
structevaluate args in the caller’s context, then read the struct’s members. If the struct is base, set base = pos (or the placement address) for its contents and advance pos to max(pos, maxEnd) on exit. Struct-level layers wrap the struct inside any use-site layers (boundStructLayers substitutes parameters).
enumread the storage prim. An unknown value is a CHECK error unless open; open unknowns are returned as plain integers.
externcall host size(view, ...args) with a view starting at pos. undefined means “need more bytes”: give a longer view, and at end that’s an EOF error. Then read(bytes[0..size], ...args). With fixedSize, skip size().
uniontry each variant at pos. The first that reads without error (checks included) wins. If none does, that’s a UNION error listing each variant’s error.
transformread inner, then evaluate read with it = the inner value.
layeredapply the layers from outermost (last) to innermost (first) around reading inner (§2.4).

2.4 Layers on read

Processed from the outermost layer inwards:

LayerRead behaviour
align(to)skip forward until (pos - origin) % to == 0. Strict: the skipped bytes must equal the fill.
padBefore(n) / padAfter(n)skip n bytes before or after the inner content.
alignEnd(to)after the inner content, skip until (pos - origin) % to == 0. On a @base struct (and the root), the struct-level layer pads its whole region, after its targets; the writer writes its fill there.
size(n)narrow end to pos + n, read the inner content inside it, then skip/verify remaining padding up to pos + n using fill (default 0; checked when strict is set on the layer or in strict mode). Window overrun/underrun is EOF.
via(codec, args)take the encoded bytes: the window [pos, end), unless the codec is streaming, in which case it reports how many bytes it consumed. Decode them and read the inner content from the decoded bytes as a fresh region (base = 0, end = decoded length). Then pos advances by the encoded length. If an inner size layer exists, its value is passed to the codec as outputSize.
endian(v)evaluate v (outside the layer) and use it as the endian argument for everything inside.
strictturn on strict mode inside.
  • Alignment origin. align and alignEnd measure from the current base by default. With from: "file" they measure from the start of the current byte space: the root source, a codec’s decoded region, or a stream, i.e. whatever $offset would count from if there were no @base in between. The frontend emits from only as "file".
  • Strict padding. A padding layer (align, alignEnd, padBefore, padAfter, size) with strict: true checks its own fill on read even outside strict mode. It may appear on field, block and struct layers.
  • Endian layers rebind $endian: inside one, both endian: "inherit" and every { kind: "param", name: "endian" } expression, including the endian argument passed to nested structs, mean the layer’s value.

Padding fill: { kind: "byte" }, or { kind: "fn" } evaluated per byte index (0-based within that padding run), keeping the low 8 bits.

2.5 Bits

Read the storage unit (prim, endianness per endian). Field value = (unit >> shift) & mask(width), sign-extended for signed prims, converted for bool/enum. A transform bit field reads its inner type that way, then applies read (and on write stores write(value) in the bits). Reserved fields (name: null) must be zero in strict mode.

2.6 Switch and blocks

  • Block: evaluate condition. If true, read members, otherwise else (if any). Apply layers around the members.
  • Switch: evaluate the discriminant, then read the members of the first case matching any value or inclusive integer range ({ kind: "range", low, high }), else default. If nothing matches and there is no default, that’s a CHECK error.

2.7 Errors

Every error carries a path (field names and array indices from the root; the synthetic _ptr_ prefix on pointer slot fields is stripped from paths) and an absolute offset. Codes are in CONFORMANCE.md.

2.8 Streams

  • field: that bytes field’s value (the decoded bytes).
  • each: the bytes field of every element of the array field, joined. from.split is present only for each streams.

Lazy implementations may decode pieces on demand. If every piece has a fixed decoded size, or the sizes are known from fields, an offset maps directly to a piece.

3. Writing

3.1 Input values

The writer takes an input value shaped like the generated input type: every field with input: "required", optionally fields with input: "optional", and never fields with input: "absent". If an absent field is present in the value, it is ignored. That way serialize(parse(bytes)) works directly.

The field kinds of DESIGN.md §1 map to these properties: an input field is input: "required" (with a derive only when it is normalized); a derived field has deriveKind: "auto" (stream split points and @origin/?= optional offsets are also input: "optional"), except that fields consumed by a from stream are input: "absent" without a derive (§3.7); a computed field has deriveKind: "formula" and input: "absent"; a constant has deriveKind: "constant" and input: "absent"; an optional field has its default or fallback expression as derive and input: "optional".

An input: "optional" field with a derive is used as given when the input has it; otherwise the writer evaluates derive. Inside such a derive, it stands for the field’s input value, which is then required: evaluating it when the input leaves the field out is an INPUT error naming the field (“missing required field”). The frontend uses this for fields measured only in some branches (DESIGN §4): length = k == 1 ? encodedSize(d, 0) : it. The write-only builtin given(field) tests whether the input gives a field: a size that is also its block’s condition derives as given(d) ? (len(d) != 0 ? len(d) : it) : 0. A transform field’s derive is its value (the writer stores it through write), like its input value.

A struct-typed field (or an array of structs) with memberFills fills in members of its value(s) that the input leaves out, before anything reads them: H h T arr[h.count] gives h memberFills: [{ member: "count", value: len(arr) }], and H.count is input: "optional" with it as its derive (required where nothing fills it). With each, value is an array and element i’s member gets value[i]. Backends fill a copy; the caller’s input is not changed. A member the input gives is used as is, and checked by the expressions that read it as before.

  • A derive that uses it normalizes the input (u32 flags = it | 0x80): it is the field’s input value, the field stays input: "required", and the writer stores the value of derive. A derive without it comes with input: "absent" or "optional".
  • A default (u32 align ?= 0x100) is input: "optional" with the default as derive, deriveKind: "formula" and no check.
  • A virtual field’s value comes from the input (required, or optional with its default as derive), or, used as a length, size or offset, is derived (absent with a derive). It is inverted on write, so its parts are derived from it: their derive expressions use >>, &, /, %, + and - on the virtual field’s value, with deriveKind: "auto" and input: "absent" (parts may be bit fields). A virtual field is never a part of another one. After writing, virtual.read must give back the input value, otherwise it’s a DERIVE error.

3.2 The write context and derive

derive expressions are evaluated in the write context:

  • field references read the input value, or the value of derive for fields that have one. Such fields may reference each other as long as there is no cycle (the frontend checks this).
  • sizeof / encodedSize / bytesof / encode take the field’s final encoding.
  • offsetof takes the field’s final position (from the base).
  • $index is the element index, and params are as on read.
  • A derive never reads another struct’s derived or computed field through member when that field’s own derive is a plain value formula: the frontend substitutes it (recs[n - 1].size becomes recs[n - 1].data.length; the plain size of a byte array, encodedSize(d, 0) or sizeof(d) without layers, as its length), so the formula sees the derived value, not a stale input. A normalizing formula of a required input (u8 n = k == 1 ? 5 : it) is substituted the same way, it being the member (c.n becomes c.k == 1 ? 5 : c.n).
  • Struct arguments are shared by the reader and the writer, so a member access in one is substituted only where both read the same value by construction: a count (u8 n u8 d[n], or E es[n]) and the @size of a byte array that reads to its window’s end (u8 n u8 d[] @size(n)) are read as the array’s length (T(es[0].n) becomes T(es[0].d.length), converted to the field’s type). Any other derived or computed field of another struct is read from the input as it is (a stale value after an edit must be corrected by the caller).
  • sizeof of a member of another struct’s value encodes that value again (codecs included, without reuse, §3.6); only elements of the array being read or written are measured where they are (elementSizes).
  • A field rebuilt by a from stream of its struct (u8 d[n] @hidden In x from d) is read from another struct’s value as written(p.d): the bytes the writer wrote for it. The frontend wraps such member accesses; a derive using written is computed once everything is written (like one using bytesof), and a backend records each carrier it writes by the value’s identity.
  • $offset in a condition or length (evaluated while writing) is the position from the base. It is exact in the base’s own inline bytes and inside a fixed placement (whose start is its offset, known before layout); inside a target the layout places it is a DERIVE error (“$offset depends on the layout”). A derive using it is computed after layout.
  • $end is the end of the enclosing @size window or region once it is written, so expressions using it are evaluated after layout. A block condition using $end takes the branch whose input fields are given (the then-branch when any of its input fields is present), and must agree once $end is known (DERIVE otherwise).

A derived field’s final value can depend on positions that are only known after layout, e.g. u64 tableOfs derived from offsetof(table). Recommended writer shape (relocation style):

  1. Encode bottom-up into nodes: inline bytes plus a list of fixups (position, width, endianness, closure computing the value from final sizes and positions) plus a list of placeable targets.
  2. Run layout (§4) to assign every target a position.
  3. Evaluate and patch the fixups: offsets, then @ref pointers, then formulas over final bytes, innermost struct first and, within a struct, in ascending contentRank (a formula after the ones whose bytes it covers).
  4. Concatenate.

The frontend rejects layout cycles, i.e. a derived value whose own size depends on a position. Variable-size derived fields (such as uleb128 holding @size) that measure a field or block mark that target preEncode: true: the writer pre-encodes it once before the variable-width field so its encoded size is known in time, and reuses those encoded bytes when emitting it. Writers pre-encode the marked members of a member list before writing any of them, so when the target sits in a later block that doesn’t hold the variable-width field (if (c) { uleb128 n } if (c) { u8 d[] @size(n) }), the outermost such block is marked instead (a target inside a later switch is marked itself). For zeroSelf fields measuring bytesof(this) / encode(this), the field’s own inline bytes (and later higher-rank zeroSelf fields) read as zeros during evaluation.

3.3 Consistency

After writing, every field with a derive must satisfy its checks. The read-side expressions must agree with what was written: an array written with N elements whose length expression evaluates to M ≠ N is a DERIVE error, and so is a constant that would read back differently. A transform with write must round-trip: read(write(v)) == v, or it’s an INPUT error. Backends may skip the round-trip check for float transforms when the difference is below the half-ulp of the storage.

An untilPredicate array must end with an element satisfying the predicate, and no earlier element may satisfy it. For while conditions that do not inspect peek or $end, each written element must satisfy the condition.

3.4 Placements and pointers on write

Pointers (T *p : S) use the same placement mechanism as at fields (with the pointer’s storage encoded in hidden _ptr_<name>, whose derive is offsetof(name) minus optional origin, or nullWhen sentinel):

  • owned (ownership omitted or "owned"): the target is a placeable in the current base (the nearest enclosing @base struct, or the root). If nullWhen holds, no target is placed and the writer verifies nullWhen agrees with whether the input is null / empty (emptyIsNull), throwing DERIVE on mismatch.
  • Identity: two placements with the same object (reference identity in the input) and the same type share one target, unless they are fixed at different offsets. A placement whose value is an inline struct value written elsewhere (the struct holding it, or an ancestor) points at that inline value instead of writing a copy. Deduplicating equal values happens only for ref placements.
  • ref (ownership: "ref"): the placement gets the offset of the input object itself if it was placed, otherwise of an already-placed, equal value of the same type: an element of an inline array, a field, or another target. Equality is equality of encodings. The current base is searched first, then the enclosing ones. If no such value exists, that’s a REF write error. When several match, the first placed wins. Note that escalated @ref offsets targeting an earlier position in an enclosing base may be negative; fixup resolution tracks a boolean resolved flag rather than pos >= 0.

3.5 Layers on write

These mirror reading:

  • size: padded with fill (default 0) up to size. Content larger than size is a DERIVE error, and a fills window (content that reads to its end) is never padded (shorter content is a DERIVE error too, as it would read back longer).
  • via: encode the inner bytes with the codec. With an inner size layer, pass outputSize.
  • Fill bytes come from fill.

3.6 Codec reuse (byte-exact rebuilds)

If a value came from a parse (same process, tracked by object identity) and the decoded content of a via region is unchanged (and so are the codec’s arguments), the writer reuses the original encoded bytes instead of re-encoding. Views get this naturally. The same applies to from pieces.

The origin of a region is remembered by the struct holding the field, keyed by the field’s slot, the layer and the indices of the arrays between the struct and the region (a struct inside the region may also remember it itself). So content without an identity of its own is reused too: strings, array elements, bytes rebuilt on write from the fields read from them (a carrier, @hidden or not), and the encodings of from fields through a codec.

3.7 Streams on write

  • from field: the consumed bytes field is input: "absent" and derived from the field read from it. It stays an output field unless hidden. A from field in a conditional branch is encoded only when its branch is taken; when the fields consuming a stream don’t cover every path, the consumed field is input: "optional" without a derive: the input’s value where none is taken.
  • from arr[*].piece: in the element struct of arr, piece is input: "absent" (its content comes from the stream), and fields whose derive measures it (encodedSize(piece, i)) are input: "optional": split points, used when given for byte-exact rebuilds, otherwise from.split decides. With fit, piece k’s block ends at the next higher offset among the elements’ offsets (probed in order until one is a RANGE error, the end of an offset list), not at element k+1’s: pieces at out-of-order offsets fit. The last piece (element k+1 has no offset), and a piece with no higher offset, take the rest.

4. Layout: placing at and pointer targets

4.1 Placeables

Within a base, a placeable is a field with placement (unless fixed, trailer, or ownership: "ref"). Each placeable has a unit: its own inline bytes (“this”) plus the units of its own placeables, ordered by its struct’s layout (default: this first, then its placeables in declaration order, recursively, i.e. pre-order depth-first). A nested @base struct’s unit is self-contained: its placeables are laid out inside its own region.

For a placed @ref array (elementPlacement.ownership === "ref"), the array elements themselves are not owned placeables (hasPlaceables is false), while a placed pointer slot array _ptr_<name> registers in the struct’s layout map $L under <name> so layout { <name> } orders the pointer table cleanly.

A placement is fixed: false when its offset expression uses a field derived from the target’s own position (offsetof(target)), or a field whose value is known only after layout: its formula (directly or through other fields) uses a position (offsetof, offsets, $offset), or the size or bytes of a placed target or of a field declared after the placement (at ofs + size where ofs and size describe another target). The layout places such a target, and the writer then checks that the offset expression gives its position (DERIVE otherwise). Constants, parameters, inputs and fields derived from values or from the sizes of earlier inline fields (at n + 2 with n derived from d.length) make it fixed: the writer evaluates the offset where the placement is written. trailer (at $end - K) places the target at the trailing end of the region after all laid-out placeables (moving forward cleanly with alignment/constraints). constraint comes from derived linear offsets (at sector * 0x800 → modulus 2048, remainder 0). An offset with optional derivation (at base + start, or ?= offsetof(data)) makes start input: "optional" and the placement fixed: false with givenBy: ["start"]: when the input gives every givenBy field the writer places the target exactly at the offset, otherwise the layout does, at no less than min (base, for an unsigned start).

An array placed element-wise (elementPlacement) has one placeable per owned element. Its elements are fixed at their offsets, unless elementPlacement.givenBy is set (T items[n] at offsets[$index]), where offsets is input: "optional" with derive: offsets(items): when the input gives offsets, each element goes exactly at its offset; otherwise the elements are laid out in order and offsets is derived afterwards. The derived offsets has one element per element of items: when the count is known only after layout (let n = bytesof(h)[2] over a header whose size the writer fills in), the writer reserves that many and checks the count after layout. elementPlacement.laidOut marks an offset known only after layout, by the rule above (a pointer array Record *recs[n] : u64, whose slots are offsets(recs)): the elements are laid out in order, and the same object placed twice is one target.

4.2 Base region

[base inline bytes][placeables per the base struct's layout][trailers]. A base’s this is always first, because offsets count from it.

4.3 Layout items

Each placeable is placed at most once. The rules below are what the TS runtime’s layout.ts implements. The other runtimes port it, and the language service’s layout simulator (layoutSuggest.ts) mirrors it.

  1. Claims first. Before anything is placed, every placeable named by any item of a container’s layout is claimed by that item and removed from every other unit, even when an earlier x[*] item would otherwise reach it (pulling groups out).
  2. Then items in order:
    • A path naming a placeable field (curves, records[*].model, volumes[*].pieces[*]) places the unit of each placeable it matches.
    • A path naming inline data or [*] elements (records[*] where elements are inline in the records target) places the remaining units of all placeables reachable from those elements, in their own layout order.
    • this places the struct’s own inline bytes.
  3. this comes first in a unit unless an item names it.
  4. Leftovers (placeables no item placed) follow the items in default order.
  5. Empty targets (empty arrays and strings) are placed at the current position after alignment, and a writer accepts any stored offset for them: one at a given offset stays there and takes no room, past the end too (it neither extends the region nor moves the running position).
  6. Fixed placements go exactly where their offset says. When layout reaches one, the running position moves to its end if that is further on.

4.4 Alignment and constraints

  • Item layers (align) apply to every structure placed by that item, unless a nested layout item specifies its own.
  • Placement constraints (constraint) add an alignment-like requirement: the writer moves the position forward to the next value ≡ remainder mod modulus.
  • Gaps are filled with zero.

Layout items that read fields. Arguments of a layout item’s layers (@align(align), @align(1 << shift)) are evaluated in the write context of the struct that owns the layout: its fields (input values, or their derive), its parameters and $index where applicable, the same as its computed fields. They never see fields of the placed target, so recs[*].body @align(count * 2) uses the container’s count. Any alignment, constant or not, must be at least 1; 0 or a negative value is a RANGE error, even when the item places nothing (arguments are evaluated per instance, like computed fields). Arguments can’t depend on sizes or positions (sizeof, offsetof). Conformance: conformance/cases/layout-fields.

4.5 Fixed placements and overlaps

A fixed placement goes exactly at the given offset, and overlapping another placed byte range is an OVERLAP error. The same applies to elementPlacement arrays: element i goes at its computed offset, and must not overlap element i+1.

5. Codecs, extern functions and extern types (host side)

Host implementations are found through yaffle.json targets.<lang>.externs[name] (a module path per target). Shapes in TS:

// extern fn pathHash(char path[]) -> u32
export function pathHash(path: string): number;

// extern codec zstd / extern async codec oodle / … @ranged
export const zstd = {
  decode(input: Uint8Array, ctx: { args: unknown[]; outputSize?: number; position?: number }): Uint8Array, // or Promise for async
  encode(input: Uint8Array, ctx: { args: unknown[]; position?: number }): Uint8Array,
};
// @ranged: decode/encode may be called on any slice; ctx.position is the slice's offset within the encoded region.
// @streaming: decode returns { output: Uint8Array; consumed: number } and gets the rest of the region as input.

// extern type VarInt(u8 maxBytes) : u64
export const VarInt = {
  size(bytes: Uint8Array, maxBytes: number): number | undefined,
  read(bytes: Uint8Array, maxBytes: number): bigint,
  write(value: bigint, maxBytes: number): Uint8Array,
};

Arguments and results use the target’s value types (the same as in the generated API, see each target’s page). In particular enum values cross the boundary as the target’s enum value, both ways: extern fn arguments and results, and the values an extern type with an enum value type reads and writes. In TS that is the member name (a string; a number for an unknown value of an open enum), in Go, C#, Java, Python, Rust and C++ their generated enum type. A host may return the storage integer instead (a number in TS, an int in Python, a Number from a Java extern type, a cast integer in Go, C# and C++): the runtime converts it to the member. An unknown value of a closed enum is a CODEC error; an unknown value of an open enum passes through as it does when read from bytes.

Built-in extern types: uleb128 (value u64) and sleb128 (value i64) have builtin: true, module: "" and exactly those ids. Every runtime implements them; they need no externs entry. Built-in codecs that need no host: none. Built-in functions (crc32, adler32, …) are implemented by each runtime.

6. Expressions: integers, floats and built-ins

  • Exact arithmetic. Integer expression arithmetic is mathematically exact: no wraparound. A result is checked when it lands in a typed location (array length, offset, field, argument). Out of range is a RANGE error.
  • Division truncates toward zero. % takes the sign of the dividend. Division by zero is a RANGE error.
  • Shifts: the shift count must be in 0..63. >> is arithmetic on negative values.
  • Bitwise operators (& | ^ ~) work on the 64-bit two’s complement representation.
  • Mixed int/float arithmetic converts to f64 (the checker inserts convert).
  • round rounds half away from zero.
  • Comparisons across int widths compare mathematical values.
  • Equality of composite values. == and != on arrays, strings and bytes compare by value, element-wise; bytes may be compared with an array of integers (element-wise, as numbers). On structs they compare canonical JSON equality.
  • TS representation: values of up to 32 bits (and u40/u48 when ≤ 2^53) are number; 64-bit fields are bigint. Generated code may compute in number when it can prove the range stays below 2^53, and must use bigint otherwise.

Built-ins beyond the obvious:

  • written(obj.field) (write side only) is the value the writer wrote for a field of another struct’s value that a from stream rebuilds (§3.2); the value’s own field when it wasn’t written, else a DERIVE error.
  • encodedLength(s, unit, encoding) returns bytes, so char16 t[n] derives n = encodedLength(t, 2, "utf16") / 2.
  • this is only the argument of sizeof (write context only; for a @base struct its whole region including targets and @alignEnd), offsetof (the struct’s start from the base), bytesof and encode. Its type is the current struct.
  • sum(arr) is the sum of an array of numbers (0 when empty), of type bigint (f64 for floats). min/max with one array argument give its smallest/largest element (the element type); an empty array is a RANGE error.
  • lengths(arr) is the element count of each element of an array of arrays (pointer targets are transparent), as an array: the derivation of u16[lens[$index]] *lists[9] : u64, where $index inside the element type is the index in lists.
  • elementSizes(arr), inside the element type of array field arr (where arr is the elements read or written so far), is the number of bytes each of those elements occupies where it was read (its span) or written (its written size), as an array of integers: no re-encoding. The frontend lowers sizeof of such an element to it (sizeof(cs[$index - 1]) becomes elementSizes(cs)[$index - 1], map(cs[0..$index], c => sizeof(c)) becomes elementSizes(cs)[0..$index]); backends record each element’s size as they read or write the array. Inline elements only (no elementPlacement).
  • sizeof(expr) / bytesof(expr) / encode(expr) generalize beyond field and this references: when argType is set on the call node, the expression is serialized directly under argType (returning encoded bytes for encode/bytesof, or byte length for sizeof).
  • slice (expr[start..end]): slices a bytes or array expression; omitted start defaults to 0, omitted end defaults to the length; out-of-range bounds are RANGE.
  • peek<T>(delta): reads targetType at pos + delta without advancing pos (EOF if out of window bounds). Used in while array conditions.
  • expr is Variant (isVariant): true iff union value value holds variant variant.
  • offsets(arr[, origin[, nullValue]]) (write side only, after layout) returns the offsets (minus optional origin, or nullValue when null/empty) of each element of an element-wise placed array.
  • isNull(x) takes one argument of a nullable type. len(x) of a null value is 0 (a null pointer’s array counts as empty, as in lengths).
  • Collections and derived arrays. map, filter, indicesWhere, isSorted, and findIndex take an array and a { kind: "lambda" } (except isSorted, which may take 1 argument for scalar arrays). contains(arr | bytes, value) checks element membership; flatten(arr) flattens array<array<T>> -> array<T> or array<bytes> -> bytes; concat joins arrays/bytes. isSorted keys compare as numbers, strings by code points, or bytes lexicographically; findIndex returns the first matching index or -1. A derive or check operand of array type assigned to (or compared with) a bytes field converts element-wise, range-checked (RANGE).

7. Generated API (every backend)

For each root: parse, parseAsync (if async or for async sources), serialize, serializeAsync, safeParse, view (tier 2), toJson, fromJson. Names are adapted to each language’s conventions (Rust: parse, serialize, to_json, …). Canonical JSON is defined in CONFORMANCE.md. Root parameters (explicit + bound + endian) become parse/serialize options.

Output and input types

  • Output type: every field with output: true.
    • Fields of conditional blocks without else are optional.
    • if/else blocks and switches become discriminated unions where a discriminant field exists (TS: a union of object types). Otherwise the fields from both branches are optional.
    • Pointers have the target’s type, plus null if nullable.
    • Unions are { type: "<Variant>", value }.
  • Input type: the same, minus absent fields, with optional fields optional.

8. Worked examples

yaffle ir file.yfl prints the IR for real sources. These sketches show the shapes.

8.1 Derived count

struct Table { u32 count  Entry entries[count] }
{ "kind": "field", "name": "count", "type": { "kind": "prim", "prim": "u32", "endian": "inherit" },
  "derive": { "kind": "call", "callee": { "kind": "builtin", "name": "len" },
              "args": [{ "kind": "field", "name": "entries", "type": { "kind": "array", "element": { "kind": "struct", "struct": "Entry" } } }],
              "type": { "kind": "bigint" } },
  "deriveKind": "auto", "checks": [], "hidden": false, "output": true, "input": "absent" }
{ "kind": "field", "name": "entries",
  "type": { "kind": "array", "element": { "kind": "struct", "struct": "Entry", "args": [{ "kind": "param", "name": "endian", "type": { "kind": "endian" } }] },
            "length": { "kind": "count", "expr": { "kind": "field", "name": "count", "type": { "kind": "int", "bits": 32, "signed": false } } } },
  "checks": [], "hidden": false, "output": true, "input": "required" }

8.2 Endianness block

struct TiffHeader { char order[2] in ("II", "MM")  @endian(order == "MM" ? be : le) { u16 magic = 42  u32 firstIfd } }

This gives a block with layers [{ kind: "endian", value: cond(order == "MM", be, le) }]. magic has derive: 42, deriveKind: "constant", a check it == 42, and input: "absent". order has literals: ["II", "MM"], an in check, and input: "required".

8.3 Layered sizes

struct Packed { u32 expSize  u32 compSize  Asset body @size(expSize) @via(oodle) @size(compSize) }
  • body.type is layered(struct Asset, [size(field expSize), via(oodle), size(field compSize)]).
  • expSize.derive is encodedSize(body, 0) and compSize.derive is encodedSize(body, 2).
  • program.structs has Packed.async = true because oodle is async.

8.4 Bound value lowering

struct Asset { u32 $version  Record r }
struct Record { Motion m }
struct Motion { if ($version >= 144) { u32 extra } }
  • Motion.params gets { name: "version", origin: "bound", boundName: "version", type: u32 }, and Record.params gets the same, because Record passes it through.
  • In Asset, the field r has type { kind: "struct", struct: "Record", args: [endian, field version] }.
  • In Record, m passes param version.

8.5 at with a derived linear offset

u32 sector  u8 data[size] at sector * 0x800
  • sector.derive is offsetof(data) / 0x800.
  • data.placement is { offset: sector * 0x800, constraint: { modulus: "2048", remainder: "0" }, fixed: false }.