Skip to main content

harn_vm/compiler/
mod.rs

1use harn_parser::{Node, SNode, TypeExpr, TypeParam};
2
3mod bindings;
4mod catalogs;
5mod closures;
6mod concurrency;
7mod decls;
8mod error;
9mod error_handling;
10mod expressions;
11mod hitl;
12mod optimizer;
13mod patterns;
14mod pipe;
15mod pipelines;
16mod schema_types;
17mod state;
18mod statements;
19#[cfg(test)]
20mod tests;
21mod type_facts;
22mod yield_scan;
23
24pub use error::CompileError;
25
26use crate::chunk::{Chunk, Constant, Op};
27
28/// Jump operands are 16-bit chunk offsets (`emit_jump`, `patch_jump`,
29/// backward loop jumps), so a chunk whose code grows past `u16::MAX`
30/// bytes would silently truncate jump targets and land somewhere wild at
31/// runtime. Every finalized chunk (the program chunk and each compiled
32/// function's chunk) must pass through this guard so oversized bodies
33/// fail compilation instead of miscompiling.
34pub(crate) fn ensure_chunk_addressable(
35    chunk: &Chunk,
36    what: &str,
37    line: u32,
38) -> Result<(), CompileError> {
39    if chunk.code.len() > u16::MAX as usize {
40        return Err(CompileError {
41            message: format!(
42                "{what} compiled to {} bytes of bytecode, more than the 64 KiB a jump \
43                 operand can address; split it into smaller functions",
44                chunk.code.len()
45            ),
46            line,
47        });
48    }
49    Ok(())
50}
51
52/// Environment variable that disables optional compiler optimizations.
53///
54/// The VM still emits structurally required bytecode, such as parameter
55/// slots, but skips semantic-preserving optimizer passes. This gives tests
56/// and benchmarks a stable optimized-vs-unoptimized comparison switch.
57pub const HARN_DISABLE_OPTIMIZATIONS_ENV: &str = "HARN_DISABLE_OPTIMIZATIONS";
58
59/// Controls semantic-preserving compiler optimizations.
60#[derive(Clone, Copy, Debug, PartialEq, Eq)]
61pub struct CompilerOptions {
62    optimize: bool,
63}
64
65impl CompilerOptions {
66    pub fn optimized() -> Self {
67        Self { optimize: true }
68    }
69
70    pub fn without_optimizations() -> Self {
71        Self { optimize: false }
72    }
73
74    pub fn from_env() -> Self {
75        if std::env::var_os(HARN_DISABLE_OPTIMIZATIONS_ENV).is_some() {
76            Self::without_optimizations()
77        } else {
78            Self::optimized()
79        }
80    }
81
82    pub fn optimizations_enabled(self) -> bool {
83        self.optimize
84    }
85}
86
87impl Default for CompilerOptions {
88    fn default() -> Self {
89        Self::optimized()
90    }
91}
92
93/// Look through an `AttributedDecl` wrapper to the inner declaration.
94/// `compile_named` / `compile` use this so attributed declarations like
95/// `@test pipeline foo(...)` are still discoverable by name.
96fn peel_node(sn: &SNode) -> &Node {
97    match &sn.node {
98        Node::AttributedDecl { inner, .. } => &inner.node,
99        other => other,
100    }
101}
102
103/// Entry in the compiler's pending-finally stack. See the field-level doc on
104/// `Compiler::finally_bodies` for the unwind semantics each variant encodes.
105#[derive(Clone, Debug)]
106enum FinallyEntry {
107    Finally(Vec<SNode>),
108    CatchBarrier,
109}
110
111#[derive(Clone, Debug)]
112struct TypeAliasDefinition {
113    type_params: Vec<TypeParam>,
114    /// `None` marks a selectively imported name. If typechecking accepted it
115    /// in a type expression, its runtime schema binding is the definition.
116    body: Option<TypeExpr>,
117}
118
119/// Tracks loop context for break/continue compilation.
120struct LoopContext {
121    /// Offset of the loop start (for continue).
122    start_offset: usize,
123    /// Positions of break jumps that need patching to the loop end.
124    break_patches: Vec<usize>,
125    /// True if this is a for-in loop (has an iterator to clean up on break).
126    has_iterator: bool,
127    /// Number of exception handlers active at loop entry.
128    handler_depth: usize,
129    /// Number of pending finally bodies at loop entry.
130    finally_depth: usize,
131    /// Lexical scope depth at loop entry.
132    scope_depth: usize,
133}
134
135#[derive(Clone, Copy, Debug)]
136enum LocalStorage {
137    Slot(u16),
138    /// An environment-backed cell that still participates in lexical
139    /// shadowing. Captured mutable bindings use cells so closures see later
140    /// writes, but a later same-named declaration must not retroactively
141    /// redirect earlier references into a new local slot.
142    Environment,
143}
144
145#[derive(Clone, Copy, Debug, PartialEq, Eq)]
146enum LocalBindingKind {
147    Value,
148    Callable,
149}
150
151#[derive(Clone, Copy, Debug)]
152struct LocalBinding {
153    storage: LocalStorage,
154    kind: LocalBindingKind,
155    mutable: bool,
156}
157
158struct EnumCatalogSnapshot {
159    names: std::collections::HashSet<String>,
160    variant_owners: std::collections::HashMap<String, Vec<String>>,
161}
162
163/// Compiles an AST into bytecode.
164pub struct Compiler {
165    options: CompilerOptions,
166    chunk: Chunk,
167    line: u32,
168    column: u32,
169    /// Track enum type names so PropertyAccess on them can produce EnumVariant.
170    enum_names: std::collections::HashSet<String>,
171    /// Variant name → owning enum names. Lets a bare call-shaped match
172    /// pattern (`Ok(v)`, `Some(x)`) resolve to its enum without
173    /// qualification when the variant name is unambiguous.
174    enum_variant_owners: std::collections::HashMap<String, Vec<String>>,
175    /// Names introduced by selective imports. A qualified match pattern such
176    /// as `ImportedEnum.Ready(value)` is enum-shaped even though the imported
177    /// declaration is not present in this module's AST. Keep these candidates
178    /// separate from local enum declarations so ordinary imported namespace
179    /// calls continue to use their runtime value.
180    imported_enum_candidates: std::collections::HashSet<String>,
181    /// Whether the imported-enum set came from an authoritative module-graph
182    /// projection. Direct `Compiler::new()` callers retain the conservative
183    /// AST fallback; file-backed callers can opt out when the graph found no
184    /// enum exports without paying for another syntax scan.
185    imported_enum_candidates_authoritative: bool,
186    /// Source spans of enums predeclared into the module catalog. Re-visiting
187    /// those AST nodes during bytecode emission must not replace the final
188    /// prepass view with an earlier duplicate declaration.
189    predeclared_enum_declarations: std::collections::HashSet<(usize, usize)>,
190    /// Catalog snapshots paired with lexical bytecode scopes. Enum
191    /// declarations update the active catalog in source order; restoring the
192    /// snapshot on scope exit prevents a block-local enum from leaking into
193    /// later outer match patterns.
194    enum_catalog_scopes: Vec<EnumCatalogSnapshot>,
195    /// Track struct type names to declared field order for indexed instances.
196    struct_layouts: std::collections::HashMap<String, Vec<String>>,
197    /// Track interface names → method names for runtime enforcement.
198    interface_methods: std::collections::HashMap<String, Vec<String>>,
199    /// Stack of active loop contexts for break/continue.
200    loop_stack: Vec<LoopContext>,
201    /// Current depth of exception handlers (for cleanup on break/continue).
202    handler_depth: usize,
203    /// Stack of pending finally bodies plus catch-handler barriers for
204    /// unwind-aware lowering of `throw`, `return`, `break`, and `continue`.
205    ///
206    /// A `Finally` entry is a pending finally body that must execute when
207    /// control exits its enclosing try block. A `CatchBarrier` marks the
208    /// boundary of an active `try/catch` handler: throws emitted inside
209    /// the try body are caught locally, so pre-running finallys *beyond*
210    /// the barrier would wrongly fire side effects for outer blocks the
211    /// throw never actually escapes. Throw lowering stops at the innermost
212    /// barrier; `return`/`break`/`continue`, which do transfer past local
213    /// handlers, still run every pending `Finally` up to their target.
214    finally_bodies: Vec<FinallyEntry>,
215    /// Counter for unique temp variable names.
216    temp_counter: usize,
217    /// Number of lexical block scopes currently active in this compiled frame.
218    scope_depth: usize,
219    /// Top-level and selectively imported type names used to materialize
220    /// schema expressions. Imported names remain runtime references so module
221    /// initialization can compose them after imports are bound.
222    type_aliases: std::collections::HashMap<String, TypeAliasDefinition>,
223    /// Lightweight compiler-side type facts used only for conservative
224    /// bytecode specialization. This mirrors lexical scopes and is separate
225    /// from the parser's diagnostic type checker so compile-only callers keep
226    /// working without a required type-check pass.
227    type_scopes: Vec<std::collections::HashMap<String, TypeExpr>>,
228    /// `(span.start, span.end)` of every mutable binding (`let` / `for`-item)
229    /// proven *monomorphic*: its value keeps a single primitive type across its
230    /// initializer and every reassignment in scope. Only these bindings may
231    /// carry an initializer-inferred primitive type fact into typed-opcode
232    /// specialization (`AddInt`, `LessInt`, …), which hard-errors on a runtime
233    /// operand-type mismatch. A mutable binding that is reassigned through an
234    /// `any`-typed (or otherwise non-matching) value is *not* recorded here, so
235    /// the compiler keeps it on the generic adaptive path that re-checks operand
236    /// shapes at runtime — see [`Compiler::record_monomorphic_var_bindings`].
237    /// Populated per lexical scope before that scope's statements are compiled;
238    /// keyed by byte span because `Span` is not `Hash`.
239    monomorphic_bindings: std::collections::HashSet<(usize, usize)>,
240    /// Current-chunk string constant index. This avoids repeatedly scanning the
241    /// constant pool while compiling name-heavy scripts.
242    string_constants: std::collections::HashMap<String, u16>,
243    /// Lexical bindings for the current compiled frame. Ordinary locals use
244    /// indexed slots; mutable values captured by nested callables retain an
245    /// environment-backed marker so lexical shadowing and dynamic cell access
246    /// agree on the same declaration.
247    local_scopes: Vec<std::collections::HashMap<String, LocalBinding>>,
248    /// True when this compiler is emitting code outside any function-like
249    /// scope (module top-level statements). `try*` is rejected here
250    /// because the rethrow has no enclosing function to live in.
251    /// Pipeline bodies and nested `Compiler::new()` instances (fn,
252    /// closure, tool, etc.) flip this to false before compiling.
253    module_level: bool,
254    /// Source bindings captured by a nested callable in the body this compiler
255    /// emits. Identity includes the declaration span, so a shadowing parameter
256    /// or block-local never boxes an unrelated same-named `let`.
257    captured_bindings: std::collections::HashSet<harn_parser::lexical::BindingId>,
258}
259
260impl Compiler {
261    /// Compile a single AST node. Most arm bodies live in per-category
262    /// submodules (expressions, statements, closures, decls, patterns,
263    /// error_handling, concurrency); this function is a thin dispatcher.
264    fn compile_node(&mut self, snode: &SNode) -> Result<(), CompileError> {
265        self.line = snode.span.line as u32;
266        self.column = snode.span.column as u32;
267        self.chunk.set_column(self.column);
268        if self.options.optimizations_enabled() {
269            if let Some(folded) = optimizer::fold_constant_expr(snode) {
270                if folded.node != snode.node {
271                    return self.compile_node(&folded);
272                }
273            }
274        }
275        match &snode.node {
276            Node::IntLiteral(n) => {
277                let idx = self.chunk.add_constant(Constant::Int(*n));
278                self.chunk.emit_u16(Op::Constant, idx, self.line);
279            }
280            Node::FloatLiteral(n) => {
281                let idx = self.chunk.add_constant(Constant::Float(*n));
282                self.chunk.emit_u16(Op::Constant, idx, self.line);
283            }
284            Node::StringLiteral(s) | Node::RawStringLiteral(s) => {
285                let idx = self.string_constant(s);
286                self.chunk.emit_u16(Op::Constant, idx, self.line);
287            }
288            Node::BoolLiteral(true) => self.chunk.emit(Op::True, self.line),
289            Node::BoolLiteral(false) => self.chunk.emit(Op::False, self.line),
290            Node::NilLiteral => self.chunk.emit(Op::Nil, self.line),
291            Node::DurationLiteral(ms) => {
292                let ms = i64::try_from(*ms).map_err(|_| CompileError {
293                    message: "duration literal is too large".to_string(),
294                    line: self.line,
295                })?;
296                let idx = self.chunk.add_constant(Constant::Duration(ms));
297                self.chunk.emit_u16(Op::Constant, idx, self.line);
298            }
299            Node::Identifier(name) => {
300                if self.emit_schema_for_alias(name) {
301                    return Ok(());
302                }
303                // A type-alias name in value position denotes its runtime
304                // schema. If materialization failed we would otherwise fall
305                // through to a bare variable load and surface a misleading
306                // `Undefined variable` at runtime. Only a locally-defined
307                // alias body can reach here (imported names and
308                // successfully-lowered aliases take the branch above), so name
309                // the alias and the failure at compile time instead.
310                if let Some(alias) = self.type_aliases.get(name) {
311                    if alias.body.is_some() {
312                        return Err(CompileError {
313                            message: format!(
314                                "cannot materialize a runtime schema for type alias `{name}`: it nests a type with no schema representation (for example an unbounded-recursive generic)"
315                            ),
316                            line: self.line,
317                        });
318                    }
319                }
320                self.emit_get_binding(name);
321            }
322            Node::LetBinding { pattern, value, .. } => {
323                let binding_type = match &snode.node {
324                    Node::LetBinding {
325                        type_ann: Some(type_ann),
326                        ..
327                    } => Some(type_ann.clone()),
328                    _ => self.infer_expr_type(value),
329                };
330                self.compile_node(value)?;
331                self.compile_destructuring(pattern, true, snode.span)?;
332                // A `let` is reassignable, so its initializer-inferred primitive
333                // type is only safe for typed-opcode specialization when the
334                // binding is provably monomorphic (proven by
335                // `record_monomorphic_var_bindings`, run before this scope's
336                // statements). Otherwise drop the primitive fact so arithmetic
337                // stays on the generic adaptive path, which re-checks operand
338                // shapes at runtime instead of hard-committing to `AddInt` etc.
339                let binding_type = self.gate_mutable_primitive_type(snode.span, binding_type);
340                self.record_binding_type(pattern, binding_type.clone());
341                self.maybe_register_owned_drop(pattern, binding_type.as_ref(), snode.span);
342            }
343            Node::ConstBinding { pattern, value, .. } => {
344                // `const` is an immutable binding. When its initializer is in
345                // the pure const-eval subset over a plain identifier, the
346                // typechecker has already folded it; either way the VM
347                // re-evaluates the same expression, producing the folded value
348                // byte-for-byte. Lowered immutable (destructuring allowed).
349                let binding_type = match &snode.node {
350                    Node::ConstBinding {
351                        type_ann: Some(type_ann),
352                        ..
353                    } => Some(type_ann.clone()),
354                    _ => self.infer_expr_type(value),
355                };
356                self.compile_node(value)?;
357                self.compile_destructuring(pattern, false, snode.span)?;
358                self.record_binding_type(pattern, binding_type.clone());
359                self.maybe_register_owned_drop(pattern, binding_type.as_ref(), snode.span);
360            }
361            Node::Assignment {
362                target, value, op, ..
363            } => {
364                self.compile_assignment(target, value, op)?;
365            }
366            Node::BinaryOp { op, left, right } => {
367                self.compile_binary_op(op, left, right)?;
368            }
369            Node::UnaryOp { op, operand } => {
370                self.compile_node(operand)?;
371                match op.as_str() {
372                    "-" => self.chunk.emit(Op::Negate, self.line),
373                    "!" => self.chunk.emit(Op::Not, self.line),
374                    _ => {}
375                }
376            }
377            Node::NonNullAssert { operand } => {
378                // `expr!` — identity when present, throws when `nil`. Leaves the
379                // (non-nil) value on the stack. `JumpIfFalse` peeks, so the
380                // `is_nil` bool is popped on both paths.
381                self.compile_node(operand)?; // [value]
382                self.chunk.emit(Op::Dup, self.line); // [value, value]
383                self.chunk.emit(Op::Nil, self.line); // [value, value, nil]
384                self.chunk.emit(Op::Equal, self.line); // [value, is_nil]
385                let present_jump = self.chunk.emit_jump(Op::JumpIfFalse, self.line);
386                // nil path: drop the bool, throw a structured message.
387                self.chunk.emit(Op::Pop, self.line); // [value]
388                let idx =
389                    self.string_constant("non-null assertion failed: value was nil (unwrap_nil)");
390                self.chunk.emit_u16(Op::Constant, idx, self.line);
391                self.chunk.emit(Op::Throw, self.line);
392                // present path: drop the bool, leaving the value.
393                self.chunk.patch_jump(present_jump);
394                self.chunk.emit(Op::Pop, self.line); // [value]
395            }
396            Node::Ternary {
397                condition,
398                true_expr,
399                false_expr,
400            } => {
401                self.compile_node(condition)?;
402                let else_jump = self.chunk.emit_jump(Op::JumpIfFalse, self.line);
403                self.chunk.emit(Op::Pop, self.line);
404                self.compile_node(true_expr)?;
405                let end_jump = self.chunk.emit_jump(Op::Jump, self.line);
406                self.chunk.patch_jump(else_jump);
407                self.chunk.emit(Op::Pop, self.line);
408                self.compile_node(false_expr)?;
409                self.chunk.patch_jump(end_jump);
410            }
411            Node::FunctionCall { name, args, .. } => {
412                self.compile_function_call(name, args)?;
413            }
414            Node::ValueCall { callee, args } => {
415                self.compile_call_expression(callee, args)?;
416            }
417            Node::MethodCall {
418                object,
419                method,
420                args,
421            } => {
422                self.compile_method_call(object, method, args)?;
423            }
424            Node::OptionalMethodCall {
425                object,
426                method,
427                args,
428            } => {
429                self.compile_node(object)?;
430                for arg in args {
431                    self.compile_node(arg)?;
432                }
433                let name_idx = self.string_constant(method);
434                self.chunk
435                    .emit_method_call_opt(name_idx, args.len() as u8, self.line);
436            }
437            Node::PropertyAccess { object, property } => {
438                self.compile_property_access(object, property)?;
439            }
440            Node::OptionalPropertyAccess { object, property } => {
441                self.compile_node(object)?;
442                let idx = self.string_constant(property);
443                self.chunk.emit_u16(Op::GetPropertyOpt, idx, self.line);
444            }
445            Node::SubscriptAccess { object, index } => {
446                self.compile_node(object)?;
447                self.compile_node(index)?;
448                self.chunk.emit(Op::Subscript, self.line);
449            }
450            Node::OptionalSubscriptAccess { object, index } => {
451                self.compile_node(object)?;
452                self.compile_node(index)?;
453                self.chunk.emit(Op::SubscriptOpt, self.line);
454            }
455            Node::SliceAccess { object, start, end } => {
456                self.compile_node(object)?;
457                if let Some(s) = start {
458                    self.compile_node(s)?;
459                } else {
460                    self.chunk.emit(Op::Nil, self.line);
461                }
462                if let Some(e) = end {
463                    self.compile_node(e)?;
464                } else {
465                    self.chunk.emit(Op::Nil, self.line);
466                }
467                self.chunk.emit(Op::Slice, self.line);
468            }
469            Node::IfElse {
470                condition,
471                then_body,
472                else_body,
473                ..
474            } => {
475                self.compile_if_else(condition, then_body, else_body)?;
476            }
477            Node::WhileLoop { condition, body } => {
478                self.compile_while_loop(condition, body)?;
479            }
480            Node::ForIn {
481                pattern,
482                iterable,
483                body,
484            } => {
485                self.compile_for_in(pattern, iterable, body, snode.span)?;
486            }
487            Node::ReturnStmt { value } => {
488                self.compile_return_stmt(value)?;
489            }
490            Node::BreakStmt => {
491                self.compile_break_stmt()?;
492            }
493            Node::ContinueStmt => {
494                self.compile_continue_stmt()?;
495            }
496            Node::ListLiteral(elements) => {
497                self.compile_list_literal(elements)?;
498            }
499            Node::DictLiteral(entries) => {
500                self.compile_dict_literal(entries)?;
501            }
502            Node::InterpolatedString(segments) => {
503                self.compile_interpolated_string(segments)?;
504            }
505            Node::FnDecl {
506                name,
507                type_params,
508                params,
509                body,
510                is_stream,
511                ..
512            } => {
513                self.compile_fn_decl(name, type_params, params, body, *is_stream)?;
514            }
515            Node::ToolDecl {
516                name,
517                description,
518                params,
519                return_type,
520                body,
521                ..
522            } => {
523                self.compile_tool_decl(name, description, params, return_type, body)?;
524            }
525            Node::SkillDecl { name, fields, .. } => {
526                self.compile_skill_decl(name, fields)?;
527            }
528            Node::EvalPackDecl {
529                binding_name,
530                pack_id,
531                fields,
532                body,
533                summarize,
534                ..
535            } => {
536                self.compile_eval_pack_decl(binding_name, pack_id, fields, body, summarize, true)?;
537            }
538            Node::Closure { params, body, .. } => {
539                self.compile_closure(params, body)?;
540            }
541            Node::ThrowStmt { value } => {
542                self.compile_throw_stmt(value)?;
543            }
544            Node::MatchExpr { value, arms } => {
545                self.compile_match_expr(value, arms)?;
546            }
547            Node::RangeExpr {
548                start,
549                end,
550                inclusive,
551            } => {
552                let name_idx = self.string_constant("__range__");
553                self.chunk.emit_u16(Op::Constant, name_idx, self.line);
554                self.compile_node(start)?;
555                self.compile_node(end)?;
556                if *inclusive {
557                    self.chunk.emit(Op::True, self.line);
558                } else {
559                    self.chunk.emit(Op::False, self.line);
560                }
561                self.chunk.emit_u8(Op::Call, 3, self.line);
562            }
563            Node::GuardStmt {
564                condition,
565                else_body,
566            } => {
567                self.compile_guard_stmt(condition, else_body)?;
568            }
569            Node::RequireStmt { condition, message } => {
570                self.compile_node(condition)?;
571                let ok_jump = self.chunk.emit_jump(Op::JumpIfTrue, self.line);
572                self.chunk.emit(Op::Pop, self.line);
573                if let Some(message) = message {
574                    self.compile_node(message)?;
575                } else {
576                    let idx = self.string_constant("require condition failed");
577                    self.chunk.emit_u16(Op::Constant, idx, self.line);
578                }
579                self.chunk.emit(Op::Throw, self.line);
580                self.chunk.patch_jump(ok_jump);
581                self.chunk.emit(Op::Pop, self.line);
582            }
583            Node::Block(stmts) => {
584                self.compile_scoped_block(stmts)?;
585            }
586            Node::DeadlineBlock { duration, body } => {
587                self.compile_node(duration)?;
588                self.chunk.emit(Op::DeadlineSetup, self.line);
589                self.compile_scoped_block(body)?;
590                self.chunk.emit(Op::DeadlineEnd, self.line);
591            }
592            Node::MutexBlock { key, body } => {
593                self.begin_scope();
594                let finally_floor = self.finally_bodies.len();
595                match key {
596                    // `mutex(resource) { ... }`: evaluate the resource and key
597                    // the lock on its structural value at runtime.
598                    Some(key_expr) => {
599                        self.compile_node(key_expr)?;
600                        self.chunk.emit(Op::SyncMutexEnterKeyed, self.line);
601                    }
602                    // `mutex { ... }`: key on the lexical call-site (computed in
603                    // the VM from the chunk + instruction pointer) so distinct
604                    // blocks don't contend on one global lock.
605                    None => {
606                        self.chunk.emit(Op::SyncMutexEnter, self.line);
607                    }
608                }
609                for sn in body {
610                    self.compile_discarded_stmt(sn)?;
611                }
612                self.drain_finallys_to_floor(finally_floor)?;
613                self.chunk.emit(Op::Nil, self.line);
614                self.end_scope();
615            }
616            Node::ScopeBlock { body } => {
617                // Structured-concurrency nursery. `TaskScopeEnter` pushes a task
618                // scope; tasks spawned inside register to it. `TaskScopeExit`
619                // joins them (propagating the first error, cancelling the rest).
620                // On `throw`/early exit the scope is unwound and its tasks
621                // cancelled by the frame/handler teardown, mirroring
622                // `held_sync_guards`.
623                self.begin_scope();
624                let finally_floor = self.finally_bodies.len();
625                self.chunk.emit(Op::TaskScopeEnter, self.line);
626                for sn in body {
627                    self.compile_discarded_stmt(sn)?;
628                }
629                self.drain_finallys_to_floor(finally_floor)?;
630                self.chunk.emit(Op::TaskScopeExit, self.line);
631                self.chunk.emit(Op::Nil, self.line);
632                self.end_scope();
633            }
634            Node::DeferStmt { body } => {
635                // Register the body to run on return/throw/scope-exit. The
636                // statement emits no bytecode of its own — the deferred body
637                // is inlined later by the finally-draining machinery — so it
638                // leaves the operand stack untouched, matching
639                // `produces_value` == false. Emitting a `Nil` here instead
640                // leaked an unpopped slot per execution, which in a loop body
641                // grew the operand stack without bound (surfaced by the
642                // #2622 balance assertion).
643                self.finally_bodies
644                    .push(FinallyEntry::Finally(body.clone()));
645            }
646            Node::YieldExpr { value } => {
647                if let Some(val) = value {
648                    self.compile_node(val)?;
649                } else {
650                    self.chunk.emit(Op::Nil, self.line);
651                }
652                self.chunk.emit(Op::Yield, self.line);
653            }
654            Node::EmitExpr { value } => {
655                self.compile_node(value)?;
656                self.chunk.emit(Op::Yield, self.line);
657            }
658            Node::EnumConstruct {
659                enum_name,
660                variant,
661                args,
662            } => {
663                self.compile_enum_construct(enum_name, variant, args)?;
664            }
665            Node::StructConstruct {
666                struct_name,
667                fields,
668            } => {
669                self.compile_struct_construct(struct_name, fields)?;
670            }
671            Node::ImportDecl { path, .. } => {
672                let idx = self.string_constant(path);
673                self.chunk.emit_u16(Op::Import, idx, self.line);
674            }
675            Node::SelectiveImport { names, path, .. } => {
676                let path_idx = self.string_constant(path);
677                let names_str = names.join(",");
678                let names_idx = self.owned_string_constant(names_str);
679                self.chunk
680                    .emit_u16(Op::SelectiveImport, path_idx, self.line);
681                let hi = (names_idx >> 8) as u8;
682                let lo = names_idx as u8;
683                self.chunk.code.push(hi);
684                self.chunk.code.push(lo);
685                self.chunk.lines.push(self.line);
686                self.chunk.columns.push(self.column);
687                self.chunk.lines.push(self.line);
688                self.chunk.columns.push(self.column);
689            }
690            Node::NamespaceImport { alias, path, .. } => {
691                let path_idx = self.string_constant(path);
692                let alias_idx = self.string_constant(alias);
693                self.chunk
694                    .emit_u16(Op::NamespaceImport, path_idx, self.line);
695                let hi = (alias_idx >> 8) as u8;
696                let lo = alias_idx as u8;
697                self.chunk.code.push(hi);
698                self.chunk.code.push(lo);
699                self.chunk.lines.push(self.line);
700                self.chunk.columns.push(self.column);
701                self.chunk.lines.push(self.line);
702                self.chunk.columns.push(self.column);
703            }
704            Node::TryOperator { operand } => {
705                self.compile_node(operand)?;
706                self.chunk.emit(Op::TryUnwrap, self.line);
707            }
708            // `try* EXPR`: evaluate EXPR; on throw, run pending finally
709            // blocks up to the innermost catch barrier and rethrow the
710            // original value. On success, leave EXPR's value on the stack.
711            //
712            // Per the issue-#26 desugaring:
713            //   { let _r = try { EXPR }
714            //     guard is_ok(_r) else { throw unwrap_err(_r) }
715            //     unwrap(_r) }
716            //
717            // The bytecode realizes this directly: install a try handler
718            // around EXPR so a throw lands in our catch path, where we
719            // pre-run pending finallys and re-emit `Throw`. Skipping the
720            // intermediate Result.Ok/Err wrapping that `TryExpr` does
721            // keeps the success path a no-op (operand value passes through
722            // as-is).
723            Node::TryStar { operand } => {
724                self.compile_try_star(operand)?;
725            }
726            Node::ImplBlock { type_name, methods } => {
727                self.compile_impl_block(type_name, methods)?;
728            }
729            Node::StructDecl { name, fields, .. } => {
730                self.compile_struct_decl(name, fields)?;
731            }
732            // Metadata-only declarations: enum names, struct/interface
733            // layouts, and type aliases are pre-scanned, so they emit no
734            // bytecode and leave the operand stack untouched. Type-alias names
735            // in expression position lower to schema expressions in the
736            // `Identifier` arm above; exported aliases use a separate compact
737            // initializer so ordinary module init chunks stay within the VM's
738            // 64 KiB jump limit.
739            // `produces_value` classifies them as non-value-producing to match;
740            // contexts that require a block to yield a value (last statement of
741            // a block, match-arm body) emit their own `Nil` placeholder.
742            // Emitting one here instead left an unpopped `Nil` on the stack in
743            // every value-discarding context (`compile_top_level_declarations`
744            // pops nothing) — a latent imbalance surfaced by the #2622 balance
745            // assertion.
746            Node::EnumDecl { name, variants, .. } => {
747                let declaration = (snode.span.start, snode.span.end);
748                if !self.predeclared_enum_declarations.contains(&declaration) {
749                    self.register_enum_decl(name, variants);
750                }
751                if self.module_level {
752                    self.compile_enum_decl(name, variants)?;
753                }
754            }
755            Node::Pipeline { .. }
756            | Node::OverrideDecl { .. }
757            | Node::TypeDecl { .. }
758            | Node::InterfaceDecl { .. } => {}
759            Node::TryCatch {
760                has_catch: _,
761                body,
762                error_var,
763                error_type,
764                catch_body,
765                finally_body,
766                ..
767            } => {
768                self.compile_try_catch(body, error_var, error_type, catch_body, finally_body)?;
769            }
770            Node::TryExpr { body } => {
771                self.compile_try_expr(body)?;
772            }
773            Node::Retry { count, body } => {
774                self.compile_retry(count, body)?;
775            }
776            Node::CostRoute { options, body } => {
777                self.compile_cost_route(options, body)?;
778            }
779            Node::Parallel {
780                mode,
781                expr,
782                variable,
783                body,
784                options,
785            } => {
786                self.compile_parallel(mode, expr, variable, body, options)?;
787            }
788            Node::SpawnExpr { body } => {
789                self.compile_spawn_expr(body)?;
790            }
791            Node::HitlExpr { kind, args } => {
792                self.compile_hitl_expr(*kind, args)?;
793            }
794            Node::SelectExpr {
795                cases,
796                timeout,
797                default_body,
798            } => {
799                self.compile_select_expr(cases, timeout, default_body)?;
800            }
801            Node::Spread(_) => {
802                return Err(CompileError {
803                    message: "spread (...) can only be used inside list literals, dict literals, or function call arguments".into(),
804                    line: self.line,
805                });
806            }
807            Node::AttributedDecl { attributes, inner } => {
808                self.compile_attributed_decl(attributes, inner)?;
809            }
810            Node::OrPattern(_) => {
811                return Err(CompileError {
812                    message: "or-pattern (|) can only appear as a match arm pattern".into(),
813                    line: self.line,
814                });
815            }
816        }
817        Ok(())
818    }
819}