Skip to main content

nybl_vm/
chunk.rs

1//! Bytecode chunk layout: instructions, constants, and nested function
2//! bodies. See the crate root for the textual description of the
3//! instruction set.
4
5use core::num::{NonZeroU32, NonZeroU64};
6use nybl::parser::ParamMode;
7
8#[cfg(all(feature = "no_std", not(feature = "std")))]
9use alloc::{string::String, sync::Arc, vec::Vec};
10#[cfg(any(feature = "std", not(feature = "no_std")))]
11use std::sync::Arc;
12
13/// One bytecode operation.
14///
15/// Operand indices (`ConstIdx`, `NameIdx`, `FnIdx`, `InterpIdx`) are
16/// indices into the owning chunk's pools. Jump targets are absolute
17/// instruction indices inside the same chunk.
18///
19/// `Copy` is load-bearing for performance: the dispatch loop
20/// reads one `Instr` per step by value out of the chunk's code
21/// vec. Before `Copy` was added the read compiled to a full
22/// `.clone()` call dispatching through the `Clone` impl's
23/// match arm — surprisingly pricey in the hot path. With
24/// `Copy`, the load is a trivial register-sized memcpy that
25/// LLVM can fold into downstream dispatch.
26#[derive(Debug, Clone, Copy, PartialEq)]
27pub enum Instr {
28    // ─── Literals ─────────────────────────────────────────────────
29    LoadConst(ConstIdx),
30    LoadNone,
31    LoadTrue,
32    LoadFalse,
33
34    // ─── Variables ────────────────────────────────────────────────
35    /// Push value of the named variable onto the stack. Slow path —
36    /// walks the current frame's `scopes` BTreeMap stack, then falls
37    /// through to module-level / function-registry lookup. Emitted
38    /// for captures, imports, and anything the compiler's
39    /// `LocalResolver` couldn't pin to a slot.
40    LoadVar(NameIdx),
41    /// Pop the top value and define it as a new block-scoped local
42    /// in the current BTreeMap scope. Used for match bindings,
43    /// for-in variables at module top-level, and module-top-level
44    /// `let` statements — everywhere slot resolution isn't active.
45    DefineLocal(NameIdx),
46    /// Pop the top value and assign it to an existing BTreeMap-scoped
47    /// variable (companion to the `LoadVar` / `DefineLocal` slow
48    /// path).
49    StoreVar(NameIdx),
50
51    /// Push the value of the local at `slot`. Fast path: a single
52    /// `Vec::get_unchecked` into the current frame's slot array.
53    /// Emitted by the compiler for every identifier reference that
54    /// resolves to a function-level local (parameter, `let`, or
55    /// `for-in` variable).
56    LoadLocal(SlotIdx),
57    /// Pop the top value and assign it to the local at `slot`.
58    /// Used for both `let x = ...` initialisation and `x = ...`
59    /// assignment; the VM treats them identically once slots are
60    /// pre-sized at call time.
61    StoreLocal(SlotIdx),
62    /// Pop an already-evaluated RHS, then read and compound-assign the live
63    /// target binding. Keeping target resolution after RHS evaluation matches
64    /// the walker/AOT error and side-effect order.
65    CompoundAssign {
66        target: AssignBack,
67        op: InPlaceAssignOp,
68    },
69
70    // ─── Superinstructions ──────────────────────────────────────
71    //
72    // Fused opcodes that collapse a common 3-4 instruction
73    // sequence into a single dispatch step. The compiler emits
74    // them via peephole detection; the VM handles them with a
75    // direct slot read + typed fast path, falling back to the
76    // equivalent generic opcodes on type mismatch.
77    /// Push `frame.slots[a] + frame.slots[b]` without touching
78    /// the value stack for the operands — fuses `LoadLocal(a) +
79    /// LoadLocal(b) + Add`. Fast path specialises on both
80    /// operands being `Int`; the fallback delegates to
81    /// `ops::add` with the slot values by reference.
82    AddLocals(SlotIdx, SlotIdx),
83    /// Push `frame.slots[a] < frame.slots[b]` — fuses
84    /// `LoadLocal(a) + LoadLocal(b) + Lt`. Same
85    /// Int-fast-path / generic-fallback split as `AddLocals`.
86    LtLocals(SlotIdx, SlotIdx),
87    /// `frame.slots[slot] += k` for a small `i32` `k`. The final store
88    /// peephole fuses `LoadLocalAddInt(slot, k) + StoreLocal(slot)`, which
89    /// represents `LoadLocal(slot) + LoadConst(k) + Add + StoreLocal(slot)`.
90    /// Specialised for `Int` slots — the `i = i + 1` and
91    /// `total = total + small_k` idioms in tight loops. If the
92    /// slot isn't an `Int`, falls back to generic add via the
93    /// runtime's `ops::add`.
94    IncLocalInt(SlotIdx, i32),
95    /// Push `frame.slots[slot] + k` (as `Int`), fuses
96    /// `LoadLocal(slot) + LoadConst(k) + Add`. Covers the
97    /// `array[i + 1]` pattern. Non-Int fallback delegates to
98    /// `ops::add`, preserving the language's generic `+` semantics.
99    LoadLocalAddInt(SlotIdx, i32),
100    /// Push `frame.slots[slot] < k` (as `Bool`), fuses
101    /// `LoadLocal(slot) + LoadConst(k:Int) + Lt`. The `n < 2`
102    /// base-case test in recursive functions.
103    LtLocalInt(SlotIdx, i32),
104
105    // ─── Scope ────────────────────────────────────────────────────
106    /// Push a fresh BTreeMap onto the current frame's scopes stack.
107    /// Only relevant when the slow-path `LoadVar` / `DefineLocal`
108    /// machinery is in play; compiler omits these around blocks
109    /// whose locals live in slots.
110    PushScope,
111    PopScope,
112
113    // ─── Stack ────────────────────────────────────────────────────
114    /// Discard the top of stack.
115    Pop,
116    /// Duplicate the top of stack.
117    Dup,
118    /// Duplicate the top two items: `[.., a, b]` → `[.., a, b, a, b]`.
119    Dup2,
120
121    // ─── Binary ops ───────────────────────────────────────────────
122    Add,
123    Sub,
124    Mul,
125    Div,
126    Rem,
127    Eq,
128    NotEq,
129    Lt,
130    Gt,
131    LtEq,
132    GtEq,
133
134    // ─── Unary ops ────────────────────────────────────────────────
135    Neg,
136    Not,
137
138    /// Replace top with `Value::Bool(top.is_truthy())`. Used for
139    /// short-circuit `&&` / `||`, which must return a Bool.
140    TruthyToBool,
141
142    // ─── Indexing ─────────────────────────────────────────────────
143    /// `[.., obj, idx]` → `[.., obj[idx]]`.
144    GetIndex,
145    /// `[.., obj, idx, val]` → `[.., obj']` with `obj'[idx] == val`.
146    SetIndex,
147    /// `[.., rhs, idx]` → `[..]`, applying `op` through the live named
148    /// binding. Keeping the receiver off-stack preserves refcount-1 CoW
149    /// mutation; carrying `op` lets compound assignment read the current
150    /// element only after RHS and index evaluation, matching the walker.
151    SetIndexInPlace {
152        target: AssignBack,
153        op: InPlaceAssignOp,
154    },
155    /// Apply an assignment through an arbitrary identifier-rooted place. The
156    /// RHS and each dynamic index projection are evaluated before this
157    /// instruction; the place recipe supplies the root and field projections.
158    AssignPlace {
159        place: PlaceIdx,
160        op: InPlaceAssignOp,
161    },
162
163    // ─── String interpolation ─────────────────────────────────────
164    /// Interpolate using a recipe from the chunk's interp pool. Each
165    /// variable part is already resolved to either a frame slot or a
166    /// name-pool entry; the resulting string is pushed.
167    StringInterp(InterpIdx),
168
169    // ─── Collections ──────────────────────────────────────────────
170    /// Pop `n` items, push an array.
171    MakeArray(u32),
172    /// Pop `n` (key, value) pairs (value on top), push a dict.
173    /// Keys are pushed as string values on the stack, interleaved with
174    /// values.
175    MakeDict(u32),
176
177    // ─── Calls ────────────────────────────────────────────────────
178    /// Call `name` with `argc` arguments popped from the stack.
179    /// Resolution order: locally-bound closure → builtin → host →
180    /// named user fn → error.
181    Call {
182        name: NameIdx,
183        argc: u32,
184    },
185    /// Call whatever sits on top of the `argc` args on the stack. The
186    /// callee must be a `Value::Fn`; anything else is a runtime
187    /// error. Emitted when the call's callee expression isn't a
188    /// bare ident (e.g. `funcs[0](x)` or `make_adder(5)(3)`). Arguments
189    /// are evaluated before the callee, matching the tree walker.
190    CallValue {
191        argc: u32,
192    },
193    /// Resolve a named callable exactly once and validate the call-site shape
194    /// before any ordinary argument expression is evaluated.
195    PrepareCall {
196        name: NameIdx,
197        site: CallSiteIdx,
198    },
199    /// Pop and preflight an already-evaluated callable value.
200    PrepareCallValue {
201        site: CallSiteIdx,
202    },
203    /// Pop an already-evaluated method receiver and preflight its positional
204    /// non-receiver arguments. Used when any explicit `ref` marker is present.
205    PrepareMethodValue {
206        method: NameIdx,
207        site: CallSiteIdx,
208        nested_place: bool,
209    },
210    /// Preflight a named method receiver without snapshotting a mutable
211    /// receiver. The VM snapshots value receivers immediately, but defers a
212    /// built-in mutator or user-defined `ref self` receiver until ordinary
213    /// arguments have run.
214    PrepareMethodNamed {
215        target: NamespaceRef,
216        method: NameIdx,
217        site: CallSiteIdx,
218    },
219    /// Resolve an identifier-rooted field/index receiver before ordinary
220    /// arguments execute, retaining its exact place for mutating/ref-self
221    /// write-back.
222    PrepareMethodPlace {
223        place: PlaceIdx,
224        method: NameIdx,
225        site: CallSiteIdx,
226    },
227    /// Snapshot the prepared call's `ref` targets, interleave them with the
228    /// ordinary argument values, and enter the callable.
229    CallPrepared {
230        site: CallSiteIdx,
231    },
232    /// Method call: `[.., args..., obj]` → `[.., ret]`, and if the
233    /// method is mutating and `obj` came from a variable, the VM
234    /// writes the mutated value back to the original binding. The
235    /// back-write target is the binding that produced `obj` —
236    /// `Slot(idx)` for compile-time-resolved locals, `Name(idx)`
237    /// for the scope-map fallback, or `None` when the receiver is
238    /// a transient (e.g. `[1,2].push(3)` — nothing to update).
239    /// `nested_place` distinguishes an index/field receiver from a
240    /// genuine temporary so built-in array mutation can fail rather
241    /// than silently discarding the detached mutation.
242    CallMethod {
243        method: NameIdx,
244        argc: u32,
245        assign_back_to: Option<AssignBack>,
246        nested_place: bool,
247    },
248    /// Mutating method call on a named receiver. Unlike `CallMethod`, the
249    /// receiver is not copied onto the value stack: after evaluating the
250    /// arguments, the VM resolves `target` and mutates an array binding's
251    /// owned buffer directly. Non-array bindings fall back to ordinary method
252    /// dispatch so user-defined methods named `push`, `pop`, etc. retain their
253    /// existing behaviour. `NamespaceRef` packs both the source spelling and
254    /// optional local slot so constant checks retain the exact receiver name
255    /// without growing this hot instruction.
256    CallMethodInPlace {
257        target: NamespaceRef,
258        method: NameIdx,
259        argc: u32,
260    },
261
262    // ─── Functions ────────────────────────────────────────────────
263    /// Register the function at `FnIdx` in the current scope.
264    DefineFn(FnIdx),
265    /// Build a `Value::Fn` for the lambda at `FnIdx`, capturing
266    /// every variable currently visible in the frame's scope
267    /// stack. Pushes the resulting closure onto the value stack.
268    MakeLambda(FnIdx),
269    /// Pop the top value and return from the current call frame.
270    Return,
271    /// Return with `Value::None`.
272    ReturnNone,
273
274    // ─── Iteration / repeat ───────────────────────────────────────
275    /// Pop iterable, push an internal iterator value. The VM owns
276    /// the representation.
277    MakeIter,
278    /// If the iterator at the top of stack has another item, push
279    /// it. Otherwise pop the iterator and jump to `target`.
280    IterNext {
281        target: CodeOffset,
282    },
283    /// Pop a number, validate it, push an internal repeat counter.
284    MakeRepeatCount,
285    /// If the repeat counter at the top is non-zero, decrement it
286    /// and fall through. Otherwise pop it and jump to `target`.
287    RepeatNext {
288        target: CodeOffset,
289    },
290    /// Discard the sidecar owned by a loop exited through `break`.
291    /// The VM checks the kind so broken compiler bookkeeping cannot
292    /// silently consume an enclosing loop's state.
293    PopLoopState(LoopStateKind),
294
295    // ─── Control flow ─────────────────────────────────────────────
296    Jump(CodeOffset),
297    /// Pop top; jump if falsy.
298    JumpIfFalse(CodeOffset),
299    /// Peek top; jump if falsy (don't pop). For `&&` short-circuit.
300    JumpIfFalsePeek(CodeOffset),
301    /// Peek top; jump if truthy (don't pop). For `||` short-circuit.
302    JumpIfTruePeek(CodeOffset),
303
304    // ─── Modules ─────────────────────────────────────────────────
305    /// Resolve, parse, compile, and run the module at the path
306    /// stored in `chunk.use_specs[idx]`, then inject its exports
307    /// per the spec — glob (default), selective (`.{a, b}`),
308    /// aliased (`as m`), or both. The VM caches by module path
309    /// so re-uses are cheap. Instruction stays `Copy` by keeping
310    /// the variable-length `items` / `alias` data in a side pool.
311    Use(UseIdx),
312
313    // ─── User-defined types ─────────────────────────────────────
314    /// Register the struct type at `StructIdx` (declared fields
315    /// live in the chunk's `struct_defs` pool). Subsequent
316    /// `ConstructStruct` / `FieldGet` / `FieldSet` opcodes
317    /// reference it by type name.
318    DefineStruct(StructIdx),
319    /// Register the enum type at `EnumIdx` (variants + their
320    /// payload shapes live in the chunk's `enum_defs` pool).
321    DefineEnum(EnumIdx),
322    /// Register a user method. Receiver type is looked up by
323    /// `type_name`; the body lives in `chunk.functions[fn_idx]`
324    /// (same pool as user fns / lambdas).
325    DefineMethod {
326        type_name: NameIdx,
327        method_name: NameIdx,
328        fn_idx: FnIdx,
329    },
330    /// Validate a complete struct-construction recipe before any field payload
331    /// expression is evaluated. The field-name list lives in a side pool so
332    /// this instruction remains `Copy`.
333    ValidateStructConstruct {
334        namespace: Option<NamespaceIdx>,
335        type_name: NameIdx,
336        fields: ConstructFieldsIdx,
337    },
338    /// Validate enum type/variant/payload shape before evaluating payloads.
339    ValidateEnumConstruct {
340        namespace: Option<NamespaceIdx>,
341        type_name: NameIdx,
342        variant: NameIdx,
343        shape: EnumConstructShape,
344        fields: ConstructFieldsIdx,
345    },
346    /// Struct literal: pop `2 * count` stack entries (field-name
347    /// string + value, alternating — same layout as `MakeDict`),
348    /// validate against the struct declaration, push a
349    /// `Value::Struct`. `namespace` (when present) is the alias
350    /// for a `m.Type { ... }` access — the VM checks that the
351    /// name resolves to a `Value::Module` whose exports include
352    /// this type before falling through to the normal registry.
353    ConstructStruct {
354        namespace: Option<NamespaceIdx>,
355        type_name: NameIdx,
356        count: u32,
357    },
358    /// Enum variant construction. The `shape` tells the VM how
359    /// many stack entries the payload consumes:
360    ///
361    /// - `Unit` — no pops
362    /// - `Tuple(argc)` — pop `argc` values
363    /// - `Struct(count)` — pop `2 * count` (name, value) pairs
364    ///
365    /// `namespace` mirrors the `ConstructStruct` field — set for
366    /// `m.Result::Ok(v)` forms.
367    ConstructEnum {
368        namespace: Option<NamespaceIdx>,
369        type_name: NameIdx,
370        variant: NameIdx,
371        shape: EnumConstructShape,
372    },
373    /// Pop the object, push the value of the named field. Works
374    /// on `Value::Struct` and on `Value::EnumVariant` with
375    /// struct-shaped payloads.
376    FieldGet(NameIdx),
377    /// `[.., obj, val]` → `[.., obj']` with `obj'.field = val`.
378    /// Generic owned-value building block; named field assignment uses
379    /// [`Self::FieldSetInPlace`] to preserve unique CoW ownership.
380    FieldSet(NameIdx),
381    /// `[.., rhs]` → `[..]`, applying `op` to `field` through the live
382    /// named binding without putting a receiver clone on the value stack.
383    FieldSetInPlace {
384        target: AssignBack,
385        field: NameIdx,
386        op: InPlaceAssignOp,
387    },
388
389    // ─── Pattern matching ───────────────────────────────────────
390    /// Pattern-match the top-of-stack value against `pattern`.
391    /// The value is popped unconditionally. On success, every
392    /// binding introduced by the pattern is installed in the
393    /// current scope and execution falls through. On failure,
394    /// nothing is bound and execution jumps to `on_fail`.
395    ///
396    /// The compiler pairs each `match` arm with its own
397    /// `PushScope` / `PopScope` bracket so bindings from a
398    /// failed arm (e.g. when a guard rejects the candidate) are
399    /// discarded before the next arm runs.
400    MatchFail {
401        pattern: PatternIdx,
402        on_fail: CodeOffset,
403    },
404    /// Raise "No match arm matched the scrutinee". Emitted after
405    /// the last arm's failure path so exhausting a `match` with
406    /// no arm that applies is observable as a runtime error.
407    MatchExhausted,
408
409    /// `try <expr>` handler. Pops the top value and inspects it:
410    /// - `Ok(v)` (single tuple payload)  → push `v`, fall through
411    /// - `Ok`    (unit variant)          → push `none`, fall through
412    /// - `Err(...)`                       → act like `Return` from
413    ///   the current frame, carrying the whole `Err` variant as
414    ///   the returned value. Raises at the engine boundary if
415    ///   the current frame is the top-level program (no fn to
416    ///   return from).
417    /// - any other shape → raise a runtime error.
418    TryUnwrap,
419
420    // ─── Termination ──────────────────────────────────────────────
421    /// End the current chunk (top-level program only).
422    Halt,
423}
424
425// ─── Index newtypes ────────────────────────────────────────────────
426
427/// Index into a chunk's constant pool.
428#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
429pub struct ConstIdx(pub u32);
430
431/// Index into a chunk's name pool (used for variable and function names).
432#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
433pub struct NameIdx(pub u32);
434
435/// Index into a chunk's nested-function table.
436#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
437pub struct FnIdx(pub u32);
438
439/// Slot index inside a function frame's flat `slots: Vec<Value>`
440/// array. Assigned at compile time by the scope resolver so the
441/// dispatch loop can read/write locals via direct `Vec` indexing
442/// instead of name-keyed BTreeMap lookups. Slot numbers are
443/// unique within a function body — blocks don't reuse them, so
444/// `FnDef::slot_count` is the maximum index ever emitted plus
445/// one, which pre-sizes the `slots` vec at call time.
446#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
447pub struct SlotIdx(pub u32);
448
449/// Index into a chunk's string-interpolation recipe table.
450#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
451pub struct InterpIdx(pub u32);
452
453/// Absolute instruction index within the same chunk.
454#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
455pub struct CodeOffset(pub u32);
456
457/// Internal stack state owned by a `for` or `repeat` loop.
458#[derive(Debug, Clone, Copy, PartialEq, Eq)]
459pub enum LoopStateKind {
460    Iterator,
461    Repeat,
462}
463
464/// Instruction span of one compiled source loop (`while` / `repeat`
465/// / `for`), recorded so a step-limit error can be attributed to the
466/// loop's header line no matter which instruction the budget happens
467/// to trip on. `start` covers the per-iteration entry point (the
468/// `while` condition, `RepeatNext`, or `IterNext`); one-time setup
469/// like a `repeat` count or `for` iterable stays outside the span,
470/// matching where the tree-walker enters its loop context. `end` is
471/// exclusive: the first instruction after the loop.
472#[derive(Debug, Clone, Copy, PartialEq, Eq)]
473pub struct LoopRange {
474    pub start: CodeOffset,
475    pub end: CodeOffset,
476    /// Source line of the loop header.
477    pub line: u32,
478}
479
480/// Index into a chunk's struct-definition pool.
481#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
482pub struct StructIdx(pub u32);
483
484/// Index into a chunk's enum-definition pool.
485#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
486pub struct EnumIdx(pub u32);
487
488/// Index into a chunk's pattern pool. Each `match` arm points at
489/// one `Pattern` here; `MatchFail` consults it at runtime via the
490/// shared `nybl::pattern_matches` helper.
491#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
492pub struct PatternIdx(pub u32);
493
494/// Compact lexically resolved namespace used by a namespaced type reference.
495///
496/// Function locals live in slots, while captures and module bindings retain
497/// name-based lookup. The non-zero packed representation keeps side-table
498/// entries at eight bytes. Name index `u32::MAX` and slot index `u32::MAX` are
499/// reserved; neither can address a materializable bytecode pool or frame.
500#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
501pub struct NamespaceRef(NonZeroU64);
502
503impl NamespaceRef {
504    pub fn from_name(name: NameIdx) -> Self {
505        assert!(name.0 != u32::MAX, "namespace name index is reserved");
506        Self(NonZeroU64::new(u64::from(name.0) + 1).expect("non-zero name encoding"))
507    }
508
509    pub fn from_slot(name: NameIdx, slot: SlotIdx) -> Self {
510        assert!(name.0 != u32::MAX, "namespace name index is reserved");
511        assert!(slot.0 != u32::MAX, "namespace slot index is reserved");
512        let encoded = ((u64::from(slot.0) + 1) << 32) | u64::from(name.0);
513        Self(NonZeroU64::new(encoded).expect("non-zero slot encoding"))
514    }
515
516    pub fn name_idx(self) -> NameIdx {
517        let encoded = self.0.get();
518        if encoded <= u64::from(u32::MAX) {
519            NameIdx((encoded - 1) as u32)
520        } else {
521            NameIdx(encoded as u32)
522        }
523    }
524
525    pub fn slot_idx(self) -> Option<SlotIdx> {
526        let encoded = self.0.get();
527        if encoded <= u64::from(u32::MAX) {
528            None
529        } else {
530            Some(SlotIdx(((encoded >> 32) - 1) as u32))
531        }
532    }
533}
534
535/// Index into a chunk's namespace-reference pool. Stored as one-based
536/// `NonZeroU32` so `Option<NamespaceIdx>` remains four bytes inside hot
537/// instructions.
538#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
539pub struct NamespaceIdx(NonZeroU32);
540
541impl NamespaceIdx {
542    pub fn new(index: u32) -> Self {
543        Self(
544            NonZeroU32::new(index.checked_add(1).expect("namespace pool is too large"))
545                .expect("one-based namespace index"),
546        )
547    }
548
549    pub fn index(self) -> u32 {
550        self.0.get() - 1
551    }
552}
553
554#[cfg(test)]
555mod instruction_layout_tests {
556    use super::{Instr, NameIdx, NamespaceIdx, NamespaceRef, SlotIdx};
557
558    #[test]
559    fn instruction_remains_three_machine_words() {
560        assert_eq!(core::mem::size_of::<Instr>(), 24);
561        assert_eq!(core::mem::size_of::<Option<NamespaceIdx>>(), 4);
562    }
563
564    #[test]
565    fn packed_namespace_references_round_trip() {
566        for name in [0, u32::MAX - 1] {
567            let namespace = NamespaceRef::from_name(NameIdx(name));
568            assert_eq!(namespace.name_idx(), NameIdx(name));
569            assert_eq!(namespace.slot_idx(), None);
570
571            for slot in [0, u32::MAX - 1] {
572                let namespace = NamespaceRef::from_slot(NameIdx(name), SlotIdx(slot));
573                assert_eq!(namespace.name_idx(), NameIdx(name));
574                assert_eq!(namespace.slot_idx(), Some(SlotIdx(slot)));
575            }
576        }
577    }
578}
579
580/// Index into a chunk's `use_specs` pool. Each `use` statement
581/// emits one [`UseSpec`] describing the shape of the import
582/// (path + optional `items` + optional `alias`); `Instr::Use`
583/// stays `Copy` by holding this side-table index rather than the
584/// variable-length spec inline.
585#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
586pub struct UseIdx(pub u32);
587
588/// Index into a chunk's function-local lexical-scope metadata.
589#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
590pub struct LocalScopeIdx(pub u32);
591
592/// Index into a chunk's construction field-name recipe pool.
593#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
594pub struct ConstructFieldsIdx(pub u32);
595
596/// Index into a chunk's call-site metadata pool.
597#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
598pub struct CallSiteIdx(pub u32);
599
600/// Index into a chunk's identifier-rooted place recipe pool.
601#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
602pub struct PlaceIdx(pub u32);
603
604/// Shape of an enum variant's payload at the construction site —
605/// tells the VM how many stack entries to pop.
606#[derive(Debug, Clone, Copy, PartialEq)]
607pub enum EnumConstructShape {
608    Unit,
609    Tuple(u32),
610    Struct(u32),
611}
612
613/// Target for a mutating-method write-back. A call like
614/// `arr.push(v)` needs the VM to re-bind `arr` to the mutated
615/// array, but *where* that binding lives depends on whether the
616/// receiver was a slot-resolved local or a name-scoped variable
617/// (captures, module top-level, match bindings). The compiler
618/// picks the right form at emit time so the runtime doesn't have
619/// to probe both.
620#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
621pub enum AssignBack {
622    /// Write the mutated value back into `slots[slot]` on the
623    /// current frame.
624    Slot(SlotIdx),
625    /// Walk the current frame's BTreeMap scope stack, find the
626    /// first entry named `name`, overwrite it. Matches the
627    /// pre-slot `CallMethod` behaviour.
628    Name(NameIdx),
629}
630
631/// Compile-time classification of one explicit `ref` argument.
632#[derive(Debug, Clone, Copy, PartialEq, Eq)]
633pub enum RefArgTarget {
634    /// A mutable-binding candidate. Runtime preflight resolves the name form
635    /// to an exact scope entry and rejects captures/constants before arguments.
636    Binding(NamespaceRef),
637    /// An identifier root followed by zero or more field/index projections.
638    Place(PlaceIdx),
639    /// Any expression other than a transparent-grouped plain identifier.
640    Invalid,
641}
642
643/// One projection in a compiled mutable place. Index expressions are emitted
644/// as ordinary bytecode and supplied on the value stack; field names remain in
645/// the recipe side table.
646#[derive(Debug, Clone, Copy, PartialEq, Eq)]
647pub enum PlaceProjectionRecipe {
648    Index,
649    Field(NameIdx),
650}
651
652#[derive(Debug, Clone, PartialEq, Eq)]
653pub struct PlaceRecipe {
654    pub root: NamespaceRef,
655    pub projections: Vec<PlaceProjectionRecipe>,
656}
657
658/// Passive metadata for one source call. `arg_modes` retains positional
659/// markers even when the callee is reached dynamically. `ref_targets` is
660/// positionally parallel and must contain a target exactly at `Ref` positions.
661#[derive(Debug, Clone)]
662pub struct CallSite {
663    pub arg_modes: Vec<ParamMode>,
664    pub ref_targets: Vec<Option<RefArgTarget>>,
665}
666
667/// Assignment operation carried by direct named index/field stores.
668#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
669pub enum InPlaceAssignOp {
670    Eq,
671    Add,
672    Sub,
673    Mul,
674    Div,
675    Rem,
676}
677
678// ─── Constants and recipes ─────────────────────────────────────────
679
680#[derive(Debug, Clone, PartialEq)]
681pub enum Constant {
682    /// Exact integer constant (phase 6). Lowered from
683    /// `ExprKind::Int` and materialised as `Value::Int` at
684    /// `LoadConst` time.
685    Int(i64),
686    Number(f64),
687    Str(String),
688}
689
690/// One part of a compiled string-interpolation recipe.
691///
692/// Binding resolution happens in the compiler, not the VM: function
693/// parameters and locals become [`Self::Local`] while captures and
694/// module-level bindings remain [`Self::Name`]. This is the same split
695/// used by `LoadLocal` / `LoadVar` and avoids losing slot-only locals at
696/// runtime.
697#[derive(Debug, Clone, PartialEq)]
698pub enum InterpPart {
699    Literal(String),
700    Local(SlotIdx),
701    Name(NameIdx),
702}
703
704/// A compiled string-interpolation recipe. Parts are formatted in
705/// source order using their compile-time-resolved bindings. The immutable
706/// slice is shared so repeated interpolation only bumps a refcount.
707#[derive(Debug, Clone, PartialEq)]
708pub struct InterpRecipe {
709    pub parts: Arc<[InterpPart]>,
710}
711
712/// One unique slot-backed name declared in a lexical scope.
713///
714/// `first_binding` is the zero-based declaration position at which the name
715/// first became visible. Repeated declarations do not need another entry:
716/// every later snapshot includes the name once the first declaration is in
717/// its binding frontier.
718#[derive(Debug, Clone, Copy, PartialEq, Eq)]
719pub struct LocalScopeName {
720    pub name: NameIdx,
721    pub first_binding: u32,
722}
723
724/// Function-local names declared in one lexical scope.
725///
726/// Entries are sorted strictly by their referenced name strings so import
727/// clash checks can use binary search. The table is retained once per scope;
728/// individual `use` statements only retain a [`LocalScopeSnapshot`].
729#[derive(Debug, Clone, Default)]
730pub struct LocalScopeNames {
731    pub binding_count: u32,
732    pub entries: Vec<LocalScopeName>,
733}
734
735/// Prefix of a lexical scope that was visible at one `use` statement.
736#[derive(Debug, Clone, Copy, PartialEq, Eq)]
737pub struct LocalScopeSnapshot {
738    pub scope: LocalScopeIdx,
739    pub binding_count: u32,
740}
741
742/// Compiled descriptor for a `use` statement. Parallel to the
743/// parser's `StmtKind::Use` fields — the VM's `Use` opcode picks
744/// this up by [`UseIdx`] at runtime so the hot-path instruction
745/// stays `Copy`.
746#[derive(Debug, Clone)]
747pub struct UseSpec {
748    pub path: String,
749    pub items: Option<Vec<String>>,
750    pub alias: Option<String>,
751    /// Slot-allocated locals / parameters visible in the innermost lexical
752    /// scope at this site. The referenced scope table is shared by every use
753    /// in that scope; the frontier makes source-order visibility exact.
754    pub local_scope: Option<LocalScopeSnapshot>,
755}
756
757// ─── Chunk ─────────────────────────────────────────────────────────
758
759/// A single compiled unit: either the top-level program or one
760/// user-defined function body.
761#[derive(Debug, Clone, Default)]
762pub struct Chunk {
763    pub code: Vec<Instr>,
764    /// Source line for each instruction; parallel to `code`.
765    pub lines: Vec<u32>,
766    pub constants: Vec<Constant>,
767    pub names: Vec<String>,
768    pub interps: Vec<InterpRecipe>,
769    pub functions: Vec<FnDef>,
770    pub struct_defs: Vec<StructDef>,
771    pub enum_defs: Vec<EnumDef>,
772    /// Namespace references shared by construction preflight and construction
773    /// instructions. Indirection keeps namespace-aware instructions compact.
774    pub namespace_refs: Vec<NamespaceRef>,
775    /// Source-order field names for struct and struct-variant construction
776    /// preflight instructions.
777    pub construct_fields: Vec<Vec<String>>,
778    /// Positional modes and reference-place recipes for source calls.
779    pub call_sites: Vec<CallSite>,
780    /// Identifier-rooted mutable places used by deep assignments, explicit
781    /// ref arguments, and method receivers.
782    pub places: Vec<PlaceRecipe>,
783    /// Match patterns referenced by `MatchFail` instructions. Pool entries
784    /// are shared because matching may execute the same arm in a hot loop.
785    pub patterns: Vec<PatternRecipe>,
786    /// Side-table of `use` descriptors referenced by
787    /// `Instr::Use`. Holds variable-length fields (path, items,
788    /// alias) so the instruction payload stays `Copy`.
789    pub use_specs: Vec<UseSpec>,
790    /// `Some` when this module declares one or more `pub { ... }` surfaces.
791    /// The names are unioned in source order. `Some([])` deliberately means
792    /// an explicit empty public surface; `None` preserves legacy exports.
793    pub public_surface: Option<Vec<String>>,
794    /// Shared function-local name indexes referenced by `UseSpec` snapshots.
795    /// Empty for top-level chunks, whose bindings already live in runtime
796    /// scope maps.
797    pub local_scopes: Vec<LocalScopeNames>,
798    /// Instruction spans of every source loop in this chunk, used to
799    /// attribute step-limit errors to the innermost enclosing loop
800    /// header. Passive metadata — never consulted on the hot path.
801    pub loop_ranges: Vec<LoopRange>,
802    /// Slot count for this chunk when it serves as a function /
803    /// lambda body. Zero at the top-level program chunk (where
804    /// bindings live in the BTreeMap scope). The VM uses this
805    /// to pre-size each call frame's `slots` vec exactly once.
806    pub slot_count: u32,
807    /// Positional ABI parameter -> canonical language binding slot.
808    ///
809    /// Repeated parameter spellings map to the same slot. Calls assign these
810    /// slots in source order, so the last positional argument for a spelling
811    /// becomes the binding visible to the body. Ref write-backs use the same
812    /// map rather than assuming every positional parameter owns a slot.
813    pub parameter_slots: Vec<SlotIdx>,
814    /// Static nesting depth of the source this chunk was compiled from
815    /// (see [`nybl::ast_depth`]). The VM charges it against
816    /// `NyblLimits::max_nesting` while a frame runs this chunk, exactly as
817    /// the tree-walker charges the AST body.
818    pub nesting_depth: u32,
819}
820
821/// Compiled struct type record.
822#[derive(Debug, Clone)]
823pub struct StructDef {
824    pub name: String,
825    pub fields: Vec<String>,
826}
827
828/// Compiled enum type record.
829#[derive(Debug, Clone)]
830pub struct EnumDef {
831    pub name: String,
832    pub variants: Vec<EnumVariantDef>,
833}
834
835#[derive(Debug, Clone)]
836pub struct EnumVariantDef {
837    pub name: String,
838    pub shape: EnumVariantShape,
839}
840
841/// Payload shape of a declared enum variant.
842#[derive(Debug, Clone, PartialEq)]
843pub enum EnumVariantShape {
844    Unit,
845    Tuple(Vec<String>),
846    Struct(Vec<String>),
847}
848
849impl Chunk {
850    pub fn new() -> Self {
851        Self::default()
852    }
853
854    pub fn len(&self) -> usize {
855        self.code.len()
856    }
857
858    pub fn is_empty(&self) -> bool {
859        self.code.is_empty()
860    }
861
862    pub fn constant(&self, idx: ConstIdx) -> &Constant {
863        &self.constants[idx.0 as usize]
864    }
865
866    pub fn name(&self, idx: NameIdx) -> &str {
867        &self.names[idx.0 as usize]
868    }
869
870    pub fn interp(&self, idx: InterpIdx) -> &InterpRecipe {
871        &self.interps[idx.0 as usize]
872    }
873
874    pub fn function(&self, idx: FnIdx) -> &FnDef {
875        &self.functions[idx.0 as usize]
876    }
877
878    pub fn struct_def(&self, idx: StructIdx) -> &StructDef {
879        &self.struct_defs[idx.0 as usize]
880    }
881
882    pub fn enum_def(&self, idx: EnumIdx) -> &EnumDef {
883        &self.enum_defs[idx.0 as usize]
884    }
885
886    pub fn construct_fields(&self, idx: ConstructFieldsIdx) -> &[String] {
887        &self.construct_fields[idx.0 as usize]
888    }
889
890    pub fn call_site(&self, idx: CallSiteIdx) -> &CallSite {
891        &self.call_sites[idx.0 as usize]
892    }
893
894    pub fn place(&self, idx: PlaceIdx) -> &PlaceRecipe {
895        &self.places[idx.0 as usize]
896    }
897
898    pub fn namespace_ref(&self, idx: NamespaceIdx) -> NamespaceRef {
899        self.namespace_refs[idx.index() as usize]
900    }
901
902    pub fn pattern(&self, idx: PatternIdx) -> &PatternRecipe {
903        &self.patterns[idx.0 as usize]
904    }
905
906    pub fn use_spec(&self, idx: UseIdx) -> &UseSpec {
907        &self.use_specs[idx.0 as usize]
908    }
909
910    /// Header line of the outermost source loop whose instruction
911    /// span contains `offset`, if any. Loop spans nest properly, so
912    /// the outermost match is the one that starts earliest.
913    ///
914    /// Outermost (not innermost) keeps step-limit error lines stable
915    /// across engines: an infinite outer loop with a finite inner
916    /// loop trips the budget at an engine-dependent phase, sometimes
917    /// inside the inner loop and sometimes between passes, but the
918    /// outermost active loop is the same either way.
919    pub fn outermost_loop_line(&self, offset: CodeOffset) -> Option<u32> {
920        self.loop_ranges
921            .iter()
922            .filter(|range| range.start.0 <= offset.0 && offset.0 < range.end.0)
923            .min_by_key(|range| range.start.0)
924            .map(|range| range.line)
925    }
926}
927
928/// A pattern plus the lexical resolution selected for every namespace it
929/// contains. Namespace names remain alongside their bytecode reference because
930/// one recursive pattern can mention several distinct aliases.
931#[derive(Debug, Clone)]
932pub struct PatternRecipe {
933    pub pattern: Arc<nybl::parser::Pattern>,
934    pub namespaces: Vec<(String, NamespaceRef)>,
935}
936
937/// A compiled user-defined function.
938#[derive(Debug, Clone)]
939pub struct FnDef {
940    pub name: String,
941    pub params: Vec<String>,
942    /// Positional parameter modes retained by every callable representation.
943    pub param_modes: Vec<ParamMode>,
944    /// Immutable compiled body shared by the defining chunk, function
945    /// registry, and every closure materialised from this definition.
946    pub chunk: Arc<Chunk>,
947    /// Total slot count for this function's frame (params + every
948    /// `let` / `for-in` variable assigned a slot by the compiler).
949    /// The VM resizes the frame's `slots` vec to this length
950    /// exactly once at call time, so `LoadLocal` / `StoreLocal`
951    /// can index it without bounds-check surprises.
952    pub slot_count: u32,
953    /// Names this function body references that don't resolve to
954    /// its own locals. Filled in by the compiler for lambdas and
955    /// nested fn bodies; empty for named fn declarations (which
956    /// don't capture — their bodies see only params + the global
957    /// function registry, matching the walker's FnDecl semantics).
958    ///
959    /// Paired with `capture_sources` positionally: `captures[i]`
960    /// tells the VM *where* in the enclosing frame to read
961    /// `capture_names[i]`'s value at `MakeLambda` time.
962    pub capture_names: Vec<String>,
963    pub capture_sources: Vec<CaptureSource>,
964    /// Whether executing this named declaration must check (and record for
965    /// later imports) that no flat `use` bound the same name in its lexical
966    /// scope. The compiler clears it when that scope keeps no runtime import
967    /// record (a function block without `use`) or when a slot local declared
968    /// earlier in the scope is the name's current binding.
969    pub checks_import_clash: bool,
970}
971
972/// Where a captured name's value comes from when a lambda is
973/// materialised. Resolved at compile time by walking the enclosing
974/// function's slot table, falling back to the BTreeMap scope stack
975/// for captures-of-captures and module-top-level bindings.
976#[derive(Debug, Clone)]
977pub enum CaptureSource {
978    /// Read `enclosing_frame.slots[SlotIdx]`. Covers the common
979    /// case: a lambda referencing a local of its immediate
980    /// enclosing function.
981    ParentSlot(SlotIdx),
982    /// Look the name up in `enclosing_frame.scopes` (walked inner
983    /// -> outer). Covers nested-lambda captures-of-captures and
984    /// module-top-level references. Carries the name again
985    /// because the runtime needs it for the BTreeMap lookup.
986    ParentScope(String),
987}