Skip to main content

harn_vm/compiler/
mod.rs

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