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
fndeclarations andletbindings are inlined, constants are folded, andimports are resolved. Every struct referenced anywhere is inprogram.structs. - Lowered scoping. Bound values (
$version) become implicit parameters (origin: "bound"). Each use site passes them explicitly inIrStructType.args.$endianis the implicitendianparameter (origin: "endian", value type{ kind: "endian" }). A struct withusesEndian: falsemay ignore it.- Parameter order.
IrStruct.paramsis always:endian(defaultle) first, then the declared parameters in declaration order (explicit, and declared$parameters with originbound), then implicitboundparameters sorted by name. Every struct has theendianparameter, even withusesEndian: false. - Implicit names. A lowered
$versionis the parameterversion(boundName: "version"), suffixed with_boundif 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.
- Parameter order.
- Resolved derivation. Every value the writer computes (derived, computed and constant
fields) has a
deriveexpression, except the bytes offromstream sources (§3.7). Pointer fields (T *p : S) lower uniformly to a hidden slot_ptr_<name>(typeS, derived as the target offset) plus the target field<name>carryingplacement. - 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 typebigintorfloat(f64), and both operands have exactly the result type: the frontend insertsconverton 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 >= 3compares twou32). - String lengths are never
len(<string>). Derived string lengths ands.lengthuseencodedLength(s, unit, encoding), divided byunitfor 2- and 4-byte units.lenis used for arrays and bytes. x == nullisisNull(x)andx != nullis!isNull(x). There is no null literal.
- Constants are folded where the operands are literals, including enum and const references and
- Inferred value types. The value type of an integer
transformis 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 givesi64(u64if non-negative). The read expression’s owntypestaysbigint. Untyped constants (const N = 4) get a type the same way. - Complete bit units. Every
IrBitsunit’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 / source | the bytes (sync or async, random access) |
pos | absolute position of the next inline byte |
base | absolute position of the current base. The file start (0) at the root, changed by @base structs |
end | absolute 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 |
index | the index of the element being read, inside arrays |
strict | whether strict checks are on (root option, struct strict, or a strict layer) |
| params | the 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
posand advanceposby the bytes consumed. placement: evaluatenullWhen(if present): when true, yieldnull(or[]withemptyIsNull) without reading or movingpos. Otherwise evaluateoffsetand read the type atbase + offsetwithout movingpos(after inline members finish whendeferred: true, e.g.@origin(offsetof(laterField))). The region’sendstays the same, except for a target at or past the end of the@sizewindows 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 ownsizewindow sizes are part of the type). Reading a@ref(ownership: "ref") target must not expand the referring@basestruct’smaxEnd.from: build the stream (§2.8) and read the type from it as a fresh region (base = 0, end = stream length).posdoesn’t move.virtual: the field occupies no bytes. Evaluatevirtual.read(typebigint, 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 aCHECKerror (CONFORMANCE.md §Errors). Strict-only checks run only in strict mode. Adeferredcheck (@verifyon a computed field:it == formula) is evaluated once the struct’s members are read, so the formula may read later fields; withzeroSelf,bytesof(this)/encode(this)inside it zeros this field’s own bytes and any laterzeroSelffields in dependency order. Its error has the field’s path, and inside a union variant it rejects the variant. Writers skip checks markeddeferredand store the formula.
2.3 Types
| Type | Read |
|---|---|
prim | little/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. |
dynInt | dynamic-width integer (width 0..8 bytes, signed, endian). width == 0 reads 0; out-of-range widths are RANGE. |
bool | one byte; nonzero → true (strict: anything other than 0 or 1 is a CHECK error). |
string | see 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. |
bytes | count, until (terminator byte or untilPredicate), while, or rest up to end - (reserveEnd ?? 0). |
array | elements 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. |
struct | evaluate 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). |
enum | read the storage prim. An unknown value is a CHECK error unless open; open unknowns are returned as plain integers. |
extern | call 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(). |
union | try 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. |
transform | read inner, then evaluate read with it = the inner value. |
layered | apply the layers from outermost (last) to innermost (first) around reading inner (§2.4). |
2.4 Layers on read
Processed from the outermost layer inwards:
| Layer | Read 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. |
strict | turn on strict mode inside. |
- Alignment origin.
alignandalignEndmeasure from the current base by default. Withfrom: "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$offsetwould count from if there were no@basein between. The frontend emitsfromonly as"file". - Strict padding. A padding layer (
align,alignEnd,padBefore,padAfter,size) withstrict: truechecks its own fill on read even outside strict mode. It may appear on field, block and struct layers. - Endian layers rebind
$endian: inside one, bothendian: "inherit"and every{ kind: "param", name: "endian" }expression, including theendianargument 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, readmembers, otherwiseelse(if any). Applylayersaround 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 }), elsedefault. If nothing matches and there is no default, that’s aCHECKerror.
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.splitis present only foreachstreams.
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
derivethat usesitnormalizes the input (u32 flags = it | 0x80):itis the field’s input value, the field staysinput: "required", and the writer stores the value ofderive. Aderivewithoutitcomes withinput: "absent"or"optional". - A default (
u32 align ?= 0x100) isinput: "optional"with the default asderive,deriveKind: "formula"and no check. - A virtual field’s value comes from the input (
required, oroptionalwith its default asderive), or, used as a length, size or offset, is derived (absentwith aderive). It is inverted on write, so its parts are derived from it: theirderiveexpressions use>>,&,/,%,+and-on the virtual field’s value, withderiveKind: "auto"andinput: "absent"(parts may be bit fields). A virtual field is never a part of another one. After writing,virtual.readmust give back the input value, otherwise it’s aDERIVEerror.
3.2 The write context and derive
derive expressions are evaluated in the write context:
fieldreferences read the input value, or the value ofderivefor fields that have one. Such fields may reference each other as long as there is no cycle (the frontend checks this).sizeof/encodedSize/bytesof/encodetake the field’s final encoding.offsetoftakes the field’s final position (from the base).$indexis the element index, and params are as on read.- A
derivenever reads another struct’s derived or computed field throughmemberwhen that field’s ownderiveis a plain value formula: the frontend substitutes it (recs[n - 1].sizebecomesrecs[n - 1].data.length; the plain size of a byte array,encodedSize(d, 0)orsizeof(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,itbeing the member (c.nbecomesc.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], orE es[n]) and the@sizeof 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)becomesT(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). sizeofof 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
fromstream of its struct (u8 d[n] @hidden In x from d) is read from another struct’s value aswritten(p.d): the bytes the writer wrote for it. The frontend wraps such member accesses; aderiveusingwrittenis computed once everything is written (like one usingbytesof), and a backend records each carrier it writes by the value’s identity. $offsetin 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 afixedplacement (whose start is its offset, known before layout); inside a target the layout places it is aDERIVEerror (“$offset depends on the layout”). Aderiveusing it is computed after layout.$endis the end of the enclosing@sizewindow or region once it is written, so expressions using it are evaluated after layout. A block condition using$endtakes the branch whose input fields are given (the then-branch when any of its input fields is present), and must agree once$endis known (DERIVEotherwise).
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):
- 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.
- Run layout (§4) to assign every target a position.
- Evaluate and patch the fixups: offsets, then
@refpointers, then formulas over final bytes, innermost struct first and, within a struct, in ascendingcontentRank(a formula after the ones whose bytes it covers). - 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 (
ownershipomitted or"owned"): the target is a placeable in the current base (the nearest enclosing@basestruct, or the root). IfnullWhenholds, no target is placed and the writer verifiesnullWhenagrees with whether the input is null / empty (emptyIsNull), throwingDERIVEon mismatch. - Identity: two placements with the same object (reference identity in the input) and the
same type share one target, unless they are
fixedat 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 forrefplacements. - 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 aREFwrite error. When several match, the first placed wins. Note that escalated@refoffsets targeting an earlier position in an enclosing base may be negative; fixup resolution tracks a booleanresolvedflag rather thanpos >= 0.
3.5 Layers on write
These mirror reading:
- size: padded with
fill(default 0) up tosize. Content larger thansizeis aDERIVEerror, and afillswindow (content that reads to its end) is never padded (shorter content is aDERIVEerror too, as it would read back longer). - via: encode the inner bytes with the codec. With an inner
sizelayer, passoutputSize. - 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 isinput: "absent"and derived from the field read from it. It stays an output field unlesshidden. Afromfield 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 isinput: "optional"without aderive: the input’s value where none is taken.from arr[*].piece: in the element struct ofarr,pieceisinput: "absent"(its content comes from the stream), and fields whosederivemeasures it (encodedSize(piece, i)) areinput: "optional": split points, used when given for byte-exact rebuilds, otherwisefrom.splitdecides. Withfit, piece k’s block ends at the next higher offset among the elements’ offsets (probed in order until one is aRANGEerror, 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.
- 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). - 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 therecordstarget) places the remaining units of all placeables reachable from those elements, in their own layout order. thisplaces the struct’s own inline bytes.
- A path naming a placeable field (
thiscomes first in a unit unless an item names it.- Leftovers (placeables no item placed) follow the items in default order.
- 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).
- 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
RANGEerror. - Division truncates toward zero.
%takes the sign of the dividend. Division by zero is aRANGEerror. - 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). roundrounds 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 arebigint. Generated code may compute innumberwhen it can prove the range stays below 2^53, and must usebigintotherwise.
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 afromstream rebuilds (§3.2); the value’s own field when it wasn’t written, else aDERIVEerror.encodedLength(s, unit, encoding)returns bytes, sochar16 t[n]derivesn = encodedLength(t, 2, "utf16") / 2.thisis only the argument ofsizeof(write context only; for a@basestruct its whole region including targets and@alignEnd),offsetof(the struct’s start from the base),bytesofandencode. Its type is the current struct.sum(arr)is the sum of an array of numbers (0 when empty), of typebigint(f64 for floats).min/maxwith one array argument give its smallest/largest element (the element type); an empty array is aRANGEerror.lengths(arr)is the element count of each element of an array of arrays (pointer targets are transparent), as an array: the derivation ofu16[lens[$index]] *lists[9] : u64, where$indexinside the element type is the index inlists.elementSizes(arr), inside the element type of array fieldarr(wherearris 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 lowerssizeofof such an element to it (sizeof(cs[$index - 1])becomeselementSizes(cs)[$index - 1],map(cs[0..$index], c => sizeof(c))becomeselementSizes(cs)[0..$index]); backends record each element’s size as they read or write the array. Inline elements only (noelementPlacement).sizeof(expr)/bytesof(expr)/encode(expr)generalize beyond field andthisreferences: whenargTypeis set on thecallnode, the expression is serialized directly underargType(returning encoded bytes forencode/bytesof, or byte length forsizeof).slice(expr[start..end]): slices abytesorarrayexpression; omittedstartdefaults to0, omittedenddefaults to the length; out-of-range bounds areRANGE.peek<T>(delta): readstargetTypeatpos + deltawithout advancingpos(EOFif out of window bounds). Used inwhilearray conditions.expr is Variant(isVariant): true iff union valuevalueholds variantvariant.offsets(arr[, origin[, nullValue]])(write side only, after layout) returns the offsets (minus optional origin, ornullValuewhen null/empty) of each element of an element-wise placed array.isNull(x)takes one argument of anullabletype.len(x)of a null value is 0 (a null pointer’s array counts as empty, as inlengths).- Collections and derived arrays.
map,filter,indicesWhere,isSorted, andfindIndextake an array and a{ kind: "lambda" }(exceptisSorted, which may take 1 argument for scalar arrays).contains(arr | bytes, value)checks element membership;flatten(arr)flattensarray<array<T>> -> array<T>orarray<bytes> -> bytes;concatjoins arrays/bytes.isSortedkeys compare as numbers, strings by code points, or bytes lexicographically;findIndexreturns 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
absentfields, withoptionalfields 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.typeislayered(struct Asset, [size(field expSize), via(oodle), size(field compSize)]).expSize.deriveisencodedSize(body, 0)andcompSize.deriveisencodedSize(body, 2).program.structshasPacked.async = truebecauseoodleis async.
8.4 Bound value lowering
struct Asset { u32 $version Record r }
struct Record { Motion m }
struct Motion { if ($version >= 144) { u32 extra } }
Motion.paramsgets{ name: "version", origin: "bound", boundName: "version", type: u32 }, andRecord.paramsgets the same, becauseRecordpasses it through.- In
Asset, the fieldrhas type{ kind: "struct", struct: "Record", args: [endian, field version] }. - In
Record,mpassesparam version.
8.5 at with a derived linear offset
u32 sector u8 data[size] at sector * 0x800
sector.deriveisoffsetof(data) / 0x800.data.placementis{ offset: sector * 0x800, constraint: { modulus: "2048", remainder: "0" }, fixed: false }.