Skip to main content

harn_kernel/compiler/
mod.rs

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