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