1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! Binary (.inkb) writer and reader for [`StoryData`].
//!
//! The `.inkb` format is a compact, little-endian binary encoding designed for
//! fast loading by the runtime.
//!
//! ## Header layout
//!
//! ```text
//! Offset Size Field
//! ------ ----- ------
//! 0 4 Magic: b"INKB"
//! 4 2 Version: u16 LE (= 1)
//! 6 1 Section count: u8 (N entries in offset table)
//! 7 1 Reserved: 0x00
//! 8 4 File size: u32 LE (total bytes)
//! 12 4 Content checksum: u32 LE (CRC-32 of all bytes after header)
//! 16 N*8 Offset table entries
//! ```
//!
//! Each offset table entry (8 bytes):
//! ```text
//! 0 1 SectionKind: u8 tag
//! 1 3 Reserved: 3 bytes of 0x00
//! 4 4 Offset: u32 LE (byte offset from start of file)
//! ```
pub
pub
pub use ;
pub use ;
use Range;
use Vec;
use crateDecodeError;
// ── Constants ───────────────────────────────────────────────────────────────
pub const MAGIC: & = b"INKB";
/// On-the-wire format version. Bumped on any byte-layout change; the reader
/// hard-rejects an unrecognized version (see `docs/format-spec.md` § Versioning).
/// v2 added `ContainerDef::param_count` to the Containers section.
/// v3 added the `local` scope bit to `GlobalVarDef` (Variables section) and
/// `ContainerDef` (Containers section) — see `docs/directive-annotations-spec.md`.
/// v4 added the collection value tags `VAL_ARRAY`/`VAL_MAP` (tree encoding) and
/// froze the reserved Tier-1 value-tag/section/opcode surface (the §9 one-bump
/// rule of `docs/value-model-spec.md`) — see `docs/format-v4-rfc.md`.
/// (Also on the v4 line: the optional `Visibility` section, M-2b,
/// `docs/modules-spec.md` §4, tag `0x0E` — omitted when empty, so it didn't
/// need a bump of its own.)
/// v5 added the `AliasTable` section (`docs/modules-spec.md` §5, M-3): this
/// section was not part of the v4 RFC's frozen inventory (unlike
/// `StructShapes`/`EffectRows`, which were pre-reserved and only needed
/// their *encoding* materialized without a bump), so a brand-new *mandatory*
/// section is its own one-bump event. The section itself carries a
/// one-byte section-local version so its *row encoding* can still evolve
/// without a further format bump, matching the `EffectRows` precedent.
/// `AliasTable` takes tag `0x0F` (the next free tag after `Visibility`).
/// v6 added the `PART_SPAN` `LinePart` tag (#1716, `docs/prose-dialect-spec.md`
/// §4.4/§4.5): like `AliasTable`, `PART_SPAN` was not part of the v4 RFC's
/// pre-reserved inventory (that inventory covers `VAL_ARRAY`/`VAL_MAP`-style
/// *value* tags and the `StructShapes`/`EffectRows` sections — it never
/// reserved a `LinePart` tag), so introducing it is its own one-bump event,
/// not a free ride on the `VAL_VEC2`/`VAL_WEIGHTED` no-bump precedent (see
/// `PART_SPAN`'s doc comment below). Ruled directly by issue #1716's own
/// ⚠ ("`LinePart::Span` is a v6 payload") and coordinated with #1683 (the
/// v6 bump manifest); this PR lands only the `Span` payload of that
/// manifest, so `VERSION` 6 stays open to absorb #1683's remaining payloads
/// (element kind/data, universal block id, choice captured environment)
/// without a further bump, the same way v4 absorbed its later Tier-1
/// milestones — a single bump event, not a bump per payload.
/// v7 added the first peephole superinstruction, `EmitLineNl` (`0x6C`,
/// `docs/optimizer-peephole.md`): a brand-new opcode discriminant, not one of
/// the reserved ones, so — like `PART_SPAN` — its own one-bump event. The
/// optimizer is the only producer; codegen output is unchanged, and the
/// reader still hard-rejects the previous version rather than translating.
/// v8 added the second superinstruction family — `BinaryImm` (`0x6D`),
/// `BinaryJumpIfFalse` (`0x6E`), `BinaryImmJumpIfFalse` (`0x6F`), each with a
/// `BinaryKind` operator byte — under the same one-bump-per-new-opcode-event
/// rule and the same optimizer-only provenance.
/// v9 added the third family — `GetTempBinaryImm` (`0x70`),
/// `GetTempBinaryImmJumpIfFalse` (`0x71`), `DuplicateBinaryImmJumpIfFalse`
/// (`0x74`): the v8 forms with their left operand's producer folded in.
/// v10 removed the parameter-binding prologue: codegen no longer emits a
/// leading `DeclareTemp` run for a container's parameters, because the VM
/// binds them into the frame at every entry instead
/// (`docs/compiler-spec.md` §"Parameter binding"). Unlike v7-v9 this is not
/// a new opcode — it is a change of meaning for existing bytecode, and the
/// dangerous direction is a v9 artifact read by a v10 runtime: its prologue
/// would decode perfectly and re-bind parameters from an empty stack. The
/// bump is what turns that into a hard rejection.
pub const VERSION: u16 = 10;
/// Fixed-size preamble: magic + version + section count + reserved + file size + checksum.
pub const HEADER_PREAMBLE: usize = 16;
/// Each offset table entry: kind(1) + reserved(3) + offset(4)
pub const SECTION_ENTRY_SIZE: usize = 8;
/// Number of *mandatory* sections in the current format (always present,
/// including the possibly-empty `AliasTable` and `EffectRows`). The optional
/// `Visibility` section (M-2b) adds one more entry to the offset table when
/// non-empty.
pub const SECTION_COUNT: u8 = 14;
// Value type tags
pub const VAL_INT: u8 = 0x00;
pub const VAL_FLOAT: u8 = 0x01;
pub const VAL_BOOL: u8 = 0x02;
pub const VAL_STRING: u8 = 0x03;
pub const VAL_LIST: u8 = 0x04;
pub const VAL_DIVERT_TARGET: u8 = 0x05;
pub const VAL_NULL: u8 = 0x06;
pub const VAL_VAR_POINTER: u8 = 0x07;
pub const VAL_FRAGMENT_REF: u8 = 0x08;
// v4 collection tags (`docs/format-v4-rfc.md` §1). Tree encoding: sharing is
// not preserved on the wire — a snapshot serializes as a plain nested tree.
pub const VAL_ARRAY: u8 = 0x09;
pub const VAL_MAP: u8 = 0x0A;
// TM-4 (`docs/typed-mode-spec.md` §6 / `docs/value-model-spec.md` §11c):
// closed-shape records. `docs/format-v4-rfc.md` §1: `ShapeId (u32 into
// StructShapes), then field values in shape order`.
pub const VAL_RECORD: u8 = 0x0F;
// T1c (`docs/t1c-spec.md` §6, `docs/format-v4-rfc.md` §1): function values.
// `VAL_FN_REF` = the zero-bound case (a `DefinitionId`); `VAL_CLOSURE` =
// `DefinitionId`, u16 env count, then env entries `{NameId, kind u8 (0=val,
// 1=ref), value}`. Numeric assignments were frozen by the one-bump rule; this
// PR (T1c-2) materializes them.
pub const VAL_FN_REF: u8 = 0x0B;
pub const VAL_CLOSURE: u8 = 0x0C;
// T1d (`docs/t1d-spec.md` §2, `docs/format-v4-rfc.md` §1): opaque
// host-resource tokens. `kind NameId, u64 id` — no live pointer, no
// dedicated opcode; handles enter the script world only via bindings.
pub const VAL_HANDLE: u8 = 0x0D;
// T1e (`docs/t1e-spec.md` §3, `docs/format-v4-rfc.md` §1): symbolic path
// projections. `cell reference (= VAL_VAR_POINTER payload shape), u8 segment
// count, then segments (u8 kind: 0=index i32 / 1=key value)`. Segment kind
// `2=range` is RESERVED — never emitted (icebox #829). First emission of
// this reserved tag.
pub const VAL_PROJECTION: u8 = 0x0E;
// NS-A1 (`docs/stdlib-spec.md` §1.1/§1.4, ruled 2026-07-18): the compiler-
// owned `Option[T]` enum. Wire form: one flag byte (0 = `none`, 1 =
// `some`), then the inner value when `some` — the enum's two variants,
// nothing more. Next free tag after `VAL_RECORD` (0x0F); this PR's own
// reservation, same "assigned here" precedent as the record/handle/
// projection tags above. Recursion counts toward `MAX_DECODE_DEPTH`
// exactly like the collection tags (a crafted chain of nested `some`s is
// the same stack-overflow shape as nested single-element arrays).
pub const VAL_OPTION: u8 = 0x10;
// NS-A5 (`docs/stdlib-spec.md` §7, F7 ruled 2026-07-19): the integer range
// value kind. Wire form: start i32, end i32, one flag byte (0 = `..`
// exclusive, 1 = `..=` inclusive) — flat, no recursion, so it does NOT
// count toward `MAX_DECODE_DEPTH` (a range holds two ints, never another
// value). Next free tag after `VAL_OPTION` (0x10); same "assigned here"
// reservation precedent as its neighbors. Distinct from the RESERVED
// projection-*segment* kind 0x02 below — that is a different namespace.
pub const VAL_RANGE: u8 = 0x11;
// NS-A8 (`docs/tower-mini-spec.md` T5, issue #1114): the numeric tower.
// Wire form is hand-serialized **explicit little-endian f32 lanes** — never
// glam's memory layout (it varies with SIMD features and versions) and never
// serde-through-glam. Lane order: vectors and the quat `x, y(, z, w)`;
// matrices column-major, column-by-column. Fixed payload sizes (no counts,
// no recursion — tower values are leaves, so like `VAL_RANGE` they do NOT
// count toward `MAX_DECODE_DEPTH`): vec2 = 8 bytes, vec3 = 12,
// vec4/quat/mat2 = 16, mat3 = 36, mat4 = 64. Next free tags after
// `VAL_RANGE` (0x11); this PR's own reservation, the same "assigned here"
// precedent as the record/handle/projection/option/range tags above. No
// format `VERSION` bump — additive value tags follow the NS-A1 `VAL_OPTION`
// precedent (an old reader rejects the unknown tag; an old file simply
// never contains one).
pub const VAL_VEC2: u8 = 0x12;
pub const VAL_VEC3: u8 = 0x13;
pub const VAL_VEC4: u8 = 0x14;
pub const VAL_QUAT: u8 = 0x15;
pub const VAL_MAT2: u8 = 0x16;
pub const VAL_MAT3: u8 = 0x17;
pub const VAL_MAT4: u8 = 0x18;
// NS-A7 (`docs/stdlib-spec.md` §8, issue #1113): the weighted table.
// Wire form: u32 entry count, then per entry an i32 weight followed by a
// recursively-encoded value. Values recurse, so decoding counts toward
// `MAX_DECODE_DEPTH` exactly like the collection tags. The reader enforces
// the §8 evidence-by-construction invariant (non-empty, weights ≥ 1) — a
// violating payload is a decode error, so a `Weighted` never enters the
// runtime invalid, even from a crafted file. Next free tag after
// `VAL_MAT4` (0x18); this PR's own reservation, additive per the NS-A1
// `VAL_OPTION` precedent (no `VERSION` bump).
pub const VAL_WEIGHTED: u8 = 0x19;
/// Wire kind for a [`crate::ProjSegment::Index`] segment.
pub const PROJ_SEG_INDEX: u8 = 0x00;
/// Wire kind for a [`crate::ProjSegment::Key`] segment.
pub const PROJ_SEG_KEY: u8 = 0x01;
// Segment kind 0x02 (range: start i32, end i32) is RESERVED — sequence
// slices/ranges (icebox #829). Never emitted; the reader rejects it
// (`InvalidProjSegmentKind`) since no `ProjSegment` variant exists to decode
// into, the same discipline the value-tag reservations above follow.
// EffectRows call-atom slots (T2-3, `docs/effects-spec.md` §11). The
// capability-parameter slot is populated `(any)` in v1; the handle-parameter
// slot is reserved (`docs/t1d-spec.md` §7) and always `None`.
/// Capability-parameter slot value: the whole capability, unrefined. The only
/// value v1 emits; path-granular tags (#826) are reserved (reader rejects).
pub const CAP_PARAM_ANY: u8 = 0x00;
/// Handle-parameter slot value: no bound handle. The only value v1 emits;
/// a non-zero slot is the reserved handle-parameterized form (reader rejects).
pub const HANDLE_PARAM_NONE: u8 = 0x00;
/// NS-A2 (issue #1108): bit assignments for the `DirectEffects` extension
/// flags byte (`EffectRows` section version 3). Bits 3–7 are RESERVED —
/// the strict reader rejects a nonzero reserved bit until a section version
/// graduates it (the same discipline as the capability/handle slots).
pub const EFFECT_DIM_EMITS: u8 = 0b0000_0001;
pub const EFFECT_DIM_TAGS: u8 = 0b0000_0010;
pub const EFFECT_DIM_FAULTS: u8 = 0b0000_0100;
pub const EFFECT_DIM_KNOWN_MASK: u8 = EFFECT_DIM_EMITS | EFFECT_DIM_TAGS | EFFECT_DIM_FAULTS;
// LineContent tags
pub const LINE_PLAIN: u8 = 0x00;
pub const LINE_TEMPLATE: u8 = 0x01;
// LinePart tags
pub const PART_LITERAL: u8 = 0x00;
pub const PART_SLOT: u8 = 0x01;
pub const PART_SELECT: u8 = 0x02;
// #1716 (`docs/prose-dialect-spec.md` §4.4/§4.5): the inline markup span.
// Structurally, adding this tag is one match arm on the existing `u8`
// part-tag dispatch — an old reader hard-rejects the unknown tag
// (`decode_line_part`'s `_ => Err(InvalidLinePart)`) and an old file simply
// never contains one. That is *not* the same as the `VAL_VEC2`/
// `VAL_WEIGHTED` no-`VERSION`-bump precedent, though: those value tags sit
// in the v4 RFC's pre-reserved, frozen tag inventory (`docs/format-v4-rfc.md`,
// the §9 one-bump rule), so materializing their encoding was already paid
// for by v4's bump. `PART_SPAN` was never part of that reservation — issue
// #1716 rules it explicitly as **"a v6 payload"**, coordinated with #1683
// (the v6 bump manifest). It IS its own one-bump event: `VERSION` bumped to
// 6 (see `VERSION`'s doc comment). `.inkl` shares this encoder/decoder
// (`inkl::{read,write}` call straight through to
// `encode_line_content`/`decode_line_content`), so both formats gain the
// tag from this one bump.
pub const PART_SPAN: u8 = 0x03;
// SelectKey tags
pub const KEY_CARDINAL: u8 = 0x00;
pub const KEY_ORDINAL: u8 = 0x01;
pub const KEY_EXACT: u8 = 0x02;
pub const KEY_KEYWORD: u8 = 0x03;
// PluralCategory tags
pub const CAT_ZERO: u8 = 0x00;
pub const CAT_ONE: u8 = 0x01;
pub const CAT_TWO: u8 = 0x02;
pub const CAT_FEW: u8 = 0x03;
pub const CAT_MANY: u8 = 0x04;
pub const CAT_OTHER: u8 = 0x05;
// ── Section types ───────────────────────────────────────────────────────────
/// Identifies a section within an `.inkb` file.
// All v4-reserved section kinds have now graduated: `LiteralPool` (0x0B),
// `StructShapes` (0x0C), and `EffectRows` (0x0D, T2-3). `Visibility` (0x0E)
// and `AliasTable` (0x0F) were later one-bump additions past the reserved
// gap; `LineVariantGroups` (0x12, #3273) is the newest.
/// An entry in the `.inkb` offset table.
/// Parsed header + offset table from an `.inkb` file.
///
/// Allows selective reads without parsing section data.
/// Cap `Vec::with_capacity` allocations against remaining buffer bytes to avoid
/// OOM on crafted inputs with huge count fields. Each element occupies at least
/// `min_element_size` bytes, so the count can't exceed `remaining / min`.
pub