Skip to main content

harn_kernel/compiler/
mod.rs

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