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