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

The yaffle language

yaffle describes binary file formats in .yfl files. A description is read in both directions: it parses bytes into values and serializes values back into bytes, byte-exact when the description says enough. docs/IR.md is normative for the precise semantics, and docs/CONFORMANCE.md defines the canonical JSON form and the error codes.

1. Principles

  1. Read-side expressions see only earlier fields. Lengths, at, conditions and attribute arguments may refer to fields declared before them, parameters and bound $values. This one rule also explains endianness switches and every other scoping question.
  2. Computed fields (= expr) see every field, because the whole value is known at write time.
  3. Bytes that would read back differently are never written. A contradiction between a formula and a read-side expression is a compile error when provable, otherwise a write error.
  4. Fields fill themselves in where they can. A length, count, offset or size that can be recovered from what it describes is derived on write and drops out of the input.
  5. Byte-exact rebuilds are supported, not required. The defaults produce valid files. layout, @ref, split points and codec reuse exist to reproduce originals exactly.

Every struct therefore has two value shapes. The output is everything a parse produces. The input is what a serialize needs. Each field is one of:

FieldExampleOn writeIn the input?
inputu32 versionwritten as givenyes
derivedu32 count + T entries[count]recovered from what it describesno
computedu32 crc = crc32(body)its formulano
constantu16 magic = 42the constantno
optionalu32 align ?= 0x100as given, else the default / derivedoptional

Padding and @hidden fields are not in the input either. Within one parse, every struct read at a given address with a given type is one object, so shared pointer targets are shared values and cycles are allowed. Trailing bytes after the root are ignored.

2. Basics

2.1 Structs, primitives and blocks

struct Entry {
  u16   handler
  u16   kind
  u32   align
  u64   offset
  u64   size
  u32be crc                 // fixed endianness
}
  • C style: type before name, array size after the name. Semicolons are optional, so a struct pasted from Ghidra mostly parses as is. Comments are // and /* */.
  • u8, u16, u24, u32, u40, u48, u56, u64 (and i…), f16/f32/f64, bool, with le/be suffixes for fixed endianness, plus dynamic-width uint(n) / int(n) (0..8 bytes). bool is one byte: nonzero reads as true (strict: only 0 or 1), and writes 0/1.
  • Blocks { … } group fields under attributes or conditions. Their fields flatten into the parent.

2.2 Arrays

struct Table {
  u32   count                           // derived: entries.length
  u32   pairs                           // derived: ids.length / 2
  Entry entries[count]
  u16   ids[pairs * 2]
  u8    hash[0x20]                      // a byte string
  u8    rest[]                          // to $end (or $end - fixed trailing fields)
  u16   list[until 0xffff]              // terminator: consumed, not in the value, written back
  Bank  banks[until it.next == 0]       // inclusive: the element that satisfies it is part of the array
  Row   rows[while peek<u8>() != 0]     // pre-element guard with non-consuming lookahead
  u8    chunk[until it < 0x80]          // terminator predicate on bytes
}
  • Derived lengths: a field used as a length, directly or through + − × << with constants, is derived from the array on write and left out of the input. Divisibility is checked.
  • Not derivable ((n + 7) / 8, rows * cols): the field stays an input and is checked against the array. A computed field (§4.1) can supply the formula instead.
  • Shared counts: several arrays using the same count must agree on write.
  • T x[] with struct or byte elements repeats until the end of the enclosing region minus any fixed-size trailing fields (u8 body[] u32 trailer). With an at over $index, each element goes at its own offset (§6.1). A byte string (u8 x[n]) or a string is one value, so an at over $index on it is an error.
  • until takes a terminator value, or a boolean expression: a stop predicate, checked after each element (it is the element just read; $offset the position after it), so Bank banks[until $offset >= end] needs no it. Only an array of bool elements reads a bool expression as its terminator value.
  • while checks a boolean condition before reading each element. Combined with peek<T>(byteOffset?), it performs non-consuming lookahead without advancing past a sentinel. peek is only allowed in a while condition, which only the reader evaluates (the writer writes the elements it is given). Every other expression (an if or switch condition, a length, an offset, an argument, a check, a formula) is evaluated on write too, where there is nothing to peek at, so peek there is a compile error (peek-on-write).
  • Array self-prefix & $count: inside an array element’s type arguments, $count is the array’s element count and arr[0..$index] slices the elements already decoded. There, sizeof of one of those elements is the bytes it occupies where it was read or written, not a re-encoding of its value: sizeof(arr[$index - 1]), or sizeof(e) as the whole lambda of map(arr[0..$index], e => sizeof(e)). So each element can hold the offset of the one before it (C(1 + sum(map(cs[0..$index - 1], c => sizeof(c)))) cs[n]). Inline elements only.

2.3 Strings

char   name[0x20]         // fixed: text up to the first \0, padded with \0 on write
str    path               // char[until 0]
char   line[until 0x0a]   // arbitrary code-unit delimiter (written back on write)
str16  wide               // char16[until 0], UTF-16, follows $endian
str32  wider              // char32[until 0], UTF-32, follows $endian
u8     len
char   title[len]         // lengths count code units, never characters

A string takes a count ([n]), a delimiter code unit ([until x]) or the rest of its region ([]); [while …] is a compile error (invalid-length): read the code units as a byte array. char is UTF-8 by default; @encoding("latin1" | "ascii") changes it. Other encodings go through extern. Data after the \0 in a fixed char[n] is dropped by a parse (views keep it); use u8[n] if it matters. A string whose length field is derived from it (title above) is counted: it keeps every unit, NULs included, so it is rebuilt byte-exact. So are the strings of the branches a length is derived from (switch (t) { case 1: char a[n] default: char b[n] }), a string whose length is a parameter derived from it (struct T(u8 n) { char s[n] } used as u8 n T(n) t, when every use of T derives its argument that way: a root’s parameters are given), a string whose length is computed from its own length or size (u16 n = c ? name.length : name.length * 2), and a char x[] that ends a @size window whose size is derived from it (u8 n Text t @size(n), also as the last field of a union variant there, when every use of the structs around it is such a window).

A length computed from the string’s own size (u16 n = sizeof(name) char name[n]) is known only once the string is written: the writer writes the string as it is (no NUL padding) and checks after layout that the length gives its code units (DERIVE otherwise, as for char16 name[n], whose size is twice its units).

2.4 Constants and checks

u16  magic = 42                   // constant: written automatically, checked on read
char tag[4] = "ARCV"
char order[2] in ("II", "MM")     // input type "II" | "MM"
u32  version in (1, 2, 5..9)
str  ver in /v\d\.\d{1,2}/        // portable regex subset (RE2-style: no backrefs or lookaround)
u32  size where it % 4 == 0       // any condition; `it` = this field's value

Checks apply in both directions: a violation is a CHECK error on parse and on serialize. They check the field’s value, after any as transform (u8 level as it - 0x30 in (1..9)).

2.5 Literals

  • numbers: 0x4c43_4150, 0b1010, 1_000;
  • hex bytes x"5f2a 91c3";
  • strings "…".

3. Attributes

3.1 How attributes work

An attribute is @name or @name(args). Where it goes depends on what it applies to:

struct Header @size(0x80) {       // a struct: between the name and `{`
  u32 a @align(4)                 // a field: after the declaration
  @endian(be) {                   // a block: before the `{`
    u32 b
  }
  u64 c @align(8)
        @padAfter(8)              // a line starting with @ continues the previous field
}

When several apply, the one closest to the thing applies first, and each wraps the result so far: on a field that’s the leftmost, on a block the one just before {. So T x @size(exp) @via(zstd) @size(comp) is the decoded size, then the codec, then the size on disk. Arguments are read-side expressions (principle 1), and named arguments may also name positional ones (@align(to: 8)).

3.2 Endianness

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

There’s no file-wide setting. A struct inherits endianness from where it’s used, and the root defaults to le. @endian(x) sets the built-in bound value $endian (§5.2) for a struct, field or block; a le/be suffix on a type fixes it for one field.

3.3 Padding and alignment

struct Entry {
  u32 a        @padBefore(4)
  u32 b        @padAfter(4, 0xcc)        // fill byte
  u8  data[16] @align(0x100)             // pad before, from the nearest @base
  u8  tail[]   @align(0x10, i => i & 0xff) @strict
  str name     @size(0x20, 0xff)         // "hello\0" then 0xff up to 0x20 bytes
  u8  blk[64]  @align(0x100, from: file) // from the file start, not the nearest @base
}
  • @align(n, fill?, strict?, from: file | base).
  • @size(n, fill?, strict?) bounds the inner content to exactly n bytes: short content is padded with fill (default 0), and overflow on write is a DERIVE error. Passing strict checks the padding fill on read even outside strict mode. Variable-width derived size fields (uleb128 len u8 data[] @size(len)) pre-encode the wrapped content on write.
  • @alignEnd(n, fill?, strict?, from: file | base) pads the end of a struct; on a @base struct (and the root), after all its targets, with the fill too.
  • Reading skips padding without checking it; @strict makes a fill mismatch a parse error.

3.4 Sizes and codecs

extern codec zstd
extern codec inflate @streaming                       // finds its own end
extern async codec oodle                              // the host's implementation is async
extern codec chacha20(u8 key[32], u64 nonce) @ranged  // can decode any slice, given its position

struct Packed {
  u32  expSize
  u32  compSize
  Asset body @size(expSize) @via(oodle) @size(compSize)    // decoded size · codec · size on disk
}

struct Node {
  u64     nonce
  u32     size
  Archive file @via(zstd) @via(chacha20(KEY_A, nonce)) @size(size)
}
  • @size measures whatever it wraps, so the inner and outer sizes are the decoded and on-disk sizes, both derived. The inner size is handed to the codec (Oodle and LZ4 need it). An @size on the wrong side of a non-streaming codec is a compile error. Variable-width length fields (uleb128 len u8 data[] @size(len)) pre-encode the wrapped field or block on write.
  • Content shorter than its @size is padded with fill (default 0), unless it reads to the end of the window (u8 data[], or a struct ending in such a field): the padding would read back as content, so a size that isn’t derived (a struct argument, say) must then match it exactly. Overflows on write are DERIVE errors, and overrun/underrun on read is EOF.
  • A computed or derived value behind a codec can’t measure data written after it (u8 cs = sizeof(data) @via(vli) u8 data[2]): its encoded size depends on its value. That is a compile error (layout-cycle); use the data’s .length, or earlier fields.
  • async codec makes every schema containing it async.
  • @ranged: lazy views decode only what they read. Other codecs decode the whole region once.
  • Stable re-encoding: a codec is re-run only if its decoded content changed.
  • Partial codecs (e.g. one that unmasks only [0, 0x800)) take the range as parameters of a struct-level @via.

3.5 Other attributes

AttributeOnMeaningSee
@strictfield, block, struct, bitsfills, reserved bits and bool are checked on read3.3
@hiddenfieldnot in the input or output; derived or computed6.4
@verifycomputed fieldthe stored value is checked against the formula4.1
@encoding("latin1" | "ascii")char fields, aliasestext encoding2.3
@openenumunknown values pass through as numbers4.2
@bitorder(msb)bits, structbit order within the storage unit5.3
@basestructoffsets inside it count from its start6.1
@fixedfieldkeeps an offset/length an input, or fixes at placement6.1
@nullable, @nullable(empty)pointer, at field/arraya null value; an empty array as null6.1
@refpointer, at field/arraypoints at an equal value placed elsewhere6.3
@origin(expr)pointer, at field/arraythe offset counts from base + origin6.1
@split(fit | sizes | every)from fieldhow a stream is cut into pieces on write6.4

4. Values

4.1 Computed fields, local bindings, functions and externs

extern fn pathHash(char path[]) -> u32
fn addScaled(u32 a, u32 b) -> u32 = a * 2 + b    // pure helper function

struct Node {
  u32  a
  let  doubleA = addScaled(a, 0)                  // local immutable binding (no bytes emitted)
  u32  n       = flags.length * 8                 // formula where n isn't derivable
  u8   flags[(n + 7) / 8]
  u32  size    = sizeof(body)
  u32  crc     = crc32(bytesof(this)) @verify     // self-zeroing checksum over the struct
  u32  hash    = pathHash(path)
  u32  align   ?= 0x100                           // optional input: default/derived when absent
  char path[0x40]
  Body body
}
  • Pure top-level fn declarations (fn name(T arg, ...) -> R = expr) and struct-local let bindings (let name = expr) factor repeated arithmetic and expressions with no wire representation.
  • = gives the raw value written, always computed. Without it the field leaves the input; with it it normalizes the input on write, and the field stays an input (§4.2). Formulas are not checked on read, except constants and fields marked @verify (u32 crc = crc32(bytesof(this)) @verify): once the struct is read, a stored value that differs from the formula is a CHECK error, which also rejects a union variant (a checksum selects the variant). Calling bytesof(this) or encode(this) inside a field’s formula or @verify check zeros that field’s own inline bytes (and any later self-zeroing fields in rank order) before computing the bytes.
  • A formula that measures sizes, positions or content is computed after layout, also for a field placed with at (u32 size at pos = sizeof(b)). Formulas over encoded bytes (checksums, bytesof, encode) are computed innermost struct first and, within a struct, after every computed field whose bytes they cover or whose value they read: u32 a = crc32(bytesof(b)) before u32 b = crc32(h) computes b first, and bytesof(this) covers every other field but later self-zeroing ones. Two formulas that each cover the other are an error. sizeof(expr), bytesof(expr) and encode(expr) work on arbitrary expressions as well as fields and this (sizeof(raw[1..3]), crc32(encode(raw[1..3]))).
  • A formula that never agrees with the read side is an error, and one that agrees only for some values is a warning. A formula equal to what the field would be derived as is redundant. A consistent formula can still be lossy: a file with n = 5 above has one byte of flags and is rebuilt with n = 8, so it doesn’t rebuild byte-exact (§8).
  • Externs are declared in yaffle and implemented once per target language. Their failures are CODEC errors.

4.2 Transforms and enums

enum MemKind : u16 { Sys = 0, Vram = 1 }    // @open: unknown values pass through as numbers

struct Entry {
  MemKind kind
  u16     angle as it * 360.0 / 65536              // the inverse is worked out
  u8      name  as names[it]                       // inverse: names.indexOf(it)
  u32     tag   as decodeTag(it) = encodeTag(it)   // explicit inverse
  u32     hash  as hex(it)                         // one-way: input stays u32, read-only in views
  u32     flags = it | 0x80                        // normalize on write
}

as reads (raw → value, it = raw). = writes (value → raw).

4.3 Virtual fields

struct Node {
  u8  sizeHigh
  u32 sizeLow
  virtual u40 size = (sizeHigh << 32) | sizeLow    // no bytes; a write derives sizeHigh and sizeLow
}
  • A virtual field occupies no bytes. Its formula is evaluated on parse and inverted on serialize, so the parts it combines are derived and leave the input.
  • Invertible forms: bit concatenation (a << k) | b (where b fits in k bits), a * K + b (with 0 ≤ b < K), and linear forms, nested. Anything else is the error virtual-not-invertible.
  • A virtual field used as a length, size or at offset is derived from that use, like any field, and its parts from it.
  • Virtual fields take where/in checks and ?= defaults, but no attributes, at, from or as. A part may be a bit field, and an in (lo..hi) check narrows its range.

4.4 Derived arrays and collection builtins

struct Asset {
  u8   index[s] = indicesWhere(records, r => r.model != null)
  Key  keys[n] where isSorted(it, k => k.name)
  bool hasKey = contains(keys[*].id, 5)
  i32  keyAt  = findIndex(keys, k => k.id == 5)
  u8   flat[] = flatten(chunks[*].data)
  u8   head[4] = raw[0..4]
}
  • Lambdas (x => expr) appear as arguments of map, filter, indicesWhere, isSorted (2-arg form isSorted(arr, k => ...); 1-arg isSorted(arr) compares scalars directly) and findIndex (first matching index, or -1). Lambda parameters may shadow fields.
  • contains(arr | bytes, value) tests element equality, flatten flattens nested arrays or byte arrays (array<bytes> -> bytes), concat joins arrays/bytes, and expr[start..end] slices bytes or arrays (both bounds optional).

5. Structure

5.1 Conditionals and unions

if (version >= 3) { u32 extra } else { u16 legacy }

switch (tag) {
  case "ARCV": Archive body
  case "ASST": Asset   body
  default:     u8      body[size]
}

switch (code) {
  case 0:       u8  zero
  case 1..4, 7: u16 shortVal          // inclusive integer ranges and comma lists
  default:      u32 bigVal
}

union Node { Archive  Index }         // try in order; the variant's checks decide
struct Root {
  Node n
  bool isArch = n is Archive          // variant predicate
}
  • A switch field’s value is a union discriminated by the tag. A union’s value records which variant matched; variants are named after their types, and expr is Variant tests which variant matched.
  • if without else makes the block’s fields optional.

5.2 Parameters and bound values

struct Blob(u32 n) { u8 data[n] }          // explicit parameters, for reusable structs
struct Body(Header hdr) { … }              // any parameter type, structs included

struct Uses {
  Blob(16)    a                            // positional
  Blob(n: 32) b                            // named
}

struct Asset {
  u32    $version                          // bound: later fields and everything nested in them can read it
  Record records[r]
}

struct MotionTable {                       // any depth below; the structs in between stay untouched
  if ($version >= 144) { u32 extra }
}

struct Node(u8 $key[32]) { … }             // bound parameters
struct Strict(u32 $version) { … }          // optional: pins the type, so the struct is checked on its own
  • Top-level declarations only. Structs, enums and unions are declared at module top level; nested type declarations and implicit outer-field captures are not allowed (pass needed data via explicit parameters or $bound values).
  • $name is always a bound or built-in value. Plain names are only fields and parameters.
  • Nearest binding wins; inner bindings shadow outer ones (with a warning).
  • Every path is checked: a path that reaches a $version read without a binding is a compile error naming the path.
  • Built-ins: $endian, $offset (current position), $end (end of the enclosing region), $index (index in the enclosing array), $count (element count of the enclosing array). A length using $end stays an input on write, and a condition on $end takes the branch whose fields are given (checked once the end is known).
  • A root struct’s parameters, and the bound values it reads, are arguments to parse.

5.3 Types, generics and bitfields

type Fixed16 = i16 as it / 256.0
type Fixed(u8 bits) = i32 as it * 1.0 / (1 << bits)   // `* 1.0` makes it float division
type EncRec  = Record @via(xor(0x5a))        // a codec per element: `EncRec recs[n]`
type Name    = char[0x20]

struct Span<T> { u64 n  u64 ofs  T items[n] at ofs }   // generics: Span<Point>

extern type VarInt(u8 maxBytes) : u64        // a host-implemented primitive
extern type Half : f32 @size(2)              // fixed size

bits u8 {                       // explicit storage unit, LSB first; @bitorder(msb) flips it
  bool    compressed : 1
  MemKind kind       : 3
  u8                 : 4        // reserved: 0 on write, checked with @strict
}
bits u16 {
  u16 sizeHigh : 12
  u16 level    : 4
}
  • An extern type’s implementation provides size(bytes, ...args) (returning “need more bytes” when it can’t tell yet), read(bytes, ...args) and write(value, ...args). LEB128 (uleb128, sleb128) and common checksums are built in.
  • Enum values cross the host boundary (extern fn arguments and results, extern types with an enum value type such as extern type Id : ElementId) as the target’s enum values: member names in TS, the generated enum type elsewhere. A host may return the storage integer instead; it is converted. An unknown value is a CODEC error for a closed enum and passes through for an @open one.
  • A bitfield’s storage unit follows $endian.

5.4 Modules and externs

import { Span, Name, SECTOR } from "./common.yfl"
import * as textures from "./textures.yfl"

export const u32 SECTOR = 0x800
export extern codec zstd                       // externs can be shared and imported by name
export struct Archive { char tag[4] = "ARCV"  … } // a root: gets parse/serialize/view
  • export marks roots. Every top-level declaration can be imported, and exported structs of imported modules are roots too. Exported generic structs and aliases are importable but never roots. Import paths are relative, and .yfl may be omitted.
  • Cross-file cycles between types are allowed.

6. Placement

6.1 Pointers and bases

struct Asset @base {                      // offsets inside count from the start of Asset
  Model  *model : u64                     // the pointer is transparent: the value is just `model`
  Graph  *graph : i32 @origin($offset)    // target = address of pointer slot + value
  Extra  *extra : u64 @nullable           // 0 → null; @nullable(0xffffffff) for other nulls
  Record *recs[count] : u64               // an array of pointers
  CurvePoint[n] *points : u64             // a pointer to an array; n is derived from its length
  Step[k] *steps : u64 @nullable(empty)   // an empty array writes 0, and 0 reads as empty
  u16[lens[$index]] *lists[9] : u64       // element-wise: lens[i] = lists[i].length on write
  str    *name : i32 @ref @origin(offsetof(pool))   // target = base + origin + value
  u64    tableOfs                         // derived from where `table` is placed
  Record table[count] at tableOfs
  u64    relOfs
  Record rel at $offset + relOfs          // offset relative to the field itself (fixed input)
  Footer footer at $end - 4               // trailer placement relative to region end
  u8     data[size] at sector * 0x800     // linear `at` → placement constraint (0x800-aligned)
}
  • Pointers are sugar over at placement: Model *model : u64 lowers to a hidden slot _ptr_model : u64 and Model model at _ptr_model. Both pointers and at fields support @nullable, @ref, and @origin(expr).

  • Explicit inputs and trailers: @fixed opts a field out of auto-derivation (or fixes an at placement), while ?= offsetof(x) makes an at offset an optional input that is derived when omitted. at $end - K places a fixed-size trailer at the end of the enclosing region.

  • Shared targets: the same offset gives the same object on read, and it’s written once. A target’s identity is its address, its type (struct arguments and lengths included) and its own @size window: T t at ofs @size(size) read twice at one address with sizes 0 and 4 is two values; with the same size, one.

  • at offsets that aren’t derivable stay inputs: the target goes exactly there, and overlaps are OVERLAP errors. Alternatively, compute it: = offsetof(t) - base.

  • A condition can’t read a derived position: in u8 o if (o > 1) { u8 x } u8 s at o, the writer evaluates the condition where the block is, but o is known only once the layout has placed s, which depends on what the condition wrote. That is a compile error (layout-cycle); make the offset an input (u8 o @fixed).

  • An offset relative to a parameter (at base + start, base an argument or a bound value) is optional in the input: given, the target goes exactly there (existing files keep their gaps); left out, start is derived and the target is laid out, no lower than base.

  • Element-wise offsets (u32 offsets[n] Entry items[n] at offsets[$index]) are optional in the input too, when nothing else reads them: given, each element goes exactly at its offset; left out, the elements are laid out in order and offsets is derived from where they went.

  • A field measured only in some branches, or behind an as, is optional in the input: a length behind an as (u16 len as it - 0xb000 u8 d[len]), a size or length used in one branch (if (k == 1) { u8 d[] @size(length) }), an offset used only inside an if (if (k == 1) { u8 data[2] at o }), and a size that is also its block’s condition (if (n != 0) { u8 d[] @size(n) }). Given, it is used exactly (files keep their bytes; content that disagrees is a DERIVE error). Left out, it is derived from the branch that measures it; where no branch does, it is the single value that makes the guard false (0 for n != 0, or for n > 0 on an unsigned field), and otherwise an INPUT error naming the field. Content given that would make its block’s condition false (d = "" above) is an INPUT error too. Measured in every branch (switch (k) { case 1: u8 a[n] default: u8 b[n] }), it is derived. Branches may nest, and the field may itself sit in a branch, with its uses in its block.

  • A count or length stored in another struct (H h T arr[h.count], u8[entries[$index].size] files[n], B(hs[$index].len) bs[n]) is an optional input of that struct: left out, the struct using it fills it in (arr.length, each file’s length); given, it is checked as before. Where nothing fills it (H written on its own), it is required. The measure must be known before the member is written: a count, a byte array’s length, or a struct argument derived from one.

  • An empty at array is placed at the current position, whatever its offset expression.

  • $offset while writing a target: known inside a fixed placement (its offset); inside a target the layout places, a condition or length using it is a DERIVE error.

  • Targets and @size windows. A target past the @size window of the struct holding it (where the writer lays it out, after the base’s inline bytes) is read up to the end of the file; a target inside the window is bounded by it.

  • x == null / x != null test @nullable pointers.

  • Following a pointer is lazy in views, and an await point with async sources.

6.2 Layout: where pointer targets go on write

The default is depth-first declaration order: each struct comes before its targets. layout reproduces formats written in a different order:

struct Asset @base @alignEnd(0x10) {
  @size(0x80) { /* header */ }
  str     pool[until ""]
  Record  records[r]        at recordsOfs
  u8      index[s]          at indexOfs
  Record *recPtrs[r] : u64  at recPtrsOfs @ref
  layout {
    records[*].model @align(0x80)        // pulled out: all model sets together
    records[*].anims @align(0x80)
    records[*]       @align(8)           // each record's remaining targets, in Record's own order
    records          @align(8)
    recPtrs
    index
  }
}
struct Record  { …  layout { curves, motions } }
struct Curves  { …  layout { x.points, y.points, x, y, this } }
struct Entry   { u32 align  u32 n  u64 ofs  u8 data[n] at ofs  layout { data @align(align) } }
struct World   { Volume volumes[n]  layout { volumes[*].pieces[*]  volumes[*].portals[*].points } }
  • layout orders only a struct’s own targets, using local paths (and [*] wildcards). this is the struct itself. Targets go after the inline fields, and targets no item names follow the items in default order.
  • Pulling out: a container can pull shared groups out of inner structs (records[*].model, volumes[*].pieces[*]), which overrides the inner layouts.
  • Item attributes may read fields, like computed fields. An item’s alignment applies to everything it places.
  • Fixed placements (at offsets that are inputs) go exactly where their offset says, and layout continues after them.

6.3 Shared values: @ref

struct Motion { str *name : u64 @ref }   // points at an equal string that's already placed

@ref pointers don’t own their target. On write they resolve to the input object itself if it was placed, otherwise to the first placed value with an equal encoding, searching the current base, then the enclosing ones. If none exists, the write fails with REF.

6.4 Streams

struct Fragmented {
  FragHeader hdr
  Frag       frags[] at max($index * 0x10000, 0x20)   // fragment k in its 64 KiB disk block
  Archive    file from frags[*].data @split(fit)      // joined decoded pieces, parsed as one stream
}
struct Frag {
  u32 magic = 0x46524147
  u32 exp                                             // decoded size: where the split falls
  u32 comp
  u32 check
  u8  data[] @size(exp) @via(zstd) @size(comp)
}

struct RawView {
  u8     raw[0x40]
  Header hdr from raw
}
  • from <stream> takes no space where it’s declared. A stream is a bytes field (from raw) or joined element pieces (from frags[*].data). Decoded bytes the struct doesn’t read are dropped. For fixed-offset substrings or slices in computed fields, slice expressions directly (raw[0x00..0x20]).
  • A field consumed by from is derived on write and leaves the input; it stays in the output unless @hidden. @hidden fields must be derived or computed. Formulas elsewhere that read it (sum(map(parts, p => p.raw.length))) see the rebuilt bytes, also when they come first.
  • Splitting on write: the pieces’ size fields, when given in the input, win (byte-exact); otherwise the @split policy decides. sizes (the default) requires them. fit means the largest piece whose encoded form fits its block, and overlap checks enforce the fit. A block ends at the next higher element offset, so pieces at out-of-order offsets (CFB sectors) fit too; the last piece (none after it, as past the end of an offset list) and a piece with no higher offset take the rest. every: n cuts pieces of n decoded bytes (the last one shorter), for formats whose blocks hold a fixed amount of data (SquashFS metadata: @split(every: 8192)); n is a constant.

7. Built-ins

Built-inMeaning
sizeof(x), offsetof(x)size on disk, position (from the nearest base); sizeof accepts any expr
bytesof(x), encode(x)bytes on disk (after codecs), plain encoding (before codecs); any expr
crc32(x), adler32(x)checksums (of a field: its bytes on disk, like bytesof)
min, max, sumof values, or over one array (max(probes[*].total))
sizeof(this), offsetof(this)the current struct; for a @base struct, its whole region (write side)
bytesof(this), encode(this)self-zeroing struct bytes (this field + later zeroSelf fields zeroed)
x.length, x[a..b]element/code-unit count, bytes/array slicing
peek<T>(delta?)lookahead at $offset + delta (default 0), only in while (§2.2)
x is Variantunion variant predicate
map, filter, indicesWhere, isSorted, findIndex, contains, flatten, concatcollection helpers (§4.4)
$endian, $offset, $end, $index, $countsee §5.2
itthis field’s own value, in as, =, until and where
nullthe null pointer, in comparisons

sizeof, offsetof and bytesof of a pointer field measure the pointer itself (its storage bytes), not its target. A target’s size reaches its struct through derivation instead: a pointer to Blob(n) whose u8 data[n] measures it derives n from the target (T(n) *p).

sizeof of a member of another struct’s value (sizeof(b.data), with b a struct argument, field or element) encodes that member’s value again, as its declaration says (codec layers included): it is not the size of the bytes the member occupies in the file. The two differ when a codec doesn’t re-encode its decoded value byte for byte, since a field’s own write reuses the original encoded bytes (IR.md §3.6) and sizeof of the member doesn’t: with struct Blk { u8 n u8 data[] @via(strip) @size(n) } and u8 s = sizeof(b.data), n keeps the reused bytes’ size and s the re-encoding’s. The exception is an element of the array being read or written, measured where it is (§2.2). The size of the bytes another struct’s member occupies is planned for 0.0.6; until then, measure the field in its own struct (u8 n above, or a computed = sizeof(data) there) and read that.

8. Syntax details

  • Line rules. Members end at a line break, ;, or where the next member starts (u64 n u64 ofs). A line starting with @ continues the previous field unless it contains a { (then the attributes prefix a block). Lines starting with at, from, as, in, where, = or ?= also continue the previous field. Binary operators continue expressions across lines, and line breaks inside ()/[] don’t matter.
  • Operator precedence is Rust-like: * / % > + - > << >> > & > ^ > | > comparisons, is and in > && > || > ?:. So it & 0x80 == 0 means (it & 0x80) == 0. After a field’s whole expression, in (…) is a check clause (u8 b = 4 in (3)); inside an operand (a && it in /x/) or followed by an operator (k in (1) ? 2 : 3) it is the operator.
  • Contextual keywords. type, from, at, … may be field names (Ghidra structs have type fields). Declaration names can’t be keywords, and field names can’t be it, true, false, le, be or this.
  • C conveniences: struct Foo name; trailing };; Ghidra/C type names (uint32_t, dword, …) get a quick fix to the yaffle type. Multi-value cases and ranges: case 1..4, 7:. Enum members in expressions: Kind.Vram. Attributes may follow at (T x at ofs @size(n)).
  • Generic type arguments must be constants (Span<Blob(16)>, not Span<Blob(n)>), so an instance is context-free. Unions are inlined at each use.
  • Conditional fields can be read only where they’re known to exist: in the same branch, under a structurally identical guard or one implying it (version >= 3 implies version >= 2), or when every branch declares them. A name may be declared again in another branch, with its own type, formula and derivation: inside a branch it means that branch’s declaration, and after the branches (same type required) the one that was taken. A use under a structurally identical guard (if (v >= 1) { u8 n } … if (v >= 1) { u8 d[n] }) derives a length or size like a use in its own branch (an offset used there stays an input); one used in only some branches is an optional input (§4).
  • = with it (u32 flags = it | 0x80) normalizes the value on write, and the field stays an input. Without it it’s a computed field, or a constant (checked on read).
  • Integers are exact. Arithmetic has no overflow; values are range-checked where they reach a typed destination. Division truncates, and float-to-integer conversion rounds half away from zero.
  • Integer types from ranges. Integer as transforms and untyped constants get the smallest standard type holding the expression’s static range (u8 v as it + 100 → u16).
  • Formula analysis is by sampling the formula against the read side over the values the field can hold (its type, width and checks). Never agreeing is contradictory-formula, agreeing only sometimes is formula-mismatch, lossy is lossy-formula, and equal to the derived value is redundant-formula.
  • What makes a field derived: the first read-side use that is linear in the field (a length, an @size layer (also on a block of plain fields: the sum of their sizes), an at offset, with placement constraints, or a struct argument: Blob(len) c derives len from Blob’s own derivation, also through a pointer that can’t be null and element-wise (Blob(lens[$index]) bs[n] derives lens)). Later uses are consistency checks.

9. Extensibility

LayeryaffleImplemented by
1. Transformsas expr, = expr, enums, type X = T as …yaffle expressions, extern fn
2. Codecs@via(codec), extern codec, async, @ranged, @streaminghost
3. Custom primitivesextern type X(args) : T with size/read/writehost