Skip to main content

harn_vm/
compiler.rs

1use harn_lexer::StringSegment;
2use harn_parser::{BindingPattern, Node, SNode, TypedParam};
3
4use crate::chunk::{Chunk, CompiledFunction, Constant, Op};
5
6/// Compile error.
7#[derive(Debug)]
8pub struct CompileError {
9    pub message: String,
10    pub line: u32,
11}
12
13impl std::fmt::Display for CompileError {
14    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
15        write!(f, "Compile error at line {}: {}", self.line, self.message)
16    }
17}
18
19impl std::error::Error for CompileError {}
20
21/// Tracks loop context for break/continue compilation.
22struct LoopContext {
23    /// Offset of the loop start (for continue).
24    start_offset: usize,
25    /// Positions of break jumps that need patching to the loop end.
26    break_patches: Vec<usize>,
27    /// True if this is a for-in loop (has an iterator to clean up on break).
28    has_iterator: bool,
29    /// Number of exception handlers active at loop entry.
30    handler_depth: usize,
31    /// Number of pending finally bodies at loop entry.
32    finally_depth: usize,
33}
34
35/// Compiles an AST into bytecode.
36pub struct Compiler {
37    chunk: Chunk,
38    line: u32,
39    column: u32,
40    /// Track enum type names so PropertyAccess on them can produce EnumVariant.
41    enum_names: std::collections::HashSet<String>,
42    /// Track interface names → method names for runtime enforcement.
43    interface_methods: std::collections::HashMap<String, Vec<String>>,
44    /// Stack of active loop contexts for break/continue.
45    loop_stack: Vec<LoopContext>,
46    /// Current depth of exception handlers (for cleanup on break/continue).
47    handler_depth: usize,
48    /// Stack of pending finally bodies for return/break/continue handling.
49    finally_bodies: Vec<Vec<SNode>>,
50    /// Counter for unique temp variable names.
51    temp_counter: usize,
52}
53
54impl Compiler {
55    pub fn new() -> Self {
56        Self {
57            chunk: Chunk::new(),
58            line: 1,
59            column: 1,
60            enum_names: std::collections::HashSet::new(),
61            interface_methods: std::collections::HashMap::new(),
62            loop_stack: Vec::new(),
63            handler_depth: 0,
64            finally_bodies: Vec::new(),
65            temp_counter: 0,
66        }
67    }
68
69    /// Compile a program (list of top-level nodes) into a Chunk.
70    /// Finds the entry pipeline and compiles its body, including inherited bodies.
71    pub fn compile(mut self, program: &[SNode]) -> Result<Chunk, CompileError> {
72        // Pre-scan the entire program for enum declarations (including inside pipelines)
73        // so we can recognize EnumName.Variant as enum construction.
74        Self::collect_enum_names(program, &mut self.enum_names);
75        // Built-in Result enum is always available
76        self.enum_names.insert("Result".to_string());
77        Self::collect_interface_methods(program, &mut self.interface_methods);
78
79        // Compile all top-level imports first
80        for sn in program {
81            match &sn.node {
82                Node::ImportDecl { .. } | Node::SelectiveImport { .. } => {
83                    self.compile_node(sn)?;
84                }
85                _ => {}
86            }
87        }
88
89        // Find entry pipeline
90        let main = program
91            .iter()
92            .find(|sn| matches!(&sn.node, Node::Pipeline { name, .. } if name == "default"))
93            .or_else(|| {
94                program
95                    .iter()
96                    .find(|sn| matches!(&sn.node, Node::Pipeline { .. }))
97            });
98
99        if let Some(sn) = main {
100            if let Node::Pipeline { body, extends, .. } = &sn.node {
101                // If this pipeline extends another, compile the parent chain first
102                if let Some(parent_name) = extends {
103                    self.compile_parent_pipeline(program, parent_name)?;
104                }
105                self.compile_block(body)?;
106            }
107        } else {
108            // No pipeline found — compile all top-level statements as an
109            // implicit entry point (script mode).
110            let top_level: Vec<&SNode> = program
111                .iter()
112                .filter(|sn| {
113                    !matches!(
114                        &sn.node,
115                        Node::ImportDecl { .. } | Node::SelectiveImport { .. }
116                    )
117                })
118                .collect();
119            for sn in &top_level {
120                self.compile_node(sn)?;
121                if Self::produces_value(&sn.node) {
122                    self.chunk.emit(Op::Pop, self.line);
123                }
124            }
125        }
126
127        self.chunk.emit(Op::Nil, self.line);
128        self.chunk.emit(Op::Return, self.line);
129        Ok(self.chunk)
130    }
131
132    /// Compile a specific named pipeline (for test runners).
133    pub fn compile_named(
134        mut self,
135        program: &[SNode],
136        pipeline_name: &str,
137    ) -> Result<Chunk, CompileError> {
138        Self::collect_enum_names(program, &mut self.enum_names);
139        Self::collect_interface_methods(program, &mut self.interface_methods);
140
141        for sn in program {
142            if matches!(
143                &sn.node,
144                Node::ImportDecl { .. } | Node::SelectiveImport { .. }
145            ) {
146                self.compile_node(sn)?;
147            }
148        }
149
150        let target = program
151            .iter()
152            .find(|sn| matches!(&sn.node, Node::Pipeline { name, .. } if name == pipeline_name));
153
154        if let Some(sn) = target {
155            if let Node::Pipeline { body, extends, .. } = &sn.node {
156                if let Some(parent_name) = extends {
157                    self.compile_parent_pipeline(program, parent_name)?;
158                }
159                self.compile_block(body)?;
160            }
161        }
162
163        self.chunk.emit(Op::Nil, self.line);
164        self.chunk.emit(Op::Return, self.line);
165        Ok(self.chunk)
166    }
167
168    /// Recursively compile parent pipeline bodies (for extends).
169    fn compile_parent_pipeline(
170        &mut self,
171        program: &[SNode],
172        parent_name: &str,
173    ) -> Result<(), CompileError> {
174        let parent = program
175            .iter()
176            .find(|sn| matches!(&sn.node, Node::Pipeline { name, .. } if name == parent_name));
177        if let Some(sn) = parent {
178            if let Node::Pipeline { body, extends, .. } = &sn.node {
179                // Recurse if this parent also extends another
180                if let Some(grandparent) = extends {
181                    self.compile_parent_pipeline(program, grandparent)?;
182                }
183                // Compile parent body - pop all statement values
184                for stmt in body {
185                    self.compile_node(stmt)?;
186                    if Self::produces_value(&stmt.node) {
187                        self.chunk.emit(Op::Pop, self.line);
188                    }
189                }
190            }
191        }
192        Ok(())
193    }
194
195    /// Emit bytecode preamble for default parameter values.
196    /// For each param with a default at index i, emits:
197    ///   GetArgc; PushInt (i+1); GreaterEqual; JumpIfTrue <skip>;
198    ///   [compile default expr]; DefLet param_name; <skip>:
199    fn emit_default_preamble(&mut self, params: &[TypedParam]) -> Result<(), CompileError> {
200        for (i, param) in params.iter().enumerate() {
201            if let Some(default_expr) = &param.default_value {
202                self.chunk.emit(Op::GetArgc, self.line);
203                let threshold_idx = self.chunk.add_constant(Constant::Int((i + 1) as i64));
204                self.chunk.emit_u16(Op::Constant, threshold_idx, self.line);
205                // argc >= (i+1) means arg was provided
206                self.chunk.emit(Op::GreaterEqual, self.line);
207                let skip_jump = self.chunk.emit_jump(Op::JumpIfTrue, self.line);
208                // Pop the boolean from JumpIfTrue (it doesn't pop)
209                self.chunk.emit(Op::Pop, self.line);
210                // Compile the default expression
211                self.compile_node(default_expr)?;
212                let name_idx = self
213                    .chunk
214                    .add_constant(Constant::String(param.name.clone()));
215                self.chunk.emit_u16(Op::DefLet, name_idx, self.line);
216                let end_jump = self.chunk.emit_jump(Op::Jump, self.line);
217                self.chunk.patch_jump(skip_jump);
218                // Pop the boolean left by JumpIfTrue on the true path
219                self.chunk.emit(Op::Pop, self.line);
220                self.chunk.patch_jump(end_jump);
221            }
222        }
223        Ok(())
224    }
225
226    /// Emit runtime type checks for parameters with type annotations.
227    /// For each param with a type annotation, emits CheckType(var_name, type_name)
228    /// or calls __assert_shape for shape types.
229    fn emit_type_checks(&mut self, params: &[TypedParam]) {
230        for param in params {
231            if let Some(type_expr) = &param.type_expr {
232                // Handle shape types via __assert_shape builtin call
233                if let harn_parser::TypeExpr::Shape(fields) = type_expr {
234                    let spec = Self::shape_to_spec_string(fields);
235                    // Emit: __assert_shape(param_value, param_name, spec)
236                    let fn_idx = self
237                        .chunk
238                        .add_constant(Constant::String("__assert_shape".into()));
239                    self.chunk.emit_u16(Op::Constant, fn_idx, self.line);
240                    let var_idx = self
241                        .chunk
242                        .add_constant(Constant::String(param.name.clone()));
243                    self.chunk.emit_u16(Op::GetVar, var_idx, self.line);
244                    let name_idx = self
245                        .chunk
246                        .add_constant(Constant::String(param.name.clone()));
247                    self.chunk.emit_u16(Op::Constant, name_idx, self.line);
248                    let spec_idx = self.chunk.add_constant(Constant::String(spec));
249                    self.chunk.emit_u16(Op::Constant, spec_idx, self.line);
250                    self.chunk.emit_u8(Op::Call, 3, self.line);
251                    self.chunk.emit(Op::Pop, self.line);
252                    continue;
253                }
254
255                // Check if this is an interface type — emit __assert_interface
256                if let harn_parser::TypeExpr::Named(name) = type_expr {
257                    if let Some(methods) = self.interface_methods.get(name) {
258                        let fn_idx = self
259                            .chunk
260                            .add_constant(Constant::String("__assert_interface".into()));
261                        self.chunk.emit_u16(Op::Constant, fn_idx, self.line);
262                        let var_idx = self
263                            .chunk
264                            .add_constant(Constant::String(param.name.clone()));
265                        self.chunk.emit_u16(Op::GetVar, var_idx, self.line);
266                        let name_idx = self
267                            .chunk
268                            .add_constant(Constant::String(param.name.clone()));
269                        self.chunk.emit_u16(Op::Constant, name_idx, self.line);
270                        let iface_idx = self.chunk.add_constant(Constant::String(name.clone()));
271                        self.chunk.emit_u16(Op::Constant, iface_idx, self.line);
272                        let methods_str = methods.join(",");
273                        let methods_idx = self.chunk.add_constant(Constant::String(methods_str));
274                        self.chunk.emit_u16(Op::Constant, methods_idx, self.line);
275                        self.chunk.emit_u8(Op::Call, 4, self.line);
276                        self.chunk.emit(Op::Pop, self.line);
277                        continue;
278                    }
279                }
280
281                let type_name = Self::type_expr_to_runtime_name(type_expr);
282                if let Some(type_name) = type_name {
283                    let var_idx = self
284                        .chunk
285                        .add_constant(Constant::String(param.name.clone()));
286                    let type_idx = self.chunk.add_constant(Constant::String(type_name));
287                    self.chunk.emit_u16(Op::CheckType, var_idx, self.line);
288                    // Emit the type name index as two extra bytes
289                    let hi = (type_idx >> 8) as u8;
290                    let lo = type_idx as u8;
291                    self.chunk.code.push(hi);
292                    self.chunk.code.push(lo);
293                }
294            }
295        }
296    }
297
298    /// Serialize a list of ShapeFields into a spec string for __assert_shape.
299    /// Format: `name:string,age:int,active:?bool,addr:{city:string,zip:string}`
300    fn shape_to_spec_string(fields: &[harn_parser::ShapeField]) -> String {
301        fields
302            .iter()
303            .map(|f| {
304                let opt = if f.optional { "?" } else { "" };
305                let type_str = Self::type_expr_to_spec(&f.type_expr);
306                format!("{}:{}{}", f.name, opt, type_str)
307            })
308            .collect::<Vec<_>>()
309            .join(",")
310    }
311
312    /// Convert a TypeExpr into a spec string fragment for shape validation.
313    fn type_expr_to_spec(type_expr: &harn_parser::TypeExpr) -> String {
314        match type_expr {
315            harn_parser::TypeExpr::Named(name) => name.clone(),
316            harn_parser::TypeExpr::Shape(fields) => {
317                let inner = Self::shape_to_spec_string(fields);
318                format!("{{{}}}", inner)
319            }
320            harn_parser::TypeExpr::List(_) => "list".to_string(),
321            harn_parser::TypeExpr::DictType(_, _) => "dict".to_string(),
322            harn_parser::TypeExpr::Union(members) => {
323                // Serialize union as "type1|type2|type3" for runtime validation
324                members
325                    .iter()
326                    .map(Self::type_expr_to_spec)
327                    .collect::<Vec<_>>()
328                    .join("|")
329            }
330            harn_parser::TypeExpr::FnType { .. } => "closure".to_string(),
331        }
332    }
333
334    /// Convert a TypeExpr to a runtime type name string for CheckType.
335    fn type_expr_to_runtime_name(type_expr: &harn_parser::TypeExpr) -> Option<String> {
336        match type_expr {
337            harn_parser::TypeExpr::Named(name) => match name.as_str() {
338                "int" | "float" | "string" | "bool" | "list" | "dict" | "set" | "nil"
339                | "closure" => Some(name.clone()),
340                _ => None, // Unknown types are not checked at runtime
341            },
342            _ => None, // Union types, shapes, etc. are not checked at runtime
343        }
344    }
345
346    /// Emit the extra u16 type name index after a TryCatchSetup jump.
347    fn emit_type_name_extra(&mut self, type_name_idx: u16) {
348        let hi = (type_name_idx >> 8) as u8;
349        let lo = type_name_idx as u8;
350        self.chunk.code.push(hi);
351        self.chunk.code.push(lo);
352        self.chunk.lines.push(self.line);
353        self.chunk.columns.push(self.column);
354        self.chunk.lines.push(self.line);
355        self.chunk.columns.push(self.column);
356    }
357
358    /// Compile a try/catch body block (produces a value on the stack).
359    fn compile_try_body(&mut self, body: &[SNode]) -> Result<(), CompileError> {
360        if body.is_empty() {
361            self.chunk.emit(Op::Nil, self.line);
362        } else {
363            self.compile_block(body)?;
364            if !Self::produces_value(&body.last().unwrap().node) {
365                self.chunk.emit(Op::Nil, self.line);
366            }
367        }
368        Ok(())
369    }
370
371    /// Compile catch error binding (error value is on stack from handler).
372    fn compile_catch_binding(&mut self, error_var: &Option<String>) -> Result<(), CompileError> {
373        if let Some(var_name) = error_var {
374            let idx = self.chunk.add_constant(Constant::String(var_name.clone()));
375            // Catch bindings share the surrounding runtime scope with sibling
376            // try/catch blocks, so use a mutable slot to allow repeated
377            // `catch e { ... }` bindings in the same enclosing block.
378            self.chunk.emit_u16(Op::DefVar, idx, self.line);
379        } else {
380            self.chunk.emit(Op::Pop, self.line);
381        }
382        Ok(())
383    }
384
385    /// Compile finally body inline, discarding its result value.
386    fn compile_finally_inline(&mut self, finally_body: &[SNode]) -> Result<(), CompileError> {
387        if !finally_body.is_empty() {
388            self.compile_block(finally_body)?;
389            // Finally body's value is discarded — only the try/catch value matters
390            if Self::produces_value(&finally_body.last().unwrap().node) {
391                self.chunk.emit(Op::Pop, self.line);
392            }
393        }
394        Ok(())
395    }
396
397    /// Compile rethrow pattern: save error to temp var, run finally, re-throw.
398    fn compile_rethrow_with_finally(&mut self, finally_body: &[SNode]) -> Result<(), CompileError> {
399        // Error is on the stack from the handler
400        self.temp_counter += 1;
401        let temp_name = format!("__finally_err_{}__", self.temp_counter);
402        let err_idx = self.chunk.add_constant(Constant::String(temp_name.clone()));
403        self.chunk.emit_u16(Op::DefVar, err_idx, self.line);
404        self.compile_finally_inline(finally_body)?;
405        let get_idx = self.chunk.add_constant(Constant::String(temp_name));
406        self.chunk.emit_u16(Op::GetVar, get_idx, self.line);
407        self.chunk.emit(Op::Throw, self.line);
408        Ok(())
409    }
410
411    fn compile_block(&mut self, stmts: &[SNode]) -> Result<(), CompileError> {
412        for (i, snode) in stmts.iter().enumerate() {
413            self.compile_node(snode)?;
414            let is_last = i == stmts.len() - 1;
415            if is_last {
416                // If the last statement doesn't produce a value, push nil
417                // so the block always leaves exactly one value on the stack.
418                if !Self::produces_value(&snode.node) {
419                    self.chunk.emit(Op::Nil, self.line);
420                }
421            } else {
422                // Only pop if the statement leaves a value on the stack
423                if Self::produces_value(&snode.node) {
424                    self.chunk.emit(Op::Pop, self.line);
425                }
426            }
427        }
428        Ok(())
429    }
430
431    fn compile_node(&mut self, snode: &SNode) -> Result<(), CompileError> {
432        self.line = snode.span.line as u32;
433        self.column = snode.span.column as u32;
434        self.chunk.set_column(self.column);
435        match &snode.node {
436            Node::IntLiteral(n) => {
437                let idx = self.chunk.add_constant(Constant::Int(*n));
438                self.chunk.emit_u16(Op::Constant, idx, self.line);
439            }
440            Node::FloatLiteral(n) => {
441                let idx = self.chunk.add_constant(Constant::Float(*n));
442                self.chunk.emit_u16(Op::Constant, idx, self.line);
443            }
444            Node::StringLiteral(s) => {
445                let idx = self.chunk.add_constant(Constant::String(s.clone()));
446                self.chunk.emit_u16(Op::Constant, idx, self.line);
447            }
448            Node::BoolLiteral(true) => self.chunk.emit(Op::True, self.line),
449            Node::BoolLiteral(false) => self.chunk.emit(Op::False, self.line),
450            Node::NilLiteral => self.chunk.emit(Op::Nil, self.line),
451            Node::DurationLiteral(ms) => {
452                let idx = self.chunk.add_constant(Constant::Duration(*ms));
453                self.chunk.emit_u16(Op::Constant, idx, self.line);
454            }
455
456            Node::Identifier(name) => {
457                let idx = self.chunk.add_constant(Constant::String(name.clone()));
458                self.chunk.emit_u16(Op::GetVar, idx, self.line);
459            }
460
461            Node::LetBinding { pattern, value, .. } => {
462                self.compile_node(value)?;
463                self.compile_destructuring(pattern, false)?;
464            }
465
466            Node::VarBinding { pattern, value, .. } => {
467                self.compile_node(value)?;
468                self.compile_destructuring(pattern, true)?;
469            }
470
471            Node::Assignment {
472                target, value, op, ..
473            } => {
474                if let Node::Identifier(name) = &target.node {
475                    let idx = self.chunk.add_constant(Constant::String(name.clone()));
476                    if let Some(op) = op {
477                        self.chunk.emit_u16(Op::GetVar, idx, self.line);
478                        self.compile_node(value)?;
479                        self.emit_compound_op(op)?;
480                        self.chunk.emit_u16(Op::SetVar, idx, self.line);
481                    } else {
482                        self.compile_node(value)?;
483                        self.chunk.emit_u16(Op::SetVar, idx, self.line);
484                    }
485                } else if let Node::PropertyAccess { object, property } = &target.node {
486                    // obj.field = value → SetProperty
487                    if let Some(var_name) = self.root_var_name(object) {
488                        let var_idx = self.chunk.add_constant(Constant::String(var_name.clone()));
489                        let prop_idx = self.chunk.add_constant(Constant::String(property.clone()));
490                        if let Some(op) = op {
491                            // compound: obj.field += value
492                            self.compile_node(target)?; // push current obj.field
493                            self.compile_node(value)?;
494                            self.emit_compound_op(op)?;
495                        } else {
496                            self.compile_node(value)?;
497                        }
498                        // Stack: [new_value]
499                        // SetProperty reads var_idx from env, sets prop, writes back
500                        self.chunk.emit_u16(Op::SetProperty, prop_idx, self.line);
501                        // Encode the variable name index as a second u16
502                        let hi = (var_idx >> 8) as u8;
503                        let lo = var_idx as u8;
504                        self.chunk.code.push(hi);
505                        self.chunk.code.push(lo);
506                        self.chunk.lines.push(self.line);
507                        self.chunk.columns.push(self.column);
508                        self.chunk.lines.push(self.line);
509                        self.chunk.columns.push(self.column);
510                    }
511                } else if let Node::SubscriptAccess { object, index } = &target.node {
512                    // obj[idx] = value → SetSubscript
513                    if let Some(var_name) = self.root_var_name(object) {
514                        let var_idx = self.chunk.add_constant(Constant::String(var_name.clone()));
515                        if let Some(op) = op {
516                            self.compile_node(target)?;
517                            self.compile_node(value)?;
518                            self.emit_compound_op(op)?;
519                        } else {
520                            self.compile_node(value)?;
521                        }
522                        self.compile_node(index)?;
523                        self.chunk.emit_u16(Op::SetSubscript, var_idx, self.line);
524                    }
525                }
526            }
527
528            Node::BinaryOp { op, left, right } => {
529                // Short-circuit operators
530                match op.as_str() {
531                    "&&" => {
532                        self.compile_node(left)?;
533                        let jump = self.chunk.emit_jump(Op::JumpIfFalse, self.line);
534                        self.chunk.emit(Op::Pop, self.line);
535                        self.compile_node(right)?;
536                        self.chunk.patch_jump(jump);
537                        // Normalize to bool
538                        self.chunk.emit(Op::Not, self.line);
539                        self.chunk.emit(Op::Not, self.line);
540                        return Ok(());
541                    }
542                    "||" => {
543                        self.compile_node(left)?;
544                        let jump = self.chunk.emit_jump(Op::JumpIfTrue, self.line);
545                        self.chunk.emit(Op::Pop, self.line);
546                        self.compile_node(right)?;
547                        self.chunk.patch_jump(jump);
548                        self.chunk.emit(Op::Not, self.line);
549                        self.chunk.emit(Op::Not, self.line);
550                        return Ok(());
551                    }
552                    "??" => {
553                        self.compile_node(left)?;
554                        self.chunk.emit(Op::Dup, self.line);
555                        // Check if nil: push nil, compare
556                        self.chunk.emit(Op::Nil, self.line);
557                        self.chunk.emit(Op::NotEqual, self.line);
558                        let jump = self.chunk.emit_jump(Op::JumpIfTrue, self.line);
559                        self.chunk.emit(Op::Pop, self.line); // pop the not-equal result
560                        self.chunk.emit(Op::Pop, self.line); // pop the nil value
561                        self.compile_node(right)?;
562                        let end = self.chunk.emit_jump(Op::Jump, self.line);
563                        self.chunk.patch_jump(jump);
564                        self.chunk.emit(Op::Pop, self.line); // pop the not-equal result
565                        self.chunk.patch_jump(end);
566                        return Ok(());
567                    }
568                    "|>" => {
569                        self.compile_node(left)?;
570                        // If the RHS contains `_` placeholders, desugar into a closure:
571                        //   value |> func(_, arg)  =>  value |> { __pipe -> func(__pipe, arg) }
572                        if contains_pipe_placeholder(right) {
573                            let replaced = replace_pipe_placeholder(right);
574                            let closure_node = SNode::dummy(Node::Closure {
575                                params: vec![TypedParam {
576                                    name: "__pipe".into(),
577                                    type_expr: None,
578                                    default_value: None,
579                                }],
580                                body: vec![replaced],
581                                fn_syntax: false,
582                            });
583                            self.compile_node(&closure_node)?;
584                        } else {
585                            self.compile_node(right)?;
586                        }
587                        self.chunk.emit(Op::Pipe, self.line);
588                        return Ok(());
589                    }
590                    _ => {}
591                }
592
593                self.compile_node(left)?;
594                self.compile_node(right)?;
595                match op.as_str() {
596                    "+" => self.chunk.emit(Op::Add, self.line),
597                    "-" => self.chunk.emit(Op::Sub, self.line),
598                    "*" => self.chunk.emit(Op::Mul, self.line),
599                    "/" => self.chunk.emit(Op::Div, self.line),
600                    "%" => self.chunk.emit(Op::Mod, self.line),
601                    "==" => self.chunk.emit(Op::Equal, self.line),
602                    "!=" => self.chunk.emit(Op::NotEqual, self.line),
603                    "<" => self.chunk.emit(Op::Less, self.line),
604                    ">" => self.chunk.emit(Op::Greater, self.line),
605                    "<=" => self.chunk.emit(Op::LessEqual, self.line),
606                    ">=" => self.chunk.emit(Op::GreaterEqual, self.line),
607                    "in" => self.chunk.emit(Op::Contains, self.line),
608                    "not_in" => {
609                        self.chunk.emit(Op::Contains, self.line);
610                        self.chunk.emit(Op::Not, self.line);
611                    }
612                    _ => {
613                        return Err(CompileError {
614                            message: format!("Unknown operator: {op}"),
615                            line: self.line,
616                        })
617                    }
618                }
619            }
620
621            Node::UnaryOp { op, operand } => {
622                self.compile_node(operand)?;
623                match op.as_str() {
624                    "-" => self.chunk.emit(Op::Negate, self.line),
625                    "!" => self.chunk.emit(Op::Not, self.line),
626                    _ => {}
627                }
628            }
629
630            Node::Ternary {
631                condition,
632                true_expr,
633                false_expr,
634            } => {
635                self.compile_node(condition)?;
636                let else_jump = self.chunk.emit_jump(Op::JumpIfFalse, self.line);
637                self.chunk.emit(Op::Pop, self.line);
638                self.compile_node(true_expr)?;
639                let end_jump = self.chunk.emit_jump(Op::Jump, self.line);
640                self.chunk.patch_jump(else_jump);
641                self.chunk.emit(Op::Pop, self.line);
642                self.compile_node(false_expr)?;
643                self.chunk.patch_jump(end_jump);
644            }
645
646            Node::FunctionCall { name, args } => {
647                let has_spread = args.iter().any(|a| matches!(&a.node, Node::Spread(_)));
648                // Push function name as string constant
649                let name_idx = self.chunk.add_constant(Constant::String(name.clone()));
650                self.chunk.emit_u16(Op::Constant, name_idx, self.line);
651
652                if has_spread {
653                    // Build the args into a single list using the flush-and-concat
654                    // pattern (same as ListLiteral with spreads).
655                    self.chunk.emit_u16(Op::BuildList, 0, self.line);
656                    let mut pending = 0u16;
657                    for arg in args {
658                        if let Node::Spread(inner) = &arg.node {
659                            if pending > 0 {
660                                self.chunk.emit_u16(Op::BuildList, pending, self.line);
661                                self.chunk.emit(Op::Add, self.line);
662                                pending = 0;
663                            }
664                            self.compile_node(inner)?;
665                            self.chunk.emit(Op::Dup, self.line);
666                            let assert_idx = self
667                                .chunk
668                                .add_constant(Constant::String("__assert_list".into()));
669                            self.chunk.emit_u16(Op::Constant, assert_idx, self.line);
670                            self.chunk.emit(Op::Swap, self.line);
671                            self.chunk.emit_u8(Op::Call, 1, self.line);
672                            self.chunk.emit(Op::Pop, self.line);
673                            self.chunk.emit(Op::Add, self.line);
674                        } else {
675                            self.compile_node(arg)?;
676                            pending += 1;
677                        }
678                    }
679                    if pending > 0 {
680                        self.chunk.emit_u16(Op::BuildList, pending, self.line);
681                        self.chunk.emit(Op::Add, self.line);
682                    }
683                    self.chunk.emit(Op::CallSpread, self.line);
684                } else {
685                    // Push arguments normally
686                    for arg in args {
687                        self.compile_node(arg)?;
688                    }
689                    self.chunk.emit_u8(Op::Call, args.len() as u8, self.line);
690                }
691            }
692
693            Node::MethodCall {
694                object,
695                method,
696                args,
697            } => {
698                // Check if this is an enum variant construction with args: EnumName.Variant(args)
699                if let Node::Identifier(name) = &object.node {
700                    if self.enum_names.contains(name) {
701                        // Compile args, then BuildEnum
702                        for arg in args {
703                            self.compile_node(arg)?;
704                        }
705                        let enum_idx = self.chunk.add_constant(Constant::String(name.clone()));
706                        let var_idx = self.chunk.add_constant(Constant::String(method.clone()));
707                        self.chunk.emit_u16(Op::BuildEnum, enum_idx, self.line);
708                        let hi = (var_idx >> 8) as u8;
709                        let lo = var_idx as u8;
710                        self.chunk.code.push(hi);
711                        self.chunk.code.push(lo);
712                        self.chunk.lines.push(self.line);
713                        self.chunk.columns.push(self.column);
714                        self.chunk.lines.push(self.line);
715                        self.chunk.columns.push(self.column);
716                        let fc = args.len() as u16;
717                        let fhi = (fc >> 8) as u8;
718                        let flo = fc as u8;
719                        self.chunk.code.push(fhi);
720                        self.chunk.code.push(flo);
721                        self.chunk.lines.push(self.line);
722                        self.chunk.columns.push(self.column);
723                        self.chunk.lines.push(self.line);
724                        self.chunk.columns.push(self.column);
725                        return Ok(());
726                    }
727                }
728                let has_spread = args.iter().any(|a| matches!(&a.node, Node::Spread(_)));
729                self.compile_node(object)?;
730                let name_idx = self.chunk.add_constant(Constant::String(method.clone()));
731                if has_spread {
732                    // Build args into a single list (same pattern as FunctionCall spread)
733                    self.chunk.emit_u16(Op::BuildList, 0, self.line);
734                    let mut pending = 0u16;
735                    for arg in args {
736                        if let Node::Spread(inner) = &arg.node {
737                            if pending > 0 {
738                                self.chunk.emit_u16(Op::BuildList, pending, self.line);
739                                self.chunk.emit(Op::Add, self.line);
740                                pending = 0;
741                            }
742                            self.compile_node(inner)?;
743                            self.chunk.emit(Op::Dup, self.line);
744                            let assert_idx = self
745                                .chunk
746                                .add_constant(Constant::String("__assert_list".into()));
747                            self.chunk.emit_u16(Op::Constant, assert_idx, self.line);
748                            self.chunk.emit(Op::Swap, self.line);
749                            self.chunk.emit_u8(Op::Call, 1, self.line);
750                            self.chunk.emit(Op::Pop, self.line);
751                            self.chunk.emit(Op::Add, self.line);
752                        } else {
753                            self.compile_node(arg)?;
754                            pending += 1;
755                        }
756                    }
757                    if pending > 0 {
758                        self.chunk.emit_u16(Op::BuildList, pending, self.line);
759                        self.chunk.emit(Op::Add, self.line);
760                    }
761                    self.chunk
762                        .emit_u16(Op::MethodCallSpread, name_idx, self.line);
763                } else {
764                    for arg in args {
765                        self.compile_node(arg)?;
766                    }
767                    self.chunk
768                        .emit_method_call(name_idx, args.len() as u8, self.line);
769                }
770            }
771
772            Node::OptionalMethodCall {
773                object,
774                method,
775                args,
776            } => {
777                self.compile_node(object)?;
778                for arg in args {
779                    self.compile_node(arg)?;
780                }
781                let name_idx = self.chunk.add_constant(Constant::String(method.clone()));
782                self.chunk
783                    .emit_method_call_opt(name_idx, args.len() as u8, self.line);
784            }
785
786            Node::PropertyAccess { object, property } => {
787                // Check if this is an enum variant construction: EnumName.Variant
788                if let Node::Identifier(name) = &object.node {
789                    if self.enum_names.contains(name) {
790                        // Emit BuildEnum with 0 fields
791                        let enum_idx = self.chunk.add_constant(Constant::String(name.clone()));
792                        let var_idx = self.chunk.add_constant(Constant::String(property.clone()));
793                        self.chunk.emit_u16(Op::BuildEnum, enum_idx, self.line);
794                        let hi = (var_idx >> 8) as u8;
795                        let lo = var_idx as u8;
796                        self.chunk.code.push(hi);
797                        self.chunk.code.push(lo);
798                        self.chunk.lines.push(self.line);
799                        self.chunk.columns.push(self.column);
800                        self.chunk.lines.push(self.line);
801                        self.chunk.columns.push(self.column);
802                        // 0 fields
803                        self.chunk.code.push(0);
804                        self.chunk.code.push(0);
805                        self.chunk.lines.push(self.line);
806                        self.chunk.columns.push(self.column);
807                        self.chunk.lines.push(self.line);
808                        self.chunk.columns.push(self.column);
809                        return Ok(());
810                    }
811                }
812                self.compile_node(object)?;
813                let idx = self.chunk.add_constant(Constant::String(property.clone()));
814                self.chunk.emit_u16(Op::GetProperty, idx, self.line);
815            }
816
817            Node::OptionalPropertyAccess { object, property } => {
818                self.compile_node(object)?;
819                let idx = self.chunk.add_constant(Constant::String(property.clone()));
820                self.chunk.emit_u16(Op::GetPropertyOpt, idx, self.line);
821            }
822
823            Node::SubscriptAccess { object, index } => {
824                self.compile_node(object)?;
825                self.compile_node(index)?;
826                self.chunk.emit(Op::Subscript, self.line);
827            }
828
829            Node::SliceAccess { object, start, end } => {
830                self.compile_node(object)?;
831                if let Some(s) = start {
832                    self.compile_node(s)?;
833                } else {
834                    self.chunk.emit(Op::Nil, self.line);
835                }
836                if let Some(e) = end {
837                    self.compile_node(e)?;
838                } else {
839                    self.chunk.emit(Op::Nil, self.line);
840                }
841                self.chunk.emit(Op::Slice, self.line);
842            }
843
844            Node::IfElse {
845                condition,
846                then_body,
847                else_body,
848            } => {
849                self.compile_node(condition)?;
850                let else_jump = self.chunk.emit_jump(Op::JumpIfFalse, self.line);
851                self.chunk.emit(Op::Pop, self.line);
852                self.compile_block(then_body)?;
853                if let Some(else_body) = else_body {
854                    let end_jump = self.chunk.emit_jump(Op::Jump, self.line);
855                    self.chunk.patch_jump(else_jump);
856                    self.chunk.emit(Op::Pop, self.line);
857                    self.compile_block(else_body)?;
858                    self.chunk.patch_jump(end_jump);
859                } else {
860                    self.chunk.patch_jump(else_jump);
861                    self.chunk.emit(Op::Pop, self.line);
862                    self.chunk.emit(Op::Nil, self.line);
863                }
864            }
865
866            Node::WhileLoop { condition, body } => {
867                let loop_start = self.chunk.current_offset();
868                self.loop_stack.push(LoopContext {
869                    start_offset: loop_start,
870                    break_patches: Vec::new(),
871                    has_iterator: false,
872                    handler_depth: self.handler_depth,
873                    finally_depth: self.finally_bodies.len(),
874                });
875                self.compile_node(condition)?;
876                let exit_jump = self.chunk.emit_jump(Op::JumpIfFalse, self.line);
877                self.chunk.emit(Op::Pop, self.line); // pop condition
878                                                     // Compile body statements, popping all results
879                for sn in body {
880                    self.compile_node(sn)?;
881                    if Self::produces_value(&sn.node) {
882                        self.chunk.emit(Op::Pop, self.line);
883                    }
884                }
885                // Jump back to condition
886                self.chunk.emit_u16(Op::Jump, loop_start as u16, self.line);
887                self.chunk.patch_jump(exit_jump);
888                self.chunk.emit(Op::Pop, self.line); // pop condition
889                                                     // Patch all break jumps to here
890                let ctx = self.loop_stack.pop().unwrap();
891                for patch_pos in ctx.break_patches {
892                    self.chunk.patch_jump(patch_pos);
893                }
894                self.chunk.emit(Op::Nil, self.line);
895            }
896
897            Node::ForIn {
898                pattern,
899                iterable,
900                body,
901            } => {
902                // Compile iterable
903                self.compile_node(iterable)?;
904                // Initialize iterator
905                self.chunk.emit(Op::IterInit, self.line);
906                let loop_start = self.chunk.current_offset();
907                self.loop_stack.push(LoopContext {
908                    start_offset: loop_start,
909                    break_patches: Vec::new(),
910                    has_iterator: true,
911                    handler_depth: self.handler_depth,
912                    finally_depth: self.finally_bodies.len(),
913                });
914                // Try to get next item — jumps to end if exhausted
915                let exit_jump_pos = self.chunk.emit_jump(Op::IterNext, self.line);
916                // Define loop variable(s) with current item (item is on stack from IterNext)
917                self.compile_destructuring(pattern, true)?;
918                // Compile body statements, popping all results
919                for sn in body {
920                    self.compile_node(sn)?;
921                    if Self::produces_value(&sn.node) {
922                        self.chunk.emit(Op::Pop, self.line);
923                    }
924                }
925                // Loop back
926                self.chunk.emit_u16(Op::Jump, loop_start as u16, self.line);
927                self.chunk.patch_jump(exit_jump_pos);
928                // Patch all break jumps to here
929                let ctx = self.loop_stack.pop().unwrap();
930                for patch_pos in ctx.break_patches {
931                    self.chunk.patch_jump(patch_pos);
932                }
933                // Push nil as result (iterator state was consumed)
934                self.chunk.emit(Op::Nil, self.line);
935            }
936
937            Node::ReturnStmt { value } => {
938                let has_pending_finally = !self.finally_bodies.is_empty();
939
940                if has_pending_finally {
941                    // Inside try-finally: compile value, save to temp,
942                    // run pending finallys, restore value, then return.
943                    if let Some(val) = value {
944                        self.compile_node(val)?;
945                    } else {
946                        self.chunk.emit(Op::Nil, self.line);
947                    }
948                    self.temp_counter += 1;
949                    let temp_name = format!("__return_val_{}__", self.temp_counter);
950                    let save_idx = self.chunk.add_constant(Constant::String(temp_name.clone()));
951                    self.chunk.emit_u16(Op::DefVar, save_idx, self.line);
952                    // Emit all pending finallys (innermost first = reverse order)
953                    let finallys: Vec<_> = self.finally_bodies.iter().rev().cloned().collect();
954                    for fb in &finallys {
955                        self.compile_finally_inline(fb)?;
956                    }
957                    let restore_idx = self.chunk.add_constant(Constant::String(temp_name));
958                    self.chunk.emit_u16(Op::GetVar, restore_idx, self.line);
959                    self.chunk.emit(Op::Return, self.line);
960                } else {
961                    // No pending finally — original behavior with tail call optimization
962                    if let Some(val) = value {
963                        if let Node::FunctionCall { name, args } = &val.node {
964                            let name_idx = self.chunk.add_constant(Constant::String(name.clone()));
965                            self.chunk.emit_u16(Op::Constant, name_idx, self.line);
966                            for arg in args {
967                                self.compile_node(arg)?;
968                            }
969                            self.chunk
970                                .emit_u8(Op::TailCall, args.len() as u8, self.line);
971                        } else if let Node::BinaryOp { op, left, right } = &val.node {
972                            if op == "|>" {
973                                self.compile_node(left)?;
974                                self.compile_node(right)?;
975                                self.chunk.emit(Op::Swap, self.line);
976                                self.chunk.emit_u8(Op::TailCall, 1, self.line);
977                            } else {
978                                self.compile_node(val)?;
979                            }
980                        } else {
981                            self.compile_node(val)?;
982                        }
983                    } else {
984                        self.chunk.emit(Op::Nil, self.line);
985                    }
986                    self.chunk.emit(Op::Return, self.line);
987                }
988            }
989
990            Node::BreakStmt => {
991                if self.loop_stack.is_empty() {
992                    return Err(CompileError {
993                        message: "break outside of loop".to_string(),
994                        line: self.line,
995                    });
996                }
997                // Copy values out to avoid borrow conflict
998                let ctx = self.loop_stack.last().unwrap();
999                let finally_depth = ctx.finally_depth;
1000                let handler_depth = ctx.handler_depth;
1001                let has_iterator = ctx.has_iterator;
1002                // Pop exception handlers that were pushed inside the loop
1003                for _ in handler_depth..self.handler_depth {
1004                    self.chunk.emit(Op::PopHandler, self.line);
1005                }
1006                // Emit pending finallys that are inside the loop
1007                if self.finally_bodies.len() > finally_depth {
1008                    let finallys: Vec<_> = self.finally_bodies[finally_depth..]
1009                        .iter()
1010                        .rev()
1011                        .cloned()
1012                        .collect();
1013                    for fb in &finallys {
1014                        self.compile_finally_inline(fb)?;
1015                    }
1016                }
1017                if has_iterator {
1018                    self.chunk.emit(Op::PopIterator, self.line);
1019                }
1020                let patch = self.chunk.emit_jump(Op::Jump, self.line);
1021                self.loop_stack
1022                    .last_mut()
1023                    .unwrap()
1024                    .break_patches
1025                    .push(patch);
1026            }
1027
1028            Node::ContinueStmt => {
1029                if self.loop_stack.is_empty() {
1030                    return Err(CompileError {
1031                        message: "continue outside of loop".to_string(),
1032                        line: self.line,
1033                    });
1034                }
1035                let ctx = self.loop_stack.last().unwrap();
1036                let finally_depth = ctx.finally_depth;
1037                let handler_depth = ctx.handler_depth;
1038                let loop_start = ctx.start_offset;
1039                for _ in handler_depth..self.handler_depth {
1040                    self.chunk.emit(Op::PopHandler, self.line);
1041                }
1042                if self.finally_bodies.len() > finally_depth {
1043                    let finallys: Vec<_> = self.finally_bodies[finally_depth..]
1044                        .iter()
1045                        .rev()
1046                        .cloned()
1047                        .collect();
1048                    for fb in &finallys {
1049                        self.compile_finally_inline(fb)?;
1050                    }
1051                }
1052                self.chunk.emit_u16(Op::Jump, loop_start as u16, self.line);
1053            }
1054
1055            Node::ListLiteral(elements) => {
1056                let has_spread = elements.iter().any(|e| matches!(&e.node, Node::Spread(_)));
1057                if !has_spread {
1058                    for el in elements {
1059                        self.compile_node(el)?;
1060                    }
1061                    self.chunk
1062                        .emit_u16(Op::BuildList, elements.len() as u16, self.line);
1063                } else {
1064                    // Build with spreads: accumulate segments into lists and concat
1065                    // Start with empty list
1066                    self.chunk.emit_u16(Op::BuildList, 0, self.line);
1067                    let mut pending = 0u16;
1068                    for el in elements {
1069                        if let Node::Spread(inner) = &el.node {
1070                            // First, build list from pending non-spread elements
1071                            if pending > 0 {
1072                                self.chunk.emit_u16(Op::BuildList, pending, self.line);
1073                                // Concat accumulated + pending segment
1074                                self.chunk.emit(Op::Add, self.line);
1075                                pending = 0;
1076                            }
1077                            // Concat with the spread expression (with type check)
1078                            self.compile_node(inner)?;
1079                            self.chunk.emit(Op::Dup, self.line);
1080                            let assert_idx = self
1081                                .chunk
1082                                .add_constant(Constant::String("__assert_list".into()));
1083                            self.chunk.emit_u16(Op::Constant, assert_idx, self.line);
1084                            self.chunk.emit(Op::Swap, self.line);
1085                            self.chunk.emit_u8(Op::Call, 1, self.line);
1086                            self.chunk.emit(Op::Pop, self.line);
1087                            self.chunk.emit(Op::Add, self.line);
1088                        } else {
1089                            self.compile_node(el)?;
1090                            pending += 1;
1091                        }
1092                    }
1093                    if pending > 0 {
1094                        self.chunk.emit_u16(Op::BuildList, pending, self.line);
1095                        self.chunk.emit(Op::Add, self.line);
1096                    }
1097                }
1098            }
1099
1100            Node::DictLiteral(entries) => {
1101                let has_spread = entries
1102                    .iter()
1103                    .any(|e| matches!(&e.value.node, Node::Spread(_)));
1104                if !has_spread {
1105                    for entry in entries {
1106                        self.compile_node(&entry.key)?;
1107                        self.compile_node(&entry.value)?;
1108                    }
1109                    self.chunk
1110                        .emit_u16(Op::BuildDict, entries.len() as u16, self.line);
1111                } else {
1112                    // Build with spreads: use empty dict + Add for merging
1113                    self.chunk.emit_u16(Op::BuildDict, 0, self.line);
1114                    let mut pending = 0u16;
1115                    for entry in entries {
1116                        if let Node::Spread(inner) = &entry.value.node {
1117                            // Flush pending entries
1118                            if pending > 0 {
1119                                self.chunk.emit_u16(Op::BuildDict, pending, self.line);
1120                                self.chunk.emit(Op::Add, self.line);
1121                                pending = 0;
1122                            }
1123                            // Merge spread dict via Add (with type check)
1124                            self.compile_node(inner)?;
1125                            self.chunk.emit(Op::Dup, self.line);
1126                            let assert_idx = self
1127                                .chunk
1128                                .add_constant(Constant::String("__assert_dict".into()));
1129                            self.chunk.emit_u16(Op::Constant, assert_idx, self.line);
1130                            self.chunk.emit(Op::Swap, self.line);
1131                            self.chunk.emit_u8(Op::Call, 1, self.line);
1132                            self.chunk.emit(Op::Pop, self.line);
1133                            self.chunk.emit(Op::Add, self.line);
1134                        } else {
1135                            self.compile_node(&entry.key)?;
1136                            self.compile_node(&entry.value)?;
1137                            pending += 1;
1138                        }
1139                    }
1140                    if pending > 0 {
1141                        self.chunk.emit_u16(Op::BuildDict, pending, self.line);
1142                        self.chunk.emit(Op::Add, self.line);
1143                    }
1144                }
1145            }
1146
1147            Node::InterpolatedString(segments) => {
1148                let mut part_count = 0u16;
1149                for seg in segments {
1150                    match seg {
1151                        StringSegment::Literal(s) => {
1152                            let idx = self.chunk.add_constant(Constant::String(s.clone()));
1153                            self.chunk.emit_u16(Op::Constant, idx, self.line);
1154                            part_count += 1;
1155                        }
1156                        StringSegment::Expression(expr_str) => {
1157                            // Parse and compile the embedded expression
1158                            let mut lexer = harn_lexer::Lexer::new(expr_str);
1159                            if let Ok(tokens) = lexer.tokenize() {
1160                                let mut parser = harn_parser::Parser::new(tokens);
1161                                if let Ok(snode) = parser.parse_single_expression() {
1162                                    self.compile_node(&snode)?;
1163                                    // Convert result to string for concatenation
1164                                    let to_str = self
1165                                        .chunk
1166                                        .add_constant(Constant::String("to_string".into()));
1167                                    self.chunk.emit_u16(Op::Constant, to_str, self.line);
1168                                    self.chunk.emit(Op::Swap, self.line);
1169                                    self.chunk.emit_u8(Op::Call, 1, self.line);
1170                                    part_count += 1;
1171                                } else {
1172                                    // Fallback: treat as literal string
1173                                    let idx =
1174                                        self.chunk.add_constant(Constant::String(expr_str.clone()));
1175                                    self.chunk.emit_u16(Op::Constant, idx, self.line);
1176                                    part_count += 1;
1177                                }
1178                            }
1179                        }
1180                    }
1181                }
1182                if part_count > 1 {
1183                    self.chunk.emit_u16(Op::Concat, part_count, self.line);
1184                }
1185            }
1186
1187            Node::FnDecl {
1188                name, params, body, ..
1189            } => {
1190                // Compile function body into a separate chunk
1191                let mut fn_compiler = Compiler::new();
1192                fn_compiler.enum_names = self.enum_names.clone();
1193                fn_compiler.emit_default_preamble(params)?;
1194                fn_compiler.emit_type_checks(params);
1195                let is_gen = body_contains_yield(body);
1196                fn_compiler.compile_block(body)?;
1197                fn_compiler.chunk.emit(Op::Nil, self.line);
1198                fn_compiler.chunk.emit(Op::Return, self.line);
1199
1200                let func = CompiledFunction {
1201                    name: name.clone(),
1202                    params: TypedParam::names(params),
1203                    default_start: TypedParam::default_start(params),
1204                    chunk: fn_compiler.chunk,
1205                    is_generator: is_gen,
1206                };
1207                let fn_idx = self.chunk.functions.len();
1208                self.chunk.functions.push(func);
1209
1210                self.chunk.emit_u16(Op::Closure, fn_idx as u16, self.line);
1211                let name_idx = self.chunk.add_constant(Constant::String(name.clone()));
1212                self.chunk.emit_u16(Op::DefLet, name_idx, self.line);
1213            }
1214
1215            Node::Closure { params, body, .. } => {
1216                let mut fn_compiler = Compiler::new();
1217                fn_compiler.enum_names = self.enum_names.clone();
1218                fn_compiler.emit_default_preamble(params)?;
1219                fn_compiler.emit_type_checks(params);
1220                let is_gen = body_contains_yield(body);
1221                fn_compiler.compile_block(body)?;
1222                // If block didn't end with return, the last value is on the stack
1223                fn_compiler.chunk.emit(Op::Return, self.line);
1224
1225                let func = CompiledFunction {
1226                    name: "<closure>".to_string(),
1227                    params: TypedParam::names(params),
1228                    default_start: TypedParam::default_start(params),
1229                    chunk: fn_compiler.chunk,
1230                    is_generator: is_gen,
1231                };
1232                let fn_idx = self.chunk.functions.len();
1233                self.chunk.functions.push(func);
1234
1235                self.chunk.emit_u16(Op::Closure, fn_idx as u16, self.line);
1236            }
1237
1238            Node::ThrowStmt { value } => {
1239                self.compile_node(value)?;
1240                self.chunk.emit(Op::Throw, self.line);
1241            }
1242
1243            Node::MatchExpr { value, arms } => {
1244                self.compile_node(value)?;
1245                let mut end_jumps = Vec::new();
1246                for arm in arms {
1247                    match &arm.pattern.node {
1248                        // Wildcard `_` — always matches
1249                        Node::Identifier(name) if name == "_" => {
1250                            self.chunk.emit(Op::Pop, self.line); // pop match value
1251                            self.compile_match_body(&arm.body)?;
1252                            end_jumps.push(self.chunk.emit_jump(Op::Jump, self.line));
1253                        }
1254                        // Enum destructuring: EnumConstruct pattern
1255                        Node::EnumConstruct {
1256                            enum_name,
1257                            variant,
1258                            args: pat_args,
1259                        } => {
1260                            // Check if the match value is this enum variant
1261                            self.chunk.emit(Op::Dup, self.line);
1262                            let en_idx =
1263                                self.chunk.add_constant(Constant::String(enum_name.clone()));
1264                            let vn_idx = self.chunk.add_constant(Constant::String(variant.clone()));
1265                            self.chunk.emit_u16(Op::MatchEnum, en_idx, self.line);
1266                            let hi = (vn_idx >> 8) as u8;
1267                            let lo = vn_idx as u8;
1268                            self.chunk.code.push(hi);
1269                            self.chunk.code.push(lo);
1270                            self.chunk.lines.push(self.line);
1271                            self.chunk.columns.push(self.column);
1272                            self.chunk.lines.push(self.line);
1273                            self.chunk.columns.push(self.column);
1274                            // Stack: [match_value, bool]
1275                            let skip = self.chunk.emit_jump(Op::JumpIfFalse, self.line);
1276                            self.chunk.emit(Op::Pop, self.line); // pop bool
1277
1278                            // Destructure: bind field variables from the enum's fields
1279                            // The match value is still on the stack; we need to extract fields
1280                            for (i, pat_arg) in pat_args.iter().enumerate() {
1281                                if let Node::Identifier(binding_name) = &pat_arg.node {
1282                                    // Dup the match value, get .fields, subscript [i]
1283                                    self.chunk.emit(Op::Dup, self.line);
1284                                    let fields_idx = self
1285                                        .chunk
1286                                        .add_constant(Constant::String("fields".to_string()));
1287                                    self.chunk.emit_u16(Op::GetProperty, fields_idx, self.line);
1288                                    let idx_const =
1289                                        self.chunk.add_constant(Constant::Int(i as i64));
1290                                    self.chunk.emit_u16(Op::Constant, idx_const, self.line);
1291                                    self.chunk.emit(Op::Subscript, self.line);
1292                                    let name_idx = self
1293                                        .chunk
1294                                        .add_constant(Constant::String(binding_name.clone()));
1295                                    self.chunk.emit_u16(Op::DefLet, name_idx, self.line);
1296                                }
1297                            }
1298
1299                            self.chunk.emit(Op::Pop, self.line); // pop match value
1300                            self.compile_match_body(&arm.body)?;
1301                            end_jumps.push(self.chunk.emit_jump(Op::Jump, self.line));
1302                            self.chunk.patch_jump(skip);
1303                            self.chunk.emit(Op::Pop, self.line); // pop bool
1304                        }
1305                        // Enum variant without args: PropertyAccess(EnumName, Variant)
1306                        Node::PropertyAccess { object, property } if matches!(&object.node, Node::Identifier(n) if self.enum_names.contains(n)) =>
1307                        {
1308                            let enum_name = if let Node::Identifier(n) = &object.node {
1309                                n.clone()
1310                            } else {
1311                                unreachable!()
1312                            };
1313                            self.chunk.emit(Op::Dup, self.line);
1314                            let en_idx = self.chunk.add_constant(Constant::String(enum_name));
1315                            let vn_idx =
1316                                self.chunk.add_constant(Constant::String(property.clone()));
1317                            self.chunk.emit_u16(Op::MatchEnum, en_idx, self.line);
1318                            let hi = (vn_idx >> 8) as u8;
1319                            let lo = vn_idx as u8;
1320                            self.chunk.code.push(hi);
1321                            self.chunk.code.push(lo);
1322                            self.chunk.lines.push(self.line);
1323                            self.chunk.columns.push(self.column);
1324                            self.chunk.lines.push(self.line);
1325                            self.chunk.columns.push(self.column);
1326                            let skip = self.chunk.emit_jump(Op::JumpIfFalse, self.line);
1327                            self.chunk.emit(Op::Pop, self.line); // pop bool
1328                            self.chunk.emit(Op::Pop, self.line); // pop match value
1329                            self.compile_match_body(&arm.body)?;
1330                            end_jumps.push(self.chunk.emit_jump(Op::Jump, self.line));
1331                            self.chunk.patch_jump(skip);
1332                            self.chunk.emit(Op::Pop, self.line); // pop bool
1333                        }
1334                        // Enum destructuring via MethodCall: EnumName.Variant(bindings...)
1335                        // Parser produces MethodCall for EnumName.Variant(x) patterns
1336                        Node::MethodCall {
1337                            object,
1338                            method,
1339                            args: pat_args,
1340                        } if matches!(&object.node, Node::Identifier(n) if self.enum_names.contains(n)) =>
1341                        {
1342                            let enum_name = if let Node::Identifier(n) = &object.node {
1343                                n.clone()
1344                            } else {
1345                                unreachable!()
1346                            };
1347                            // Check if the match value is this enum variant
1348                            self.chunk.emit(Op::Dup, self.line);
1349                            let en_idx = self.chunk.add_constant(Constant::String(enum_name));
1350                            let vn_idx = self.chunk.add_constant(Constant::String(method.clone()));
1351                            self.chunk.emit_u16(Op::MatchEnum, en_idx, self.line);
1352                            let hi = (vn_idx >> 8) as u8;
1353                            let lo = vn_idx as u8;
1354                            self.chunk.code.push(hi);
1355                            self.chunk.code.push(lo);
1356                            self.chunk.lines.push(self.line);
1357                            self.chunk.columns.push(self.column);
1358                            self.chunk.lines.push(self.line);
1359                            self.chunk.columns.push(self.column);
1360                            let skip = self.chunk.emit_jump(Op::JumpIfFalse, self.line);
1361                            self.chunk.emit(Op::Pop, self.line); // pop bool
1362
1363                            // Destructure: bind field variables
1364                            for (i, pat_arg) in pat_args.iter().enumerate() {
1365                                if let Node::Identifier(binding_name) = &pat_arg.node {
1366                                    self.chunk.emit(Op::Dup, self.line);
1367                                    let fields_idx = self
1368                                        .chunk
1369                                        .add_constant(Constant::String("fields".to_string()));
1370                                    self.chunk.emit_u16(Op::GetProperty, fields_idx, self.line);
1371                                    let idx_const =
1372                                        self.chunk.add_constant(Constant::Int(i as i64));
1373                                    self.chunk.emit_u16(Op::Constant, idx_const, self.line);
1374                                    self.chunk.emit(Op::Subscript, self.line);
1375                                    let name_idx = self
1376                                        .chunk
1377                                        .add_constant(Constant::String(binding_name.clone()));
1378                                    self.chunk.emit_u16(Op::DefLet, name_idx, self.line);
1379                                }
1380                            }
1381
1382                            self.chunk.emit(Op::Pop, self.line); // pop match value
1383                            self.compile_match_body(&arm.body)?;
1384                            end_jumps.push(self.chunk.emit_jump(Op::Jump, self.line));
1385                            self.chunk.patch_jump(skip);
1386                            self.chunk.emit(Op::Pop, self.line); // pop bool
1387                        }
1388                        // Binding pattern: bare identifier (not a literal)
1389                        Node::Identifier(name) => {
1390                            // Bind the match value to this name, always matches
1391                            self.chunk.emit(Op::Dup, self.line); // dup for binding
1392                            let name_idx = self.chunk.add_constant(Constant::String(name.clone()));
1393                            self.chunk.emit_u16(Op::DefLet, name_idx, self.line);
1394                            self.chunk.emit(Op::Pop, self.line); // pop match value
1395                            self.compile_match_body(&arm.body)?;
1396                            end_jumps.push(self.chunk.emit_jump(Op::Jump, self.line));
1397                        }
1398                        // Dict pattern: {key: literal, key: binding, ...}
1399                        Node::DictLiteral(entries)
1400                            if entries
1401                                .iter()
1402                                .all(|e| matches!(&e.key.node, Node::StringLiteral(_))) =>
1403                        {
1404                            // Check type is dict: dup, call type_of, compare "dict"
1405                            self.chunk.emit(Op::Dup, self.line);
1406                            let typeof_idx =
1407                                self.chunk.add_constant(Constant::String("type_of".into()));
1408                            self.chunk.emit_u16(Op::Constant, typeof_idx, self.line);
1409                            self.chunk.emit(Op::Swap, self.line);
1410                            self.chunk.emit_u8(Op::Call, 1, self.line);
1411                            let dict_str = self.chunk.add_constant(Constant::String("dict".into()));
1412                            self.chunk.emit_u16(Op::Constant, dict_str, self.line);
1413                            self.chunk.emit(Op::Equal, self.line);
1414                            let skip_type = self.chunk.emit_jump(Op::JumpIfFalse, self.line);
1415                            self.chunk.emit(Op::Pop, self.line); // pop bool
1416
1417                            // Check literal constraints
1418                            let mut constraint_skips = Vec::new();
1419                            let mut bindings = Vec::new();
1420                            for entry in entries {
1421                                if let Node::StringLiteral(key) = &entry.key.node {
1422                                    match &entry.value.node {
1423                                        // Literal value → constraint: dict[key] == value
1424                                        Node::StringLiteral(_)
1425                                        | Node::IntLiteral(_)
1426                                        | Node::FloatLiteral(_)
1427                                        | Node::BoolLiteral(_)
1428                                        | Node::NilLiteral => {
1429                                            self.chunk.emit(Op::Dup, self.line);
1430                                            let key_idx = self
1431                                                .chunk
1432                                                .add_constant(Constant::String(key.clone()));
1433                                            self.chunk.emit_u16(Op::Constant, key_idx, self.line);
1434                                            self.chunk.emit(Op::Subscript, self.line);
1435                                            self.compile_node(&entry.value)?;
1436                                            self.chunk.emit(Op::Equal, self.line);
1437                                            let skip =
1438                                                self.chunk.emit_jump(Op::JumpIfFalse, self.line);
1439                                            self.chunk.emit(Op::Pop, self.line); // pop bool
1440                                            constraint_skips.push(skip);
1441                                        }
1442                                        // Identifier → binding: bind dict[key] to variable
1443                                        Node::Identifier(binding) => {
1444                                            bindings.push((key.clone(), binding.clone()));
1445                                        }
1446                                        _ => {
1447                                            // Complex expression constraint
1448                                            self.chunk.emit(Op::Dup, self.line);
1449                                            let key_idx = self
1450                                                .chunk
1451                                                .add_constant(Constant::String(key.clone()));
1452                                            self.chunk.emit_u16(Op::Constant, key_idx, self.line);
1453                                            self.chunk.emit(Op::Subscript, self.line);
1454                                            self.compile_node(&entry.value)?;
1455                                            self.chunk.emit(Op::Equal, self.line);
1456                                            let skip =
1457                                                self.chunk.emit_jump(Op::JumpIfFalse, self.line);
1458                                            self.chunk.emit(Op::Pop, self.line);
1459                                            constraint_skips.push(skip);
1460                                        }
1461                                    }
1462                                }
1463                            }
1464
1465                            // All constraints passed — emit bindings
1466                            for (key, binding) in &bindings {
1467                                self.chunk.emit(Op::Dup, self.line);
1468                                let key_idx =
1469                                    self.chunk.add_constant(Constant::String(key.clone()));
1470                                self.chunk.emit_u16(Op::Constant, key_idx, self.line);
1471                                self.chunk.emit(Op::Subscript, self.line);
1472                                let name_idx =
1473                                    self.chunk.add_constant(Constant::String(binding.clone()));
1474                                self.chunk.emit_u16(Op::DefLet, name_idx, self.line);
1475                            }
1476
1477                            self.chunk.emit(Op::Pop, self.line); // pop match value
1478                            self.compile_match_body(&arm.body)?;
1479                            end_jumps.push(self.chunk.emit_jump(Op::Jump, self.line));
1480
1481                            // All failures jump here: pop the false bool, leave match_value
1482                            let fail_target = self.chunk.code.len();
1483                            self.chunk.emit(Op::Pop, self.line); // pop bool
1484                                                                 // Patch all failure jumps to the shared cleanup point
1485                            for skip in constraint_skips {
1486                                self.chunk.patch_jump_to(skip, fail_target);
1487                            }
1488                            self.chunk.patch_jump_to(skip_type, fail_target);
1489                        }
1490                        // List pattern: [literal, binding, ...]
1491                        Node::ListLiteral(elements) => {
1492                            // Check type is list: dup, call type_of, compare "list"
1493                            self.chunk.emit(Op::Dup, self.line);
1494                            let typeof_idx =
1495                                self.chunk.add_constant(Constant::String("type_of".into()));
1496                            self.chunk.emit_u16(Op::Constant, typeof_idx, self.line);
1497                            self.chunk.emit(Op::Swap, self.line);
1498                            self.chunk.emit_u8(Op::Call, 1, self.line);
1499                            let list_str = self.chunk.add_constant(Constant::String("list".into()));
1500                            self.chunk.emit_u16(Op::Constant, list_str, self.line);
1501                            self.chunk.emit(Op::Equal, self.line);
1502                            let skip_type = self.chunk.emit_jump(Op::JumpIfFalse, self.line);
1503                            self.chunk.emit(Op::Pop, self.line); // pop bool
1504
1505                            // Check length: dup, call len, compare >= elements.len()
1506                            self.chunk.emit(Op::Dup, self.line);
1507                            let len_idx = self.chunk.add_constant(Constant::String("len".into()));
1508                            self.chunk.emit_u16(Op::Constant, len_idx, self.line);
1509                            self.chunk.emit(Op::Swap, self.line);
1510                            self.chunk.emit_u8(Op::Call, 1, self.line);
1511                            let count = self
1512                                .chunk
1513                                .add_constant(Constant::Int(elements.len() as i64));
1514                            self.chunk.emit_u16(Op::Constant, count, self.line);
1515                            self.chunk.emit(Op::GreaterEqual, self.line);
1516                            let skip_len = self.chunk.emit_jump(Op::JumpIfFalse, self.line);
1517                            self.chunk.emit(Op::Pop, self.line); // pop bool
1518
1519                            // Check literal constraints and collect bindings
1520                            let mut constraint_skips = Vec::new();
1521                            let mut bindings = Vec::new();
1522                            for (i, elem) in elements.iter().enumerate() {
1523                                match &elem.node {
1524                                    Node::Identifier(name) if name != "_" => {
1525                                        bindings.push((i, name.clone()));
1526                                    }
1527                                    Node::Identifier(_) => {} // wildcard _
1528                                    // Literal constraint
1529                                    _ => {
1530                                        self.chunk.emit(Op::Dup, self.line);
1531                                        let idx_const =
1532                                            self.chunk.add_constant(Constant::Int(i as i64));
1533                                        self.chunk.emit_u16(Op::Constant, idx_const, self.line);
1534                                        self.chunk.emit(Op::Subscript, self.line);
1535                                        self.compile_node(elem)?;
1536                                        self.chunk.emit(Op::Equal, self.line);
1537                                        let skip = self.chunk.emit_jump(Op::JumpIfFalse, self.line);
1538                                        self.chunk.emit(Op::Pop, self.line);
1539                                        constraint_skips.push(skip);
1540                                    }
1541                                }
1542                            }
1543
1544                            // Emit bindings
1545                            for (i, name) in &bindings {
1546                                self.chunk.emit(Op::Dup, self.line);
1547                                let idx_const = self.chunk.add_constant(Constant::Int(*i as i64));
1548                                self.chunk.emit_u16(Op::Constant, idx_const, self.line);
1549                                self.chunk.emit(Op::Subscript, self.line);
1550                                let name_idx =
1551                                    self.chunk.add_constant(Constant::String(name.clone()));
1552                                self.chunk.emit_u16(Op::DefLet, name_idx, self.line);
1553                            }
1554
1555                            self.chunk.emit(Op::Pop, self.line); // pop match value
1556                            self.compile_match_body(&arm.body)?;
1557                            end_jumps.push(self.chunk.emit_jump(Op::Jump, self.line));
1558
1559                            // All failures jump here: pop the false bool
1560                            let fail_target = self.chunk.code.len();
1561                            self.chunk.emit(Op::Pop, self.line); // pop bool
1562                            for skip in constraint_skips {
1563                                self.chunk.patch_jump_to(skip, fail_target);
1564                            }
1565                            self.chunk.patch_jump_to(skip_len, fail_target);
1566                            self.chunk.patch_jump_to(skip_type, fail_target);
1567                        }
1568                        // Literal/expression pattern — compare with Equal
1569                        _ => {
1570                            self.chunk.emit(Op::Dup, self.line);
1571                            self.compile_node(&arm.pattern)?;
1572                            self.chunk.emit(Op::Equal, self.line);
1573                            let skip = self.chunk.emit_jump(Op::JumpIfFalse, self.line);
1574                            self.chunk.emit(Op::Pop, self.line); // pop bool
1575                            self.chunk.emit(Op::Pop, self.line); // pop match value
1576                            self.compile_match_body(&arm.body)?;
1577                            end_jumps.push(self.chunk.emit_jump(Op::Jump, self.line));
1578                            self.chunk.patch_jump(skip);
1579                            self.chunk.emit(Op::Pop, self.line); // pop bool
1580                        }
1581                    }
1582                }
1583                // No match — pop value, push nil
1584                self.chunk.emit(Op::Pop, self.line);
1585                self.chunk.emit(Op::Nil, self.line);
1586                for j in end_jumps {
1587                    self.chunk.patch_jump(j);
1588                }
1589            }
1590
1591            Node::RangeExpr {
1592                start,
1593                end,
1594                inclusive,
1595            } => {
1596                // Compile as __range__(start, end, inclusive_bool) builtin call
1597                let name_idx = self
1598                    .chunk
1599                    .add_constant(Constant::String("__range__".to_string()));
1600                self.chunk.emit_u16(Op::Constant, name_idx, self.line);
1601                self.compile_node(start)?;
1602                self.compile_node(end)?;
1603                if *inclusive {
1604                    self.chunk.emit(Op::True, self.line);
1605                } else {
1606                    self.chunk.emit(Op::False, self.line);
1607                }
1608                self.chunk.emit_u8(Op::Call, 3, self.line);
1609            }
1610
1611            Node::GuardStmt {
1612                condition,
1613                else_body,
1614            } => {
1615                // guard condition else { body }
1616                // Compile condition; if truthy, skip else_body
1617                self.compile_node(condition)?;
1618                let skip_jump = self.chunk.emit_jump(Op::JumpIfTrue, self.line);
1619                self.chunk.emit(Op::Pop, self.line); // pop condition
1620                                                     // Compile else_body
1621                self.compile_block(else_body)?;
1622                // Pop result of else_body (guard is a statement, not expression)
1623                if !else_body.is_empty() && Self::produces_value(&else_body.last().unwrap().node) {
1624                    self.chunk.emit(Op::Pop, self.line);
1625                }
1626                let end_jump = self.chunk.emit_jump(Op::Jump, self.line);
1627                self.chunk.patch_jump(skip_jump);
1628                self.chunk.emit(Op::Pop, self.line); // pop condition
1629                self.chunk.patch_jump(end_jump);
1630                self.chunk.emit(Op::Nil, self.line);
1631            }
1632
1633            Node::Block(stmts) => {
1634                if stmts.is_empty() {
1635                    self.chunk.emit(Op::Nil, self.line);
1636                } else {
1637                    self.compile_block(stmts)?;
1638                }
1639            }
1640
1641            Node::DeadlineBlock { duration, body } => {
1642                self.compile_node(duration)?;
1643                self.chunk.emit(Op::DeadlineSetup, self.line);
1644                if body.is_empty() {
1645                    self.chunk.emit(Op::Nil, self.line);
1646                } else {
1647                    self.compile_block(body)?;
1648                }
1649                self.chunk.emit(Op::DeadlineEnd, self.line);
1650            }
1651
1652            Node::MutexBlock { body } => {
1653                // v1: single-threaded, just compile the body
1654                if body.is_empty() {
1655                    self.chunk.emit(Op::Nil, self.line);
1656                } else {
1657                    // Compile body, but pop intermediate values and push nil at the end.
1658                    // The body typically contains statements (assignments) that don't produce values.
1659                    for sn in body {
1660                        self.compile_node(sn)?;
1661                        if Self::produces_value(&sn.node) {
1662                            self.chunk.emit(Op::Pop, self.line);
1663                        }
1664                    }
1665                    self.chunk.emit(Op::Nil, self.line);
1666                }
1667            }
1668
1669            Node::YieldExpr { value } => {
1670                if let Some(val) = value {
1671                    self.compile_node(val)?;
1672                } else {
1673                    self.chunk.emit(Op::Nil, self.line);
1674                }
1675                self.chunk.emit(Op::Yield, self.line);
1676            }
1677
1678            Node::AskExpr { fields } => {
1679                // Compile as a dict literal and call llm_call builtin
1680                // For v1, just build the dict (llm_call requires async)
1681                for entry in fields {
1682                    self.compile_node(&entry.key)?;
1683                    self.compile_node(&entry.value)?;
1684                }
1685                self.chunk
1686                    .emit_u16(Op::BuildDict, fields.len() as u16, self.line);
1687            }
1688
1689            Node::EnumConstruct {
1690                enum_name,
1691                variant,
1692                args,
1693            } => {
1694                // Push field values onto the stack, then BuildEnum
1695                for arg in args {
1696                    self.compile_node(arg)?;
1697                }
1698                let enum_idx = self.chunk.add_constant(Constant::String(enum_name.clone()));
1699                let var_idx = self.chunk.add_constant(Constant::String(variant.clone()));
1700                // BuildEnum: enum_name_idx, variant_idx, field_count
1701                self.chunk.emit_u16(Op::BuildEnum, enum_idx, self.line);
1702                let hi = (var_idx >> 8) as u8;
1703                let lo = var_idx as u8;
1704                self.chunk.code.push(hi);
1705                self.chunk.code.push(lo);
1706                self.chunk.lines.push(self.line);
1707                self.chunk.columns.push(self.column);
1708                self.chunk.lines.push(self.line);
1709                self.chunk.columns.push(self.column);
1710                let fc = args.len() as u16;
1711                let fhi = (fc >> 8) as u8;
1712                let flo = fc as u8;
1713                self.chunk.code.push(fhi);
1714                self.chunk.code.push(flo);
1715                self.chunk.lines.push(self.line);
1716                self.chunk.columns.push(self.column);
1717                self.chunk.lines.push(self.line);
1718                self.chunk.columns.push(self.column);
1719            }
1720
1721            Node::StructConstruct {
1722                struct_name,
1723                fields,
1724            } => {
1725                // Build as a dict with a __struct__ key for metadata
1726                let struct_key = self
1727                    .chunk
1728                    .add_constant(Constant::String("__struct__".to_string()));
1729                let struct_val = self
1730                    .chunk
1731                    .add_constant(Constant::String(struct_name.clone()));
1732                self.chunk.emit_u16(Op::Constant, struct_key, self.line);
1733                self.chunk.emit_u16(Op::Constant, struct_val, self.line);
1734
1735                for entry in fields {
1736                    self.compile_node(&entry.key)?;
1737                    self.compile_node(&entry.value)?;
1738                }
1739                self.chunk
1740                    .emit_u16(Op::BuildDict, (fields.len() + 1) as u16, self.line);
1741            }
1742
1743            Node::ImportDecl { path } => {
1744                let idx = self.chunk.add_constant(Constant::String(path.clone()));
1745                self.chunk.emit_u16(Op::Import, idx, self.line);
1746            }
1747
1748            Node::SelectiveImport { names, path } => {
1749                let path_idx = self.chunk.add_constant(Constant::String(path.clone()));
1750                let names_str = names.join(",");
1751                let names_idx = self.chunk.add_constant(Constant::String(names_str));
1752                self.chunk
1753                    .emit_u16(Op::SelectiveImport, path_idx, self.line);
1754                let hi = (names_idx >> 8) as u8;
1755                let lo = names_idx as u8;
1756                self.chunk.code.push(hi);
1757                self.chunk.code.push(lo);
1758                self.chunk.lines.push(self.line);
1759                self.chunk.columns.push(self.column);
1760                self.chunk.lines.push(self.line);
1761                self.chunk.columns.push(self.column);
1762            }
1763
1764            Node::TryOperator { operand } => {
1765                self.compile_node(operand)?;
1766                self.chunk.emit(Op::TryUnwrap, self.line);
1767            }
1768
1769            Node::ImplBlock { type_name, methods } => {
1770                // Compile each method as a closure and store in __impl_TypeName dict.
1771                // Build key-value pairs on stack, then BuildDict.
1772                for method_sn in methods {
1773                    if let Node::FnDecl {
1774                        name, params, body, ..
1775                    } = &method_sn.node
1776                    {
1777                        // Method name key
1778                        let key_idx = self.chunk.add_constant(Constant::String(name.clone()));
1779                        self.chunk.emit_u16(Op::Constant, key_idx, self.line);
1780
1781                        // Compile method body as closure
1782                        let mut fn_compiler = Compiler::new();
1783                        fn_compiler.enum_names = self.enum_names.clone();
1784                        fn_compiler.emit_default_preamble(params)?;
1785                        fn_compiler.emit_type_checks(params);
1786                        fn_compiler.compile_block(body)?;
1787                        fn_compiler.chunk.emit(Op::Nil, self.line);
1788                        fn_compiler.chunk.emit(Op::Return, self.line);
1789
1790                        let func = CompiledFunction {
1791                            name: format!("{}.{}", type_name, name),
1792                            params: TypedParam::names(params),
1793                            default_start: TypedParam::default_start(params),
1794                            chunk: fn_compiler.chunk,
1795                            is_generator: false,
1796                        };
1797                        let fn_idx = self.chunk.functions.len();
1798                        self.chunk.functions.push(func);
1799                        self.chunk.emit_u16(Op::Closure, fn_idx as u16, self.line);
1800                    }
1801                }
1802                let method_count = methods
1803                    .iter()
1804                    .filter(|m| matches!(m.node, Node::FnDecl { .. }))
1805                    .count();
1806                self.chunk
1807                    .emit_u16(Op::BuildDict, method_count as u16, self.line);
1808                let impl_name = format!("__impl_{}", type_name);
1809                let name_idx = self.chunk.add_constant(Constant::String(impl_name));
1810                self.chunk.emit_u16(Op::DefLet, name_idx, self.line);
1811            }
1812
1813            Node::StructDecl { name, .. } => {
1814                // Compile a constructor function: StructName({field: val, ...}) -> StructInstance
1815                let mut fn_compiler = Compiler::new();
1816                fn_compiler.enum_names = self.enum_names.clone();
1817                let params = vec![TypedParam::untyped("__fields")];
1818                fn_compiler.emit_default_preamble(&params)?;
1819
1820                // Call __make_struct(struct_name, fields_dict) to tag the dict
1821                let make_idx = fn_compiler
1822                    .chunk
1823                    .add_constant(Constant::String("__make_struct".into()));
1824                fn_compiler
1825                    .chunk
1826                    .emit_u16(Op::Constant, make_idx, self.line);
1827                let sname_idx = fn_compiler
1828                    .chunk
1829                    .add_constant(Constant::String(name.clone()));
1830                fn_compiler
1831                    .chunk
1832                    .emit_u16(Op::Constant, sname_idx, self.line);
1833                let fields_idx = fn_compiler
1834                    .chunk
1835                    .add_constant(Constant::String("__fields".into()));
1836                fn_compiler
1837                    .chunk
1838                    .emit_u16(Op::GetVar, fields_idx, self.line);
1839                fn_compiler.chunk.emit_u8(Op::Call, 2, self.line);
1840                fn_compiler.chunk.emit(Op::Return, self.line);
1841
1842                let func = CompiledFunction {
1843                    name: name.clone(),
1844                    params: TypedParam::names(&params),
1845                    default_start: None,
1846                    chunk: fn_compiler.chunk,
1847                    is_generator: false,
1848                };
1849                let fn_idx = self.chunk.functions.len();
1850                self.chunk.functions.push(func);
1851                self.chunk.emit_u16(Op::Closure, fn_idx as u16, self.line);
1852                let name_idx = self.chunk.add_constant(Constant::String(name.clone()));
1853                self.chunk.emit_u16(Op::DefLet, name_idx, self.line);
1854            }
1855
1856            // Declarations that only register metadata (no runtime effect needed for v1)
1857            Node::Pipeline { .. }
1858            | Node::OverrideDecl { .. }
1859            | Node::TypeDecl { .. }
1860            | Node::EnumDecl { .. }
1861            | Node::InterfaceDecl { .. } => {
1862                self.chunk.emit(Op::Nil, self.line);
1863            }
1864
1865            Node::TryCatch {
1866                body,
1867                error_var,
1868                error_type,
1869                catch_body,
1870                finally_body,
1871            } => {
1872                // Extract the type name for typed catch (e.g., "AppError")
1873                let type_name = error_type.as_ref().and_then(|te| {
1874                    if let harn_parser::TypeExpr::Named(name) = te {
1875                        Some(name.clone())
1876                    } else {
1877                        None
1878                    }
1879                });
1880
1881                let type_name_idx = if let Some(ref tn) = type_name {
1882                    self.chunk.add_constant(Constant::String(tn.clone()))
1883                } else {
1884                    self.chunk.add_constant(Constant::String(String::new()))
1885                };
1886
1887                let has_catch = !catch_body.is_empty() || error_var.is_some();
1888                let has_finally = finally_body.is_some();
1889
1890                if has_catch && has_finally {
1891                    // === try-catch-finally ===
1892                    let finally_body = finally_body.as_ref().unwrap();
1893
1894                    // Push finally body onto pending stack for return/break handling
1895                    self.finally_bodies.push(finally_body.clone());
1896
1897                    // 1. TryCatchSetup for try body
1898                    self.handler_depth += 1;
1899                    let catch_jump = self.chunk.emit_jump(Op::TryCatchSetup, self.line);
1900                    self.emit_type_name_extra(type_name_idx);
1901
1902                    // 2. Compile try body
1903                    self.compile_try_body(body)?;
1904
1905                    // 3. PopHandler + inline finally (success path)
1906                    self.handler_depth -= 1;
1907                    self.chunk.emit(Op::PopHandler, self.line);
1908                    self.compile_finally_inline(finally_body)?;
1909                    let end_jump = self.chunk.emit_jump(Op::Jump, self.line);
1910
1911                    // 4. Catch entry
1912                    self.chunk.patch_jump(catch_jump);
1913                    self.compile_catch_binding(error_var)?;
1914
1915                    // 5. Inner try around catch body (so finally runs if catch throws)
1916                    self.handler_depth += 1;
1917                    let rethrow_jump = self.chunk.emit_jump(Op::TryCatchSetup, self.line);
1918                    let empty_type = self.chunk.add_constant(Constant::String(String::new()));
1919                    self.emit_type_name_extra(empty_type);
1920
1921                    // 6. Compile catch body
1922                    self.compile_try_body(catch_body)?;
1923
1924                    // 7. PopHandler + inline finally (catch success path)
1925                    self.handler_depth -= 1;
1926                    self.chunk.emit(Op::PopHandler, self.line);
1927                    self.compile_finally_inline(finally_body)?;
1928                    let end_jump2 = self.chunk.emit_jump(Op::Jump, self.line);
1929
1930                    // 8. Rethrow handler: save error, run finally, re-throw
1931                    self.chunk.patch_jump(rethrow_jump);
1932                    self.compile_rethrow_with_finally(finally_body)?;
1933
1934                    self.chunk.patch_jump(end_jump);
1935                    self.chunk.patch_jump(end_jump2);
1936
1937                    self.finally_bodies.pop();
1938                } else if has_finally {
1939                    // === try-finally (no catch) ===
1940                    let finally_body = finally_body.as_ref().unwrap();
1941
1942                    self.finally_bodies.push(finally_body.clone());
1943
1944                    // 1. TryCatchSetup to error path
1945                    self.handler_depth += 1;
1946                    let error_jump = self.chunk.emit_jump(Op::TryCatchSetup, self.line);
1947                    let empty_type = self.chunk.add_constant(Constant::String(String::new()));
1948                    self.emit_type_name_extra(empty_type);
1949
1950                    // 2. Compile try body
1951                    self.compile_try_body(body)?;
1952
1953                    // 3. PopHandler + inline finally (success path)
1954                    self.handler_depth -= 1;
1955                    self.chunk.emit(Op::PopHandler, self.line);
1956                    self.compile_finally_inline(finally_body)?;
1957                    let end_jump = self.chunk.emit_jump(Op::Jump, self.line);
1958
1959                    // 4. Error path: save error, run finally, re-throw
1960                    self.chunk.patch_jump(error_jump);
1961                    self.compile_rethrow_with_finally(finally_body)?;
1962
1963                    self.chunk.patch_jump(end_jump);
1964
1965                    self.finally_bodies.pop();
1966                } else {
1967                    // === try-catch (no finally) — original behavior ===
1968
1969                    // 1. TryCatchSetup
1970                    self.handler_depth += 1;
1971                    let catch_jump = self.chunk.emit_jump(Op::TryCatchSetup, self.line);
1972                    self.emit_type_name_extra(type_name_idx);
1973
1974                    // 2. Compile try body
1975                    self.compile_try_body(body)?;
1976
1977                    // 3. PopHandler + jump past catch
1978                    self.handler_depth -= 1;
1979                    self.chunk.emit(Op::PopHandler, self.line);
1980                    let end_jump = self.chunk.emit_jump(Op::Jump, self.line);
1981
1982                    // 4. Catch entry
1983                    self.chunk.patch_jump(catch_jump);
1984                    self.compile_catch_binding(error_var)?;
1985
1986                    // 5. Compile catch body
1987                    self.compile_try_body(catch_body)?;
1988
1989                    // 6. Patch end
1990                    self.chunk.patch_jump(end_jump);
1991                }
1992            }
1993
1994            Node::TryExpr { body } => {
1995                // try { body } — returns Result.Ok(value) or Result.Err(error)
1996
1997                // 1. Set up try-catch handler (untyped)
1998                self.handler_depth += 1;
1999                let catch_jump = self.chunk.emit_jump(Op::TryCatchSetup, self.line);
2000                let empty_type = self.chunk.add_constant(Constant::String(String::new()));
2001                self.emit_type_name_extra(empty_type);
2002
2003                // 2. Compile try body (leaves value on stack)
2004                self.compile_try_body(body)?;
2005
2006                // 3. PopHandler (success path)
2007                self.handler_depth -= 1;
2008                self.chunk.emit(Op::PopHandler, self.line);
2009
2010                // 4. Wrap in Result.Ok: push "Ok", swap, call Ok(value)
2011                let ok_idx = self.chunk.add_constant(Constant::String("Ok".to_string()));
2012                self.chunk.emit_u16(Op::Constant, ok_idx, self.line);
2013                self.chunk.emit(Op::Swap, self.line);
2014                self.chunk.emit_u8(Op::Call, 1, self.line);
2015
2016                // 5. Jump past error handler
2017                let end_jump = self.chunk.emit_jump(Op::Jump, self.line);
2018
2019                // 6. Error handler: error value is on stack
2020                self.chunk.patch_jump(catch_jump);
2021
2022                // 7. Wrap in Result.Err: push "Err", swap, call Err(error)
2023                let err_idx = self.chunk.add_constant(Constant::String("Err".to_string()));
2024                self.chunk.emit_u16(Op::Constant, err_idx, self.line);
2025                self.chunk.emit(Op::Swap, self.line);
2026                self.chunk.emit_u8(Op::Call, 1, self.line);
2027
2028                // 8. Patch end
2029                self.chunk.patch_jump(end_jump);
2030            }
2031
2032            Node::Retry { count, body } => {
2033                // Compile count expression into a mutable counter variable
2034                self.compile_node(count)?;
2035                let counter_name = "__retry_counter__";
2036                let counter_idx = self
2037                    .chunk
2038                    .add_constant(Constant::String(counter_name.to_string()));
2039                self.chunk.emit_u16(Op::DefVar, counter_idx, self.line);
2040
2041                // Also store the last error for re-throwing
2042                self.chunk.emit(Op::Nil, self.line);
2043                let err_name = "__retry_last_error__";
2044                let err_idx = self
2045                    .chunk
2046                    .add_constant(Constant::String(err_name.to_string()));
2047                self.chunk.emit_u16(Op::DefVar, err_idx, self.line);
2048
2049                // Loop start
2050                let loop_start = self.chunk.current_offset();
2051
2052                // Set up try/catch (untyped - empty type name)
2053                let catch_jump = self.chunk.emit_jump(Op::TryCatchSetup, self.line);
2054                // Emit empty type name for untyped catch
2055                let empty_type = self.chunk.add_constant(Constant::String(String::new()));
2056                let hi = (empty_type >> 8) as u8;
2057                let lo = empty_type as u8;
2058                self.chunk.code.push(hi);
2059                self.chunk.code.push(lo);
2060                self.chunk.lines.push(self.line);
2061                self.chunk.columns.push(self.column);
2062                self.chunk.lines.push(self.line);
2063                self.chunk.columns.push(self.column);
2064
2065                // Compile body
2066                self.compile_block(body)?;
2067
2068                // Success: pop handler, jump to end
2069                self.chunk.emit(Op::PopHandler, self.line);
2070                let end_jump = self.chunk.emit_jump(Op::Jump, self.line);
2071
2072                // Catch handler
2073                self.chunk.patch_jump(catch_jump);
2074                // Save the error value for potential re-throw
2075                self.chunk.emit(Op::Dup, self.line);
2076                self.chunk.emit_u16(Op::SetVar, err_idx, self.line);
2077                // Pop the error value
2078                self.chunk.emit(Op::Pop, self.line);
2079
2080                // Decrement counter
2081                self.chunk.emit_u16(Op::GetVar, counter_idx, self.line);
2082                let one_idx = self.chunk.add_constant(Constant::Int(1));
2083                self.chunk.emit_u16(Op::Constant, one_idx, self.line);
2084                self.chunk.emit(Op::Sub, self.line);
2085                self.chunk.emit(Op::Dup, self.line);
2086                self.chunk.emit_u16(Op::SetVar, counter_idx, self.line);
2087
2088                // If counter > 0, jump to loop start
2089                let zero_idx = self.chunk.add_constant(Constant::Int(0));
2090                self.chunk.emit_u16(Op::Constant, zero_idx, self.line);
2091                self.chunk.emit(Op::Greater, self.line);
2092                let retry_jump = self.chunk.emit_jump(Op::JumpIfFalse, self.line);
2093                self.chunk.emit(Op::Pop, self.line); // pop condition
2094                self.chunk.emit_u16(Op::Jump, loop_start as u16, self.line);
2095
2096                // No more retries — re-throw the last error
2097                self.chunk.patch_jump(retry_jump);
2098                self.chunk.emit(Op::Pop, self.line); // pop condition
2099                self.chunk.emit_u16(Op::GetVar, err_idx, self.line);
2100                self.chunk.emit(Op::Throw, self.line);
2101
2102                self.chunk.patch_jump(end_jump);
2103                // Push nil as the result of a successful retry block
2104                self.chunk.emit(Op::Nil, self.line);
2105            }
2106
2107            Node::Parallel {
2108                count,
2109                variable,
2110                body,
2111            } => {
2112                self.compile_node(count)?;
2113                let mut fn_compiler = Compiler::new();
2114                fn_compiler.enum_names = self.enum_names.clone();
2115                fn_compiler.compile_block(body)?;
2116                fn_compiler.chunk.emit(Op::Return, self.line);
2117                let params = vec![variable.clone().unwrap_or_else(|| "__i__".to_string())];
2118                let func = CompiledFunction {
2119                    name: "<parallel>".to_string(),
2120                    params,
2121                    default_start: None,
2122                    chunk: fn_compiler.chunk,
2123                    is_generator: false,
2124                };
2125                let fn_idx = self.chunk.functions.len();
2126                self.chunk.functions.push(func);
2127                self.chunk.emit_u16(Op::Closure, fn_idx as u16, self.line);
2128                self.chunk.emit(Op::Parallel, self.line);
2129            }
2130
2131            Node::ParallelMap {
2132                list,
2133                variable,
2134                body,
2135            } => {
2136                self.compile_node(list)?;
2137                let mut fn_compiler = Compiler::new();
2138                fn_compiler.enum_names = self.enum_names.clone();
2139                fn_compiler.compile_block(body)?;
2140                fn_compiler.chunk.emit(Op::Return, self.line);
2141                let func = CompiledFunction {
2142                    name: "<parallel_map>".to_string(),
2143                    params: vec![variable.clone()],
2144                    default_start: None,
2145                    chunk: fn_compiler.chunk,
2146                    is_generator: false,
2147                };
2148                let fn_idx = self.chunk.functions.len();
2149                self.chunk.functions.push(func);
2150                self.chunk.emit_u16(Op::Closure, fn_idx as u16, self.line);
2151                self.chunk.emit(Op::ParallelMap, self.line);
2152            }
2153
2154            Node::ParallelSettle {
2155                list,
2156                variable,
2157                body,
2158            } => {
2159                self.compile_node(list)?;
2160                let mut fn_compiler = Compiler::new();
2161                fn_compiler.enum_names = self.enum_names.clone();
2162                fn_compiler.compile_block(body)?;
2163                fn_compiler.chunk.emit(Op::Return, self.line);
2164                let func = CompiledFunction {
2165                    name: "<parallel_settle>".to_string(),
2166                    params: vec![variable.clone()],
2167                    default_start: None,
2168                    chunk: fn_compiler.chunk,
2169                    is_generator: false,
2170                };
2171                let fn_idx = self.chunk.functions.len();
2172                self.chunk.functions.push(func);
2173                self.chunk.emit_u16(Op::Closure, fn_idx as u16, self.line);
2174                self.chunk.emit(Op::ParallelSettle, self.line);
2175            }
2176
2177            Node::SpawnExpr { body } => {
2178                let mut fn_compiler = Compiler::new();
2179                fn_compiler.enum_names = self.enum_names.clone();
2180                fn_compiler.compile_block(body)?;
2181                fn_compiler.chunk.emit(Op::Return, self.line);
2182                let func = CompiledFunction {
2183                    name: "<spawn>".to_string(),
2184                    params: vec![],
2185                    default_start: None,
2186                    chunk: fn_compiler.chunk,
2187                    is_generator: false,
2188                };
2189                let fn_idx = self.chunk.functions.len();
2190                self.chunk.functions.push(func);
2191                self.chunk.emit_u16(Op::Closure, fn_idx as u16, self.line);
2192                self.chunk.emit(Op::Spawn, self.line);
2193            }
2194            Node::SelectExpr {
2195                cases,
2196                timeout,
2197                default_body,
2198            } => {
2199                // Desugar select into: builtin call + index-based dispatch.
2200                //
2201                // Step 1: Push builtin name, compile channel list, optionally
2202                //         compile timeout duration, then Call.
2203                // Step 2: Store result dict in temp, dispatch on result.index.
2204
2205                let builtin_name = if timeout.is_some() {
2206                    "__select_timeout"
2207                } else if default_body.is_some() {
2208                    "__select_try"
2209                } else {
2210                    "__select_list"
2211                };
2212
2213                // Push builtin name (callee goes below args on stack)
2214                let name_idx = self
2215                    .chunk
2216                    .add_constant(Constant::String(builtin_name.into()));
2217                self.chunk.emit_u16(Op::Constant, name_idx, self.line);
2218
2219                // Build channel list (arg 1)
2220                for case in cases {
2221                    self.compile_node(&case.channel)?;
2222                }
2223                self.chunk
2224                    .emit_u16(Op::BuildList, cases.len() as u16, self.line);
2225
2226                // If timeout, compile duration (arg 2)
2227                if let Some((duration_expr, _)) = timeout {
2228                    self.compile_node(duration_expr)?;
2229                    self.chunk.emit_u8(Op::Call, 2, self.line);
2230                } else {
2231                    self.chunk.emit_u8(Op::Call, 1, self.line);
2232                }
2233
2234                // Store result in temp var
2235                self.temp_counter += 1;
2236                let result_name = format!("__sel_result_{}__", self.temp_counter);
2237                let result_idx = self
2238                    .chunk
2239                    .add_constant(Constant::String(result_name.clone()));
2240                self.chunk.emit_u16(Op::DefVar, result_idx, self.line);
2241
2242                // Dispatch on result.index
2243                let mut end_jumps = Vec::new();
2244
2245                for (i, case) in cases.iter().enumerate() {
2246                    let get_r = self
2247                        .chunk
2248                        .add_constant(Constant::String(result_name.clone()));
2249                    self.chunk.emit_u16(Op::GetVar, get_r, self.line);
2250                    let idx_prop = self.chunk.add_constant(Constant::String("index".into()));
2251                    self.chunk.emit_u16(Op::GetProperty, idx_prop, self.line);
2252                    let case_i = self.chunk.add_constant(Constant::Int(i as i64));
2253                    self.chunk.emit_u16(Op::Constant, case_i, self.line);
2254                    self.chunk.emit(Op::Equal, self.line);
2255                    let skip = self.chunk.emit_jump(Op::JumpIfFalse, self.line);
2256                    self.chunk.emit(Op::Pop, self.line);
2257
2258                    // Bind variable = result.value
2259                    let get_r2 = self
2260                        .chunk
2261                        .add_constant(Constant::String(result_name.clone()));
2262                    self.chunk.emit_u16(Op::GetVar, get_r2, self.line);
2263                    let val_prop = self.chunk.add_constant(Constant::String("value".into()));
2264                    self.chunk.emit_u16(Op::GetProperty, val_prop, self.line);
2265                    let var_idx = self
2266                        .chunk
2267                        .add_constant(Constant::String(case.variable.clone()));
2268                    self.chunk.emit_u16(Op::DefLet, var_idx, self.line);
2269
2270                    self.compile_try_body(&case.body)?;
2271                    end_jumps.push(self.chunk.emit_jump(Op::Jump, self.line));
2272                    self.chunk.patch_jump(skip);
2273                    self.chunk.emit(Op::Pop, self.line);
2274                }
2275
2276                // Timeout/default fallthrough (index == -1)
2277                if let Some((_, ref timeout_body)) = timeout {
2278                    self.compile_try_body(timeout_body)?;
2279                } else if let Some(ref def_body) = default_body {
2280                    self.compile_try_body(def_body)?;
2281                } else {
2282                    self.chunk.emit(Op::Nil, self.line);
2283                }
2284
2285                for ej in end_jumps {
2286                    self.chunk.patch_jump(ej);
2287                }
2288            }
2289            Node::Spread(_) => {
2290                return Err(CompileError {
2291                    message: "spread (...) can only be used inside list literals, dict literals, or function call arguments".into(),
2292                    line: self.line,
2293                });
2294            }
2295        }
2296        Ok(())
2297    }
2298
2299    /// Compile a destructuring binding pattern.
2300    /// Expects the RHS value to already be on the stack.
2301    /// After this, the value is consumed (popped) and each binding is defined.
2302    fn compile_destructuring(
2303        &mut self,
2304        pattern: &BindingPattern,
2305        is_mutable: bool,
2306    ) -> Result<(), CompileError> {
2307        let def_op = if is_mutable { Op::DefVar } else { Op::DefLet };
2308        match pattern {
2309            BindingPattern::Identifier(name) => {
2310                // Simple case: just define the variable
2311                let idx = self.chunk.add_constant(Constant::String(name.clone()));
2312                self.chunk.emit_u16(def_op, idx, self.line);
2313            }
2314            BindingPattern::Dict(fields) => {
2315                // Stack has the dict value.
2316                // Emit runtime type check: __assert_dict(value)
2317                self.chunk.emit(Op::Dup, self.line);
2318                let assert_idx = self
2319                    .chunk
2320                    .add_constant(Constant::String("__assert_dict".into()));
2321                self.chunk.emit_u16(Op::Constant, assert_idx, self.line);
2322                self.chunk.emit(Op::Swap, self.line);
2323                self.chunk.emit_u8(Op::Call, 1, self.line);
2324                self.chunk.emit(Op::Pop, self.line); // discard nil result
2325
2326                // For each non-rest field: dup dict, push key string, subscript, define var.
2327                // For rest field: dup dict, call __dict_rest builtin.
2328                let non_rest: Vec<_> = fields.iter().filter(|f| !f.is_rest).collect();
2329                let rest_field = fields.iter().find(|f| f.is_rest);
2330
2331                for field in &non_rest {
2332                    self.chunk.emit(Op::Dup, self.line);
2333                    let key_idx = self.chunk.add_constant(Constant::String(field.key.clone()));
2334                    self.chunk.emit_u16(Op::Constant, key_idx, self.line);
2335                    self.chunk.emit(Op::Subscript, self.line);
2336                    let binding_name = field.alias.as_deref().unwrap_or(&field.key);
2337                    let name_idx = self
2338                        .chunk
2339                        .add_constant(Constant::String(binding_name.to_string()));
2340                    self.chunk.emit_u16(def_op, name_idx, self.line);
2341                }
2342
2343                if let Some(rest) = rest_field {
2344                    // Call the __dict_rest builtin: __dict_rest(dict, [keys_to_exclude])
2345                    // Push function name
2346                    let fn_idx = self
2347                        .chunk
2348                        .add_constant(Constant::String("__dict_rest".into()));
2349                    self.chunk.emit_u16(Op::Constant, fn_idx, self.line);
2350                    // Swap so dict is above function name: [fn, dict]
2351                    self.chunk.emit(Op::Swap, self.line);
2352                    // Build the exclusion keys list
2353                    for field in &non_rest {
2354                        let key_idx = self.chunk.add_constant(Constant::String(field.key.clone()));
2355                        self.chunk.emit_u16(Op::Constant, key_idx, self.line);
2356                    }
2357                    self.chunk
2358                        .emit_u16(Op::BuildList, non_rest.len() as u16, self.line);
2359                    // Call __dict_rest(dict, keys_list) — 2 args
2360                    self.chunk.emit_u8(Op::Call, 2, self.line);
2361                    let rest_name = &rest.key;
2362                    let rest_idx = self.chunk.add_constant(Constant::String(rest_name.clone()));
2363                    self.chunk.emit_u16(def_op, rest_idx, self.line);
2364                } else {
2365                    // Pop the source dict
2366                    self.chunk.emit(Op::Pop, self.line);
2367                }
2368            }
2369            BindingPattern::List(elements) => {
2370                // Stack has the list value.
2371                // Emit runtime type check: __assert_list(value)
2372                self.chunk.emit(Op::Dup, self.line);
2373                let assert_idx = self
2374                    .chunk
2375                    .add_constant(Constant::String("__assert_list".into()));
2376                self.chunk.emit_u16(Op::Constant, assert_idx, self.line);
2377                self.chunk.emit(Op::Swap, self.line);
2378                self.chunk.emit_u8(Op::Call, 1, self.line);
2379                self.chunk.emit(Op::Pop, self.line); // discard nil result
2380
2381                let non_rest: Vec<_> = elements.iter().filter(|e| !e.is_rest).collect();
2382                let rest_elem = elements.iter().find(|e| e.is_rest);
2383
2384                for (i, elem) in non_rest.iter().enumerate() {
2385                    self.chunk.emit(Op::Dup, self.line);
2386                    let idx_const = self.chunk.add_constant(Constant::Int(i as i64));
2387                    self.chunk.emit_u16(Op::Constant, idx_const, self.line);
2388                    self.chunk.emit(Op::Subscript, self.line);
2389                    let name_idx = self.chunk.add_constant(Constant::String(elem.name.clone()));
2390                    self.chunk.emit_u16(def_op, name_idx, self.line);
2391                }
2392
2393                if let Some(rest) = rest_elem {
2394                    // Slice the list from index non_rest.len() to end: list[n..]
2395                    // Slice op takes: object, start, end on stack
2396                    // self.chunk.emit(Op::Dup, self.line); -- list is still on stack
2397                    let start_idx = self
2398                        .chunk
2399                        .add_constant(Constant::Int(non_rest.len() as i64));
2400                    self.chunk.emit_u16(Op::Constant, start_idx, self.line);
2401                    self.chunk.emit(Op::Nil, self.line); // end = nil (to end)
2402                    self.chunk.emit(Op::Slice, self.line);
2403                    let rest_name_idx =
2404                        self.chunk.add_constant(Constant::String(rest.name.clone()));
2405                    self.chunk.emit_u16(def_op, rest_name_idx, self.line);
2406                } else {
2407                    // Pop the source list
2408                    self.chunk.emit(Op::Pop, self.line);
2409                }
2410            }
2411        }
2412        Ok(())
2413    }
2414
2415    /// Check if a node produces a value on the stack that needs to be popped.
2416    fn produces_value(node: &Node) -> bool {
2417        match node {
2418            // These nodes do NOT produce a value on the stack
2419            Node::LetBinding { .. }
2420            | Node::VarBinding { .. }
2421            | Node::Assignment { .. }
2422            | Node::ReturnStmt { .. }
2423            | Node::FnDecl { .. }
2424            | Node::ImplBlock { .. }
2425            | Node::StructDecl { .. }
2426            | Node::EnumDecl { .. }
2427            | Node::InterfaceDecl { .. }
2428            | Node::TypeDecl { .. }
2429            | Node::ThrowStmt { .. }
2430            | Node::BreakStmt
2431            | Node::ContinueStmt => false,
2432            // These compound nodes explicitly produce a value
2433            Node::TryCatch { .. }
2434            | Node::TryExpr { .. }
2435            | Node::Retry { .. }
2436            | Node::GuardStmt { .. }
2437            | Node::DeadlineBlock { .. }
2438            | Node::MutexBlock { .. }
2439            | Node::Spread(_) => true,
2440            // All other expressions produce values
2441            _ => true,
2442        }
2443    }
2444}
2445
2446impl Compiler {
2447    /// Compile a function body into a CompiledFunction (for import support).
2448    pub fn compile_fn_body(
2449        &mut self,
2450        params: &[TypedParam],
2451        body: &[SNode],
2452    ) -> Result<CompiledFunction, CompileError> {
2453        let mut fn_compiler = Compiler::new();
2454        fn_compiler.compile_block(body)?;
2455        fn_compiler.chunk.emit(Op::Nil, 0);
2456        fn_compiler.chunk.emit(Op::Return, 0);
2457        Ok(CompiledFunction {
2458            name: String::new(),
2459            params: TypedParam::names(params),
2460            default_start: TypedParam::default_start(params),
2461            chunk: fn_compiler.chunk,
2462            is_generator: false,
2463        })
2464    }
2465
2466    /// Compile a match arm body, ensuring it always pushes exactly one value.
2467    fn compile_match_body(&mut self, body: &[SNode]) -> Result<(), CompileError> {
2468        if body.is_empty() {
2469            self.chunk.emit(Op::Nil, self.line);
2470        } else {
2471            self.compile_block(body)?;
2472            // If the last statement doesn't produce a value, push nil
2473            if !Self::produces_value(&body.last().unwrap().node) {
2474                self.chunk.emit(Op::Nil, self.line);
2475            }
2476        }
2477        Ok(())
2478    }
2479
2480    /// Emit the binary op instruction for a compound assignment operator.
2481    fn emit_compound_op(&mut self, op: &str) -> Result<(), CompileError> {
2482        match op {
2483            "+" => self.chunk.emit(Op::Add, self.line),
2484            "-" => self.chunk.emit(Op::Sub, self.line),
2485            "*" => self.chunk.emit(Op::Mul, self.line),
2486            "/" => self.chunk.emit(Op::Div, self.line),
2487            "%" => self.chunk.emit(Op::Mod, self.line),
2488            _ => {
2489                return Err(CompileError {
2490                    message: format!("Unknown compound operator: {op}"),
2491                    line: self.line,
2492                })
2493            }
2494        }
2495        Ok(())
2496    }
2497
2498    /// Extract the root variable name from a (possibly nested) access expression.
2499    fn root_var_name(&self, node: &SNode) -> Option<String> {
2500        match &node.node {
2501            Node::Identifier(name) => Some(name.clone()),
2502            Node::PropertyAccess { object, .. } | Node::OptionalPropertyAccess { object, .. } => {
2503                self.root_var_name(object)
2504            }
2505            Node::SubscriptAccess { object, .. } => self.root_var_name(object),
2506            _ => None,
2507        }
2508    }
2509}
2510
2511impl Compiler {
2512    /// Recursively collect all enum type names from the AST.
2513    fn collect_enum_names(nodes: &[SNode], names: &mut std::collections::HashSet<String>) {
2514        for sn in nodes {
2515            match &sn.node {
2516                Node::EnumDecl { name, .. } => {
2517                    names.insert(name.clone());
2518                }
2519                Node::Pipeline { body, .. } => {
2520                    Self::collect_enum_names(body, names);
2521                }
2522                Node::FnDecl { body, .. } => {
2523                    Self::collect_enum_names(body, names);
2524                }
2525                Node::Block(stmts) => {
2526                    Self::collect_enum_names(stmts, names);
2527                }
2528                _ => {}
2529            }
2530        }
2531    }
2532
2533    fn collect_interface_methods(
2534        nodes: &[SNode],
2535        interfaces: &mut std::collections::HashMap<String, Vec<String>>,
2536    ) {
2537        for sn in nodes {
2538            match &sn.node {
2539                Node::InterfaceDecl { name, methods } => {
2540                    let method_names: Vec<String> =
2541                        methods.iter().map(|m| m.name.clone()).collect();
2542                    interfaces.insert(name.clone(), method_names);
2543                }
2544                Node::Pipeline { body, .. } | Node::FnDecl { body, .. } => {
2545                    Self::collect_interface_methods(body, interfaces);
2546                }
2547                Node::Block(stmts) => {
2548                    Self::collect_interface_methods(stmts, interfaces);
2549                }
2550                _ => {}
2551            }
2552        }
2553    }
2554}
2555
2556impl Default for Compiler {
2557    fn default() -> Self {
2558        Self::new()
2559    }
2560}
2561
2562/// Check if a list of AST nodes contains any `yield` expression (used to detect generator functions).
2563fn body_contains_yield(nodes: &[SNode]) -> bool {
2564    nodes.iter().any(|sn| node_contains_yield(&sn.node))
2565}
2566
2567fn node_contains_yield(node: &Node) -> bool {
2568    match node {
2569        Node::YieldExpr { .. } => true,
2570        // Don't recurse into nested function/closure declarations — yield in a nested
2571        // function does NOT make the outer function a generator.
2572        Node::FnDecl { .. } | Node::Closure { .. } => false,
2573        Node::Block(stmts) => body_contains_yield(stmts),
2574        Node::IfElse {
2575            condition,
2576            then_body,
2577            else_body,
2578        } => {
2579            node_contains_yield(&condition.node)
2580                || body_contains_yield(then_body)
2581                || else_body.as_ref().is_some_and(|b| body_contains_yield(b))
2582        }
2583        Node::WhileLoop { condition, body } => {
2584            node_contains_yield(&condition.node) || body_contains_yield(body)
2585        }
2586        Node::ForIn { iterable, body, .. } => {
2587            node_contains_yield(&iterable.node) || body_contains_yield(body)
2588        }
2589        Node::TryCatch {
2590            body, catch_body, ..
2591        } => body_contains_yield(body) || body_contains_yield(catch_body),
2592        Node::TryExpr { body } => body_contains_yield(body),
2593        _ => false,
2594    }
2595}
2596
2597/// Check if an AST node contains `_` identifier (pipe placeholder).
2598fn contains_pipe_placeholder(node: &SNode) -> bool {
2599    match &node.node {
2600        Node::Identifier(name) if name == "_" => true,
2601        Node::FunctionCall { args, .. } => args.iter().any(contains_pipe_placeholder),
2602        Node::MethodCall { object, args, .. } => {
2603            contains_pipe_placeholder(object) || args.iter().any(contains_pipe_placeholder)
2604        }
2605        Node::BinaryOp { left, right, .. } => {
2606            contains_pipe_placeholder(left) || contains_pipe_placeholder(right)
2607        }
2608        Node::UnaryOp { operand, .. } => contains_pipe_placeholder(operand),
2609        Node::ListLiteral(items) => items.iter().any(contains_pipe_placeholder),
2610        Node::PropertyAccess { object, .. } => contains_pipe_placeholder(object),
2611        Node::SubscriptAccess { object, index } => {
2612            contains_pipe_placeholder(object) || contains_pipe_placeholder(index)
2613        }
2614        _ => false,
2615    }
2616}
2617
2618/// Replace all `_` identifiers with `__pipe` in an AST node (for pipe placeholder desugaring).
2619fn replace_pipe_placeholder(node: &SNode) -> SNode {
2620    let new_node = match &node.node {
2621        Node::Identifier(name) if name == "_" => Node::Identifier("__pipe".into()),
2622        Node::FunctionCall { name, args } => Node::FunctionCall {
2623            name: name.clone(),
2624            args: args.iter().map(replace_pipe_placeholder).collect(),
2625        },
2626        Node::MethodCall {
2627            object,
2628            method,
2629            args,
2630        } => Node::MethodCall {
2631            object: Box::new(replace_pipe_placeholder(object)),
2632            method: method.clone(),
2633            args: args.iter().map(replace_pipe_placeholder).collect(),
2634        },
2635        Node::BinaryOp { op, left, right } => Node::BinaryOp {
2636            op: op.clone(),
2637            left: Box::new(replace_pipe_placeholder(left)),
2638            right: Box::new(replace_pipe_placeholder(right)),
2639        },
2640        Node::UnaryOp { op, operand } => Node::UnaryOp {
2641            op: op.clone(),
2642            operand: Box::new(replace_pipe_placeholder(operand)),
2643        },
2644        Node::ListLiteral(items) => {
2645            Node::ListLiteral(items.iter().map(replace_pipe_placeholder).collect())
2646        }
2647        Node::PropertyAccess { object, property } => Node::PropertyAccess {
2648            object: Box::new(replace_pipe_placeholder(object)),
2649            property: property.clone(),
2650        },
2651        Node::SubscriptAccess { object, index } => Node::SubscriptAccess {
2652            object: Box::new(replace_pipe_placeholder(object)),
2653            index: Box::new(replace_pipe_placeholder(index)),
2654        },
2655        _ => return node.clone(),
2656    };
2657    SNode::new(new_node, node.span)
2658}
2659
2660#[cfg(test)]
2661mod tests {
2662    use super::*;
2663    use harn_lexer::Lexer;
2664    use harn_parser::Parser;
2665
2666    fn compile_source(source: &str) -> Chunk {
2667        let mut lexer = Lexer::new(source);
2668        let tokens = lexer.tokenize().unwrap();
2669        let mut parser = Parser::new(tokens);
2670        let program = parser.parse().unwrap();
2671        Compiler::new().compile(&program).unwrap()
2672    }
2673
2674    #[test]
2675    fn test_compile_arithmetic() {
2676        let chunk = compile_source("pipeline test(task) { let x = 2 + 3 }");
2677        assert!(!chunk.code.is_empty());
2678        // Should have constants: 2, 3, "x"
2679        assert!(chunk.constants.contains(&Constant::Int(2)));
2680        assert!(chunk.constants.contains(&Constant::Int(3)));
2681    }
2682
2683    #[test]
2684    fn test_compile_function_call() {
2685        let chunk = compile_source("pipeline test(task) { log(42) }");
2686        let disasm = chunk.disassemble("test");
2687        assert!(disasm.contains("CALL"));
2688    }
2689
2690    #[test]
2691    fn test_compile_if_else() {
2692        let chunk =
2693            compile_source(r#"pipeline test(task) { if true { log("yes") } else { log("no") } }"#);
2694        let disasm = chunk.disassemble("test");
2695        assert!(disasm.contains("JUMP_IF_FALSE"));
2696        assert!(disasm.contains("JUMP"));
2697    }
2698
2699    #[test]
2700    fn test_compile_while() {
2701        let chunk = compile_source("pipeline test(task) { var i = 0\n while i < 5 { i = i + 1 } }");
2702        let disasm = chunk.disassemble("test");
2703        assert!(disasm.contains("JUMP_IF_FALSE"));
2704        // Should have a backward jump
2705        assert!(disasm.contains("JUMP"));
2706    }
2707
2708    #[test]
2709    fn test_compile_closure() {
2710        let chunk = compile_source("pipeline test(task) { let f = { x -> x * 2 } }");
2711        assert!(!chunk.functions.is_empty());
2712        assert_eq!(chunk.functions[0].params, vec!["x"]);
2713    }
2714
2715    #[test]
2716    fn test_compile_list() {
2717        let chunk = compile_source("pipeline test(task) { let a = [1, 2, 3] }");
2718        let disasm = chunk.disassemble("test");
2719        assert!(disasm.contains("BUILD_LIST"));
2720    }
2721
2722    #[test]
2723    fn test_compile_dict() {
2724        let chunk = compile_source(r#"pipeline test(task) { let d = {name: "test"} }"#);
2725        let disasm = chunk.disassemble("test");
2726        assert!(disasm.contains("BUILD_DICT"));
2727    }
2728
2729    #[test]
2730    fn test_disassemble() {
2731        let chunk = compile_source("pipeline test(task) { log(2 + 3) }");
2732        let disasm = chunk.disassemble("test");
2733        // Should be readable
2734        assert!(disasm.contains("CONSTANT"));
2735        assert!(disasm.contains("ADD"));
2736        assert!(disasm.contains("CALL"));
2737    }
2738}