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 /// Names referenced inside a nested closure of the body this compiler is
199 /// emitting. A mutable (`let`) local whose name is in this set is captured
200 /// by a closure, so it is boxed into a shared cell (`Op::DefCell`) rather
201 /// than a by-value local slot — this is what makes closure capture
202 /// **by reference** (harn#4479). Recomputed per function-like body via
203 /// [`Compiler::seed_captured_idents`]; an over-approximation (a shadowed or
204 /// read-only capture may be boxed) is safe — it only forgoes the slot fast
205 /// path for that one local. `const` locals and params are immutable and
206 /// never boxed.
207 captured_idents: std::collections::HashSet<String>,
208}
209
210impl Compiler {
211 /// Compile a single AST node. Most arm bodies live in per-category
212 /// submodules (expressions, statements, closures, decls, patterns,
213 /// error_handling, concurrency); this function is a thin dispatcher.
214 fn compile_node(&mut self, snode: &SNode) -> Result<(), CompileError> {
215 self.line = snode.span.line as u32;
216 self.column = snode.span.column as u32;
217 self.chunk.set_column(self.column);
218 if self.options.optimizations_enabled() {
219 if let Some(folded) = optimizer::fold_constant_expr(snode) {
220 if folded.node != snode.node {
221 return self.compile_node(&folded);
222 }
223 }
224 }
225 match &snode.node {
226 Node::IntLiteral(n) => {
227 let idx = self.chunk.add_constant(Constant::Int(*n));
228 self.chunk.emit_u16(Op::Constant, idx, self.line);
229 }
230 Node::FloatLiteral(n) => {
231 let idx = self.chunk.add_constant(Constant::Float(*n));
232 self.chunk.emit_u16(Op::Constant, idx, self.line);
233 }
234 Node::StringLiteral(s) | Node::RawStringLiteral(s) => {
235 let idx = self.string_constant(s);
236 self.chunk.emit_u16(Op::Constant, idx, self.line);
237 }
238 Node::BoolLiteral(true) => self.chunk.emit(Op::True, self.line),
239 Node::BoolLiteral(false) => self.chunk.emit(Op::False, self.line),
240 Node::NilLiteral => self.chunk.emit(Op::Nil, self.line),
241 Node::DurationLiteral(ms) => {
242 let ms = i64::try_from(*ms).map_err(|_| CompileError {
243 message: "duration literal is too large".to_string(),
244 line: self.line,
245 })?;
246 let idx = self.chunk.add_constant(Constant::Duration(ms));
247 self.chunk.emit_u16(Op::Constant, idx, self.line);
248 }
249 Node::Identifier(name) => {
250 if let Some(schema) = self.schema_value_for_alias(name) {
251 self.emit_vm_value_literal(&schema);
252 return Ok(());
253 }
254 self.emit_get_binding(name);
255 }
256 Node::LetBinding { pattern, value, .. } => {
257 let binding_type = match &snode.node {
258 Node::LetBinding {
259 type_ann: Some(type_ann),
260 ..
261 } => Some(type_ann.clone()),
262 _ => self.infer_expr_type(value),
263 };
264 self.compile_node(value)?;
265 self.compile_destructuring(pattern, true)?;
266 // A `let` is reassignable, so its initializer-inferred primitive
267 // type is only safe for typed-opcode specialization when the
268 // binding is provably monomorphic (proven by
269 // `record_monomorphic_var_bindings`, run before this scope's
270 // statements). Otherwise drop the primitive fact so arithmetic
271 // stays on the generic adaptive path, which re-checks operand
272 // shapes at runtime instead of hard-committing to `AddInt` etc.
273 let binding_type = self.gate_mutable_primitive_type(snode.span, binding_type);
274 self.record_binding_type(pattern, binding_type.clone());
275 self.maybe_register_owned_drop(pattern, binding_type.as_ref(), snode.span);
276 }
277 Node::ConstBinding { pattern, value, .. } => {
278 // `const` is an immutable binding. When its initializer is in
279 // the pure const-eval subset over a plain identifier, the
280 // typechecker has already folded it; either way the VM
281 // re-evaluates the same expression, producing the folded value
282 // byte-for-byte. Lowered immutable (destructuring allowed).
283 let binding_type = match &snode.node {
284 Node::ConstBinding {
285 type_ann: Some(type_ann),
286 ..
287 } => Some(type_ann.clone()),
288 _ => self.infer_expr_type(value),
289 };
290 self.compile_node(value)?;
291 self.compile_destructuring(pattern, false)?;
292 self.record_binding_type(pattern, binding_type.clone());
293 self.maybe_register_owned_drop(pattern, binding_type.as_ref(), snode.span);
294 }
295 Node::Assignment {
296 target, value, op, ..
297 } => {
298 self.compile_assignment(target, value, op)?;
299 }
300 Node::BinaryOp { op, left, right } => {
301 self.compile_binary_op(op, left, right)?;
302 }
303 Node::UnaryOp { op, operand } => {
304 self.compile_node(operand)?;
305 match op.as_str() {
306 "-" => self.chunk.emit(Op::Negate, self.line),
307 "!" => self.chunk.emit(Op::Not, self.line),
308 _ => {}
309 }
310 }
311 Node::NonNullAssert { operand } => {
312 // `expr!` — identity when present, throws when `nil`. Leaves the
313 // (non-nil) value on the stack. `JumpIfFalse` peeks, so the
314 // `is_nil` bool is popped on both paths.
315 self.compile_node(operand)?; // [value]
316 self.chunk.emit(Op::Dup, self.line); // [value, value]
317 self.chunk.emit(Op::Nil, self.line); // [value, value, nil]
318 self.chunk.emit(Op::Equal, self.line); // [value, is_nil]
319 let present_jump = self.chunk.emit_jump(Op::JumpIfFalse, self.line);
320 // nil path: drop the bool, throw a structured message.
321 self.chunk.emit(Op::Pop, self.line); // [value]
322 let idx =
323 self.string_constant("non-null assertion failed: value was nil (unwrap_nil)");
324 self.chunk.emit_u16(Op::Constant, idx, self.line);
325 self.chunk.emit(Op::Throw, self.line);
326 // present path: drop the bool, leaving the value.
327 self.chunk.patch_jump(present_jump);
328 self.chunk.emit(Op::Pop, self.line); // [value]
329 }
330 Node::Ternary {
331 condition,
332 true_expr,
333 false_expr,
334 } => {
335 self.compile_node(condition)?;
336 let else_jump = self.chunk.emit_jump(Op::JumpIfFalse, self.line);
337 self.chunk.emit(Op::Pop, self.line);
338 self.compile_node(true_expr)?;
339 let end_jump = self.chunk.emit_jump(Op::Jump, self.line);
340 self.chunk.patch_jump(else_jump);
341 self.chunk.emit(Op::Pop, self.line);
342 self.compile_node(false_expr)?;
343 self.chunk.patch_jump(end_jump);
344 }
345 Node::FunctionCall { name, args, .. } => {
346 self.compile_function_call(name, args)?;
347 }
348 Node::MethodCall {
349 object,
350 method,
351 args,
352 } => {
353 self.compile_method_call(object, method, args)?;
354 }
355 Node::OptionalMethodCall {
356 object,
357 method,
358 args,
359 } => {
360 self.compile_node(object)?;
361 for arg in args {
362 self.compile_node(arg)?;
363 }
364 let name_idx = self.string_constant(method);
365 self.chunk
366 .emit_method_call_opt(name_idx, args.len() as u8, self.line);
367 }
368 Node::PropertyAccess { object, property } => {
369 self.compile_property_access(object, property)?;
370 }
371 Node::OptionalPropertyAccess { object, property } => {
372 self.compile_node(object)?;
373 let idx = self.string_constant(property);
374 self.chunk.emit_u16(Op::GetPropertyOpt, idx, self.line);
375 }
376 Node::SubscriptAccess { object, index } => {
377 self.compile_node(object)?;
378 self.compile_node(index)?;
379 self.chunk.emit(Op::Subscript, self.line);
380 }
381 Node::OptionalSubscriptAccess { object, index } => {
382 self.compile_node(object)?;
383 self.compile_node(index)?;
384 self.chunk.emit(Op::SubscriptOpt, self.line);
385 }
386 Node::SliceAccess { object, start, end } => {
387 self.compile_node(object)?;
388 if let Some(s) = start {
389 self.compile_node(s)?;
390 } else {
391 self.chunk.emit(Op::Nil, self.line);
392 }
393 if let Some(e) = end {
394 self.compile_node(e)?;
395 } else {
396 self.chunk.emit(Op::Nil, self.line);
397 }
398 self.chunk.emit(Op::Slice, self.line);
399 }
400 Node::IfElse {
401 condition,
402 then_body,
403 else_body,
404 } => {
405 self.compile_if_else(condition, then_body, else_body)?;
406 }
407 Node::WhileLoop { condition, body } => {
408 self.compile_while_loop(condition, body)?;
409 }
410 Node::ForIn {
411 pattern,
412 iterable,
413 body,
414 } => {
415 self.compile_for_in(pattern, iterable, body)?;
416 }
417 Node::ReturnStmt { value } => {
418 self.compile_return_stmt(value)?;
419 }
420 Node::BreakStmt => {
421 self.compile_break_stmt()?;
422 }
423 Node::ContinueStmt => {
424 self.compile_continue_stmt()?;
425 }
426 Node::ListLiteral(elements) => {
427 self.compile_list_literal(elements)?;
428 }
429 Node::DictLiteral(entries) => {
430 self.compile_dict_literal(entries)?;
431 }
432 Node::InterpolatedString(segments) => {
433 self.compile_interpolated_string(segments)?;
434 }
435 Node::FnDecl {
436 name,
437 type_params,
438 params,
439 body,
440 is_stream,
441 ..
442 } => {
443 self.compile_fn_decl(name, type_params, params, body, *is_stream)?;
444 }
445 Node::ToolDecl {
446 name,
447 description,
448 params,
449 return_type,
450 body,
451 ..
452 } => {
453 self.compile_tool_decl(name, description, params, return_type, body)?;
454 }
455 Node::SkillDecl { name, fields, .. } => {
456 self.compile_skill_decl(name, fields)?;
457 }
458 Node::EvalPackDecl {
459 binding_name,
460 pack_id,
461 fields,
462 body,
463 summarize,
464 ..
465 } => {
466 self.compile_eval_pack_decl(binding_name, pack_id, fields, body, summarize, true)?;
467 }
468 Node::Closure { params, body, .. } => {
469 self.compile_closure(params, body)?;
470 }
471 Node::ThrowStmt { value } => {
472 self.compile_throw_stmt(value)?;
473 }
474 Node::MatchExpr { value, arms } => {
475 self.compile_match_expr(value, arms)?;
476 }
477 Node::RangeExpr {
478 start,
479 end,
480 inclusive,
481 } => {
482 let name_idx = self.string_constant("__range__");
483 self.chunk.emit_u16(Op::Constant, name_idx, self.line);
484 self.compile_node(start)?;
485 self.compile_node(end)?;
486 if *inclusive {
487 self.chunk.emit(Op::True, self.line);
488 } else {
489 self.chunk.emit(Op::False, self.line);
490 }
491 self.chunk.emit_u8(Op::Call, 3, self.line);
492 }
493 Node::GuardStmt {
494 condition,
495 else_body,
496 } => {
497 self.compile_guard_stmt(condition, else_body)?;
498 }
499 Node::RequireStmt { condition, message } => {
500 self.compile_node(condition)?;
501 let ok_jump = self.chunk.emit_jump(Op::JumpIfTrue, self.line);
502 self.chunk.emit(Op::Pop, self.line);
503 if let Some(message) = message {
504 self.compile_node(message)?;
505 } else {
506 let idx = self.string_constant("require condition failed");
507 self.chunk.emit_u16(Op::Constant, idx, self.line);
508 }
509 self.chunk.emit(Op::Throw, self.line);
510 self.chunk.patch_jump(ok_jump);
511 self.chunk.emit(Op::Pop, self.line);
512 }
513 Node::Block(stmts) => {
514 self.compile_scoped_block(stmts)?;
515 }
516 Node::DeadlineBlock { duration, body } => {
517 self.compile_node(duration)?;
518 self.chunk.emit(Op::DeadlineSetup, self.line);
519 self.compile_scoped_block(body)?;
520 self.chunk.emit(Op::DeadlineEnd, self.line);
521 }
522 Node::MutexBlock { key, body } => {
523 self.begin_scope();
524 let finally_floor = self.finally_bodies.len();
525 match key {
526 // `mutex(resource) { ... }`: evaluate the resource and key
527 // the lock on its structural value at runtime.
528 Some(key_expr) => {
529 self.compile_node(key_expr)?;
530 self.chunk.emit(Op::SyncMutexEnterKeyed, self.line);
531 }
532 // `mutex { ... }`: key on the lexical call-site (computed in
533 // the VM from the chunk + instruction pointer) so distinct
534 // blocks don't contend on one global lock.
535 None => {
536 self.chunk.emit(Op::SyncMutexEnter, self.line);
537 }
538 }
539 for sn in body {
540 self.compile_discarded_stmt(sn)?;
541 }
542 self.drain_finallys_to_floor(finally_floor)?;
543 self.chunk.emit(Op::Nil, self.line);
544 self.end_scope();
545 }
546 Node::ScopeBlock { body } => {
547 // Structured-concurrency nursery. `TaskScopeEnter` pushes a task
548 // scope; tasks spawned inside register to it. `TaskScopeExit`
549 // joins them (propagating the first error, cancelling the rest).
550 // On `throw`/early exit the scope is unwound and its tasks
551 // cancelled by the frame/handler teardown, mirroring
552 // `held_sync_guards`.
553 self.begin_scope();
554 let finally_floor = self.finally_bodies.len();
555 self.chunk.emit(Op::TaskScopeEnter, self.line);
556 for sn in body {
557 self.compile_discarded_stmt(sn)?;
558 }
559 self.drain_finallys_to_floor(finally_floor)?;
560 self.chunk.emit(Op::TaskScopeExit, self.line);
561 self.chunk.emit(Op::Nil, self.line);
562 self.end_scope();
563 }
564 Node::DeferStmt { body } => {
565 // Register the body to run on return/throw/scope-exit. The
566 // statement emits no bytecode of its own — the deferred body
567 // is inlined later by the finally-draining machinery — so it
568 // leaves the operand stack untouched, matching
569 // `produces_value` == false. Emitting a `Nil` here instead
570 // leaked an unpopped slot per execution, which in a loop body
571 // grew the operand stack without bound (surfaced by the
572 // #2622 balance assertion).
573 self.finally_bodies
574 .push(FinallyEntry::Finally(body.clone()));
575 }
576 Node::YieldExpr { value } => {
577 if let Some(val) = value {
578 self.compile_node(val)?;
579 } else {
580 self.chunk.emit(Op::Nil, self.line);
581 }
582 self.chunk.emit(Op::Yield, self.line);
583 }
584 Node::EmitExpr { value } => {
585 self.compile_node(value)?;
586 self.chunk.emit(Op::Yield, self.line);
587 }
588 Node::EnumConstruct {
589 enum_name,
590 variant,
591 args,
592 } => {
593 self.compile_enum_construct(enum_name, variant, args)?;
594 }
595 Node::StructConstruct {
596 struct_name,
597 fields,
598 } => {
599 self.compile_struct_construct(struct_name, fields)?;
600 }
601 Node::ImportDecl { path, .. } => {
602 let idx = self.string_constant(path);
603 self.chunk.emit_u16(Op::Import, idx, self.line);
604 }
605 Node::SelectiveImport { names, path, .. } => {
606 let path_idx = self.string_constant(path);
607 let names_str = names.join(",");
608 let names_idx = self.owned_string_constant(names_str);
609 self.chunk
610 .emit_u16(Op::SelectiveImport, path_idx, self.line);
611 let hi = (names_idx >> 8) as u8;
612 let lo = names_idx as u8;
613 self.chunk.code.push(hi);
614 self.chunk.code.push(lo);
615 self.chunk.lines.push(self.line);
616 self.chunk.columns.push(self.column);
617 self.chunk.lines.push(self.line);
618 self.chunk.columns.push(self.column);
619 }
620 Node::TryOperator { operand } => {
621 self.compile_node(operand)?;
622 self.chunk.emit(Op::TryUnwrap, self.line);
623 }
624 // `try* EXPR`: evaluate EXPR; on throw, run pending finally
625 // blocks up to the innermost catch barrier and rethrow the
626 // original value. On success, leave EXPR's value on the stack.
627 //
628 // Per the issue-#26 desugaring:
629 // { let _r = try { EXPR }
630 // guard is_ok(_r) else { throw unwrap_err(_r) }
631 // unwrap(_r) }
632 //
633 // The bytecode realizes this directly: install a try handler
634 // around EXPR so a throw lands in our catch path, where we
635 // pre-run pending finallys and re-emit `Throw`. Skipping the
636 // intermediate Result.Ok/Err wrapping that `TryExpr` does
637 // keeps the success path a no-op (operand value passes through
638 // as-is).
639 Node::TryStar { operand } => {
640 self.compile_try_star(operand)?;
641 }
642 Node::ImplBlock { type_name, methods } => {
643 self.compile_impl_block(type_name, methods)?;
644 }
645 Node::StructDecl { name, fields, .. } => {
646 self.compile_struct_decl(name, fields)?;
647 }
648 // Metadata-only declarations: enum names, struct/interface
649 // layouts, and type aliases are pre-scanned, so they emit no
650 // bytecode and leave the operand stack untouched. Type-alias names
651 // in expression position lower directly to schema constants in the
652 // `Identifier` arm above; eagerly binding every alias at top level
653 // bloats large module init chunks past the VM's 64 KiB jump limit.
654 // `produces_value` classifies them as non-value-producing to match;
655 // contexts that require a block to yield a value (last statement of
656 // a block, match-arm body) emit their own `Nil` placeholder.
657 // Emitting one here instead left an unpopped `Nil` on the stack in
658 // every value-discarding context (`compile_top_level_declarations`
659 // pops nothing) — a latent imbalance surfaced by the #2622 balance
660 // assertion.
661 Node::Pipeline { .. }
662 | Node::OverrideDecl { .. }
663 | Node::TypeDecl { .. }
664 | Node::EnumDecl { .. }
665 | Node::InterfaceDecl { .. } => {}
666 Node::TryCatch {
667 has_catch: _,
668 body,
669 error_var,
670 error_type,
671 catch_body,
672 finally_body,
673 } => {
674 self.compile_try_catch(body, error_var, error_type, catch_body, finally_body)?;
675 }
676 Node::TryExpr { body } => {
677 self.compile_try_expr(body)?;
678 }
679 Node::Retry { count, body } => {
680 self.compile_retry(count, body)?;
681 }
682 Node::CostRoute { options, body } => {
683 self.compile_cost_route(options, body)?;
684 }
685 Node::Parallel {
686 mode,
687 expr,
688 variable,
689 body,
690 options,
691 } => {
692 self.compile_parallel(mode, expr, variable, body, options)?;
693 }
694 Node::SpawnExpr { body } => {
695 self.compile_spawn_expr(body)?;
696 }
697 Node::HitlExpr { kind, args } => {
698 self.compile_hitl_expr(*kind, args)?;
699 }
700 Node::SelectExpr {
701 cases,
702 timeout,
703 default_body,
704 } => {
705 self.compile_select_expr(cases, timeout, default_body)?;
706 }
707 Node::Spread(_) => {
708 return Err(CompileError {
709 message: "spread (...) can only be used inside list literals, dict literals, or function call arguments".into(),
710 line: self.line,
711 });
712 }
713 Node::AttributedDecl { attributes, inner } => {
714 self.compile_attributed_decl(attributes, inner)?;
715 }
716 Node::OrPattern(_) => {
717 return Err(CompileError {
718 message: "or-pattern (|) can only appear as a match arm pattern".into(),
719 line: self.line,
720 });
721 }
722 }
723 Ok(())
724 }
725}