Skip to main content

harn_vm/compiler/
mod.rs

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