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