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