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