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