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