Skip to main content

harn_vm/compiler/
mod.rs

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