Skip to main content

vibe/bytecode/
compiler.rs

1//! AST → bytecode compiler.
2//!
3//! Compiles a checked `vibe::ast::Program` into a `Chunk`. The
4//! compiler walks each function body and top-level statement, emitting
5//! stack-based opcodes. Local variables are assigned slot indices; string
6//! and IRI literals are interned into the constant pool.
7//!
8//! ## Compilation model
9//!
10//! - Each user function gets a `FuncMeta` entry and a code region.
11//! - Top-level statements are emitted into a preamble that runs before
12//!   any function call.
13//! - Control flow uses forward/backward jumps with patching.
14//! - `return` emits `Op::Return`; falling off the end of a function emits
15//!   `Op::ReturnNull`.
16
17use crate::ast::*;
18use crate::bytecode::op::{Chunk, FuncMeta, Op};
19use std::collections::HashMap;
20
21/// Compiler error.
22#[derive(Debug, Clone, PartialEq)]
23pub enum CompileError {
24    /// Too many constants in the pool.
25    TooManyConstants,
26    /// Too many local variable slots.
27    TooManyLocals,
28    /// Too many functions.
29    TooManyFunctions,
30    /// Code segment exceeds 64 KiB.
31    CodeTooLarge,
32    /// Feature not yet supported in bytecode.
33    Unsupported(&'static str),
34    /// A `break`/`continue` appeared outside a loop.
35    BreakOutsideLoop,
36    /// A `continue` appeared outside a loop.
37    ContinueOutsideLoop,
38}
39
40impl std::fmt::Display for CompileError {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        match self {
43            Self::TooManyConstants => write!(f, "bytecode: too many constants (>65535)"),
44            Self::TooManyLocals => write!(f, "bytecode: too many locals (>65535)"),
45            Self::TooManyFunctions => write!(f, "bytecode: too many functions (>65535)"),
46            Self::CodeTooLarge => write!(f, "bytecode: code segment exceeds 64 KiB"),
47            Self::Unsupported(what) => write!(f, "bytecode: unsupported feature: {what}"),
48            Self::BreakOutsideLoop => write!(f, "bytecode: break outside loop"),
49            Self::ContinueOutsideLoop => write!(f, "bytecode: continue outside loop"),
50        }
51    }
52}
53
54impl std::error::Error for CompileError {}
55
56/// A pending jump that needs its target patched once the destination offset is known.
57struct PendingJump {
58    /// Offset of the u16 operand in `code` that needs patching.
59    operand_offset: usize,
60}
61
62/// Loop context for break/continue patching.
63struct LoopCtx {
64    /// Pending `JumpIfFalse` operands for `continue` (jump to loop start).
65    continues: Vec<PendingJump>,
66    /// Pending `Jump` operands for `break` (jump to loop end).
67    breaks: Vec<PendingJump>,
68}
69
70/// The compiler state.
71struct Compiler {
72    chunk: Chunk,
73    /// Current scope's variable name → slot index (relative to current frame).
74    scopes: Vec<HashMap<String, u16>>,
75    /// Loop stack for break/continue.
76    loops: Vec<LoopCtx>,
77    /// Map from function name → index in `chunk.functions`.
78    func_indices: HashMap<String, u16>,
79    /// User-defined enum declarations (for variant construction/matching).
80    enums: HashMap<String, EnumDecl>,
81    /// Base offset for the current function's locals.
82    /// Top-level preamble uses 0; each function uses 1.
83    local_base: u16,
84    /// Next local slot for the current frame.
85    next_local: u16,
86    aliases: HashMap<String, String>,
87}
88
89impl Compiler {
90    fn new() -> Self {
91        Self {
92            chunk: Chunk::new(),
93            scopes: vec![HashMap::new()],
94            loops: Vec::new(),
95            func_indices: HashMap::new(),
96            enums: HashMap::new(),
97            local_base: 0,
98            next_local: 0,
99            aliases: HashMap::new(),
100        }
101    }
102
103    fn current_scope(&mut self) -> &mut HashMap<String, u16> {
104        self.scopes.last_mut().expect("scope stack")
105    }
106
107    fn lookup(&self, name: &str) -> Option<u16> {
108        for scope in self.scopes.iter().rev() {
109            if let Some(&slot) = scope.get(name) {
110                return Some(slot);
111            }
112        }
113        None
114    }
115
116    fn declare_var(&mut self, name: &str) -> Result<u16, CompileError> {
117        let slot = self.next_local;
118        if slot as usize >= crate::bytecode::op::MAX_LOCALS {
119            return Err(CompileError::TooManyLocals);
120        }
121        self.current_scope().insert(name.to_string(), slot);
122        self.next_local += 1;
123        // Track the maximum number of locals needed for the top-level preamble.
124        if self.local_base == 0 && slot >= self.chunk.top_locals {
125            self.chunk.top_locals = slot + 1;
126        }
127        Ok(slot)
128    }
129
130    fn add_string(&mut self, s: &str) -> Result<u16, CompileError> {
131        if self.chunk.constants.len() >= crate::bytecode::op::MAX_CONSTANTS {
132            return Err(CompileError::TooManyConstants);
133        }
134        Ok(self.chunk.add_string(s))
135    }
136
137    fn add_iri(&mut self, s: &str) -> Result<u16, CompileError> {
138        if self.chunk.constants.len() >= crate::bytecode::op::MAX_CONSTANTS {
139            return Err(CompileError::TooManyConstants);
140        }
141        Ok(self.chunk.add_iri(s))
142    }
143
144    fn check_code_size(&self) -> Result<(), CompileError> {
145        if self.chunk.code.len() >= crate::bytecode::op::MAX_CODE {
146            Err(CompileError::CodeTooLarge)
147        } else {
148            Ok(())
149        }
150    }
151
152    fn emit_op(&mut self, op: Op) -> Result<(), CompileError> {
153        self.chunk.emit_op(op);
154        self.check_code_size()
155    }
156
157    fn emit_u16(&mut self, v: u16) -> Result<(), CompileError> {
158        self.chunk.emit_u16(v);
159        self.check_code_size()
160    }
161
162    fn emit_u8(&mut self, v: u8) -> Result<(), CompileError> {
163        self.chunk.emit_u8(v);
164        self.check_code_size()
165    }
166
167    fn emit_i64(&mut self, v: i64) -> Result<(), CompileError> {
168        self.chunk.emit_i64(v);
169        self.check_code_size()
170    }
171
172    fn emit_u64(&mut self, v: u64) -> Result<(), CompileError> {
173        self.chunk.emit_u64(v);
174        self.check_code_size()
175    }
176
177    /// Reserve a u16 operand placeholder, returning the offset for later patching.
178    fn emit_placeholder(&mut self) -> Result<usize, CompileError> {
179        let off = self.chunk.code.len();
180        self.chunk.emit_u16(0);
181        self.check_code_size()?;
182        Ok(off)
183    }
184
185    fn patch(&mut self, operand_offset: usize, target: u16) {
186        self.chunk.patch_u16(operand_offset, target);
187    }
188
189    fn push_scope(&mut self) {
190        self.scopes.push(HashMap::new());
191    }
192
193    fn pop_scope(&mut self) {
194        self.scopes.pop();
195    }
196
197    // ── Expression compilation ───────────────────────────────────
198
199    fn compile_expr(&mut self, e: &Expr) -> Result<(), CompileError> {
200        match &e.kind {
201            ExprKind::Literal(lit) => self.compile_literal(lit),
202            ExprKind::Ident(name) => {
203                if name == "None" {
204                    return self.emit_op(Op::PushNull);
205                }
206                if let Some(slot) = self.lookup(name) {
207                    self.emit_op(Op::LoadVar)?;
208                    self.emit_u16(slot)?;
209                } else {
210                    // Unresolved identifier — emit as a string for host dispatch
211                    // to resolve (e.g. module function names like `math.sqrt`).
212                    let idx = self.add_string(name)?;
213                    self.emit_op(Op::PushString)?;
214                    self.emit_u16(idx)?;
215                }
216                Ok(())
217            }
218            ExprKind::QueryVar(name) => {
219                let idx = self.add_string(&format!("?{name}"))?;
220                self.emit_op(Op::PushString)?;
221                self.emit_u16(idx)
222            }
223            ExprKind::Iri(iri) => {
224                let idx = self.add_iri(iri)?;
225                self.emit_op(Op::PushIri)?;
226                self.emit_u16(idx)
227            }
228            ExprKind::Prefixed(prefix, local) => {
229                let idx = self.add_iri(&format!("{prefix}:{local}"))?;
230                self.emit_op(Op::PushIri)?;
231                self.emit_u16(idx)
232            }
233            ExprKind::Blank(label) => {
234                let idx = self.add_string(&format!("_:{label}"))?;
235                self.emit_op(Op::PushString)?;
236                self.emit_u16(idx)
237            }
238            ExprKind::Binary { op, left, right } => self.compile_binary(op, left, right),
239            ExprKind::IfElse {
240                cond,
241                then_value,
242                else_value,
243            } => {
244                // cond; JumpIfFalse else; then; Jump end; else: else_value; end:
245                // Each path pushes exactly one value, so stack depth at the
246                // merge point is identical on both paths.
247                self.compile_expr(cond)?;
248                self.emit_op(Op::JumpIfFalse)?;
249                let else_jump = self.emit_placeholder()?;
250                self.compile_expr(then_value)?;
251                self.emit_op(Op::Jump)?;
252                let end_jump = self.emit_placeholder()?;
253                let else_start = self.chunk.current_offset();
254                self.patch(else_jump, else_start);
255                self.compile_expr(else_value)?;
256                let end = self.chunk.current_offset();
257                self.patch(end_jump, end);
258                Ok(())
259            }
260            ExprKind::Unary { op, expr } => self.compile_unary(op, expr),
261            ExprKind::Await(inner) => {
262                // Literal await is identity. Dynamic tasks need the admitted AST
263                // Engine context that this VM profile does not carry.
264                if !matches!(&inner.kind, ExprKind::Literal(_)) {
265                    return Err(CompileError::Unsupported(
266                        "dynamic await requires the admitted AST task runtime",
267                    ));
268                }
269                self.compile_expr(inner)
270            }
271            ExprKind::Member { recv, name } => {
272                self.compile_expr(recv)?;
273                let idx = self.add_string(name)?;
274                self.emit_op(Op::GetMember)?;
275                self.emit_u16(idx)
276            }
277            ExprKind::Call { callee, args } => self.compile_call(callee, args),
278            ExprKind::Index { recv, index } => {
279                self.compile_expr(recv)?;
280                self.compile_expr(index)?;
281                self.emit_op(Op::GetIndex)
282            }
283            ExprKind::Try(inner) => {
284                self.compile_expr(inner)?;
285                self.emit_op(Op::TryUnwrap)?;
286                let catch_off = self.emit_placeholder()?;
287                // Patch catch to the instruction immediately after TryUnwrap so
288                // Op::TryUnwrap propagates `Err(...)` as E600, matching AST `eval_expr`.
289                let after = self.chunk.current_offset();
290                self.patch(catch_off, after);
291                Ok(())
292            }
293            ExprKind::List(elements) => {
294                if elements.len() > u16::MAX as usize {
295                    return Err(CompileError::CodeTooLarge);
296                }
297                for el in elements {
298                    self.compile_expr(el)?;
299                }
300                self.emit_op(Op::MakeList)?;
301                self.emit_u16(elements.len() as u16)
302            }
303            ExprKind::Record(fields) => {
304                if fields.len() > u16::MAX as usize {
305                    return Err(CompileError::CodeTooLarge);
306                }
307                for na in fields {
308                    let key_idx = self.add_string(&na.name)?;
309                    self.emit_op(Op::PushString)?;
310                    self.emit_u16(key_idx)?;
311                    self.compile_expr(&na.value)?;
312                }
313                self.emit_op(Op::MakeRecord)?;
314                self.emit_u16(fields.len() as u16)
315            }
316            ExprKind::Pipe { left, right } => match &right.kind {
317                ExprKind::Call { callee, args } => {
318                    let mut all_args = vec![crate::ast::Arg::Pos((**left).clone())];
319                    all_args.extend(args.iter().cloned());
320                    self.compile_call(callee, &all_args)
321                }
322                _ => {
323                    let all_args = vec![crate::ast::Arg::Pos((**left).clone())];
324                    self.compile_call(right, &all_args)
325                }
326            },
327            ExprKind::Interpolate(parts) => {
328                if parts.is_empty() {
329                    let idx = self.add_string("")?;
330                    self.emit_op(Op::PushString)?;
331                    self.emit_u16(idx)?;
332                    return Ok(());
333                }
334                for (i, p) in parts.iter().enumerate() {
335                    self.compile_expr(p)?;
336                    if i > 0 {
337                        self.emit_op(Op::Add)?;
338                    }
339                }
340                Ok(())
341            }
342            ExprKind::GraphQuery { .. } | ExprKind::ModalLogic { .. } => {
343                Err(CompileError::Unsupported(
344                    "graph query / modal logic in pure bytecode VM; use AST evaluator",
345                ))
346            }
347            ExprKind::Lambda { .. } => Err(CompileError::Unsupported(
348                "lambda in bytecode VM; use AST evaluator",
349            )),
350            ExprKind::Tween { .. } => Err(CompileError::Unsupported(
351                "tween in bytecode VM; use AST evaluator",
352            )),
353            ExprKind::Triple { .. } | ExprKind::Reified { .. } => Err(CompileError::Unsupported(
354                "triple/reified terms in bytecode",
355            )),
356        }
357    }
358
359    fn compile_literal(&mut self, lit: &Literal) -> Result<(), CompileError> {
360        match lit {
361            Literal::Null => self.emit_op(Op::PushNull),
362            Literal::Bool(b) => {
363                self.emit_op(Op::PushBool)?;
364                self.emit_u8(if *b { 1 } else { 0 })
365            }
366            Literal::Int(v) => {
367                self.emit_op(Op::PushInt)?;
368                self.emit_i64(*v)
369            }
370            Literal::UInt(v) => {
371                self.emit_op(Op::PushUInt)?;
372                self.emit_u64(*v)
373            }
374            Literal::Float(bits) => {
375                self.emit_op(Op::PushFloat)?;
376                self.emit_u64(*bits)
377            }
378            Literal::Quantity { value, unit } => {
379                let idx = self.add_string(unit)?;
380                self.emit_op(Op::PushQuantity)?;
381                self.emit_u64(*value)?;
382                self.emit_u16(idx)
383            }
384            Literal::String(s) => {
385                let idx = self.add_string(s)?;
386                self.emit_op(Op::PushString)?;
387                self.emit_u16(idx)
388            }
389            Literal::Color(c) => {
390                let hex = format!("#{:02x}{:02x}{:02x}{:02x}", c.r, c.g, c.b, c.a);
391                let idx = self.add_string(&hex)?;
392                self.emit_op(Op::PushString)?;
393                self.emit_u16(idx)
394            }
395        }
396    }
397
398    fn compile_binary(
399        &mut self,
400        op: &BinOp,
401        left: &Expr,
402        right: &Expr,
403    ) -> Result<(), CompileError> {
404        match op {
405            BinOp::And => {
406                // Short-circuit: if left is false, push false and skip right.
407                self.compile_expr(left)?;
408                self.emit_op(Op::Dup)?;
409                self.emit_op(Op::JumpIfFalse)?;
410                let skip = self.emit_placeholder()?;
411                // If we didn't jump, pop the duplicated false, eval right.
412                self.emit_op(Op::Pop)?;
413                self.compile_expr(right)?;
414                let after = self.chunk.current_offset();
415                self.patch(skip, after);
416                Ok(())
417            }
418            BinOp::Or => {
419                // Short-circuit: if left is true, push true and skip right.
420                self.compile_expr(left)?;
421                self.emit_op(Op::Dup)?;
422                self.emit_op(Op::JumpIfTrue)?;
423                let skip = self.emit_placeholder()?;
424                self.emit_op(Op::Pop)?;
425                self.compile_expr(right)?;
426                let after = self.chunk.current_offset();
427                self.patch(skip, after);
428                Ok(())
429            }
430            _ => {
431                self.compile_expr(left)?;
432                self.compile_expr(right)?;
433                let bc_op = match op {
434                    BinOp::Add => Op::Add,
435                    BinOp::Sub => Op::Sub,
436                    BinOp::Mul => Op::Mul,
437                    BinOp::Div => Op::Div,
438                    BinOp::Rem => Op::Rem,
439                    BinOp::Eq => Op::Eq,
440                    BinOp::Ne => Op::Ne,
441                    BinOp::Lt => Op::Lt,
442                    BinOp::Le => Op::Le,
443                    BinOp::Gt => Op::Gt,
444                    BinOp::Ge => Op::Ge,
445                    BinOp::And | BinOp::Or => unreachable!(),
446                };
447                self.emit_op(bc_op)
448            }
449        }
450    }
451
452    fn compile_unary(&mut self, op: &UnOp, expr: &Expr) -> Result<(), CompileError> {
453        self.compile_expr(expr)?;
454        match op {
455            UnOp::Neg => self.emit_op(Op::Neg),
456            UnOp::Not => self.emit_op(Op::Not),
457            UnOp::Plus => Ok(()), // no-op
458        }
459    }
460
461    fn compile_call(&mut self, callee: &Expr, args: &[Arg]) -> Result<(), CompileError> {
462        if super::task_admission::scoped_callee(callee, &self.aliases) {
463            return Err(CompileError::Unsupported(
464                "scoped task operation requires the admitted AST task runtime",
465            ));
466        }
467        // Determine if this is a builtin constructor, enum variant, user function, or host call.
468        let callee_name = callee.ident_name();
469
470        let mut pos_args = Vec::new();
471        let mut named_args = Vec::new();
472        for arg in args {
473            match arg {
474                Arg::Pos(e) => pos_args.push(e),
475                Arg::Named(na) => named_args.push(na),
476            }
477        }
478        if pos_args.len() > u8::MAX as usize || named_args.len() > u8::MAX as usize {
479            return Err(CompileError::Unsupported("more than 255 call arguments"));
480        }
481
482        // Builtin Result / Option constructors matching AST `eval/call.rs`.
483        if let Some(name @ ("Ok" | "Err" | "Some")) = callee_name {
484            if !named_args.is_empty() {
485                return Err(CompileError::Unsupported(
486                    "named arguments to builtin constructor",
487                ));
488            }
489            if let Some(first) = pos_args.first() {
490                self.compile_expr(first)?;
491            } else {
492                self.emit_op(Op::PushNull)?;
493            }
494            return match name {
495                "Ok" => self.emit_op(Op::MakeOk),
496                "Err" => self.emit_op(Op::MakeErr),
497                _ => Ok(()),
498            };
499        }
500
501        // Enum variant construction (`EnumName.Variant(args)`).
502        if let ExprKind::Member { recv, name: variant_name } = &callee.kind {
503            if let ExprKind::Ident(enum_name) = &recv.kind {
504                if let Some(enum_decl) = self.enums.get(enum_name).cloned() {
505                    if enum_decl.variants.iter().any(|v| v.name == *variant_name) {
506                        if !named_args.is_empty() {
507                            return Err(CompileError::Unsupported(
508                                "named arguments to enum variant constructor",
509                            ));
510                        }
511                        let enum_idx = self.add_string(enum_name)?;
512                        let var_idx = self.add_string(variant_name)?;
513                        for e in &pos_args {
514                            self.compile_expr(e)?;
515                        }
516                        self.emit_op(Op::MakeVariant)?;
517                        self.emit_u16(enum_idx)?;
518                        self.emit_u16(var_idx)?;
519                        return self.emit_u8(pos_args.len() as u8);
520                    }
521                }
522            }
523        }
524
525        // Check if it's a user-defined function.
526        if let Some(name) = callee_name {
527            if let Some(&fn_idx) = self.func_indices.get(name) {
528                if !named_args.is_empty() {
529                    return Err(CompileError::Unsupported(
530                        "named arguments to user function in bytecode",
531                    ));
532                }
533                for e in &pos_args {
534                    self.compile_expr(e)?;
535                }
536                self.emit_op(Op::CallUser)?;
537                self.emit_u16(fn_idx)?;
538                self.emit_u8(pos_args.len() as u8)?;
539                return Ok(());
540            }
541        }
542
543        // Otherwise, treat as a host/extension call. The callee path is a string constant.
544        // Supports both 2-level (`math.sqrt`, `mech.verlet_step`) and 3-level (`mech.kinematics.verlet_step`) paths.
545        let static_member_path;
546        let path = if let Some(name) = callee_name {
547            name
548        } else if let ExprKind::Member { recv, name } = &callee.kind {
549            match &recv.kind {
550                ExprKind::Ident(namespace) => {
551                    if self.lookup(namespace).is_some() {
552                        return Err(CompileError::Unsupported(
553                            "dynamic member callee; use the AST evaluator",
554                        ));
555                    }
556                    let namespace = self
557                        .aliases
558                        .get(namespace)
559                        .map(String::as_str)
560                        .unwrap_or(namespace);
561                    static_member_path = format!("{namespace}.{name}");
562                    &static_member_path
563                }
564                ExprKind::Member {
565                    recv: inner_recv,
566                    name: sub_name,
567                } => {
568                    let ExprKind::Ident(namespace) = &inner_recv.kind else {
569                        return Err(CompileError::Unsupported(
570                            "dynamic host callee; use the AST evaluator",
571                        ));
572                    };
573                    if self.lookup(namespace).is_some() {
574                        return Err(CompileError::Unsupported(
575                            "dynamic member callee; use the AST evaluator",
576                        ));
577                    }
578                    let namespace = self
579                        .aliases
580                        .get(namespace)
581                        .map(String::as_str)
582                        .unwrap_or(namespace);
583                    static_member_path = format!("{namespace}.{sub_name}.{name}");
584                    &static_member_path
585                }
586                _ => {
587                    return Err(CompileError::Unsupported(
588                        "dynamic host callee; use the AST evaluator",
589                    ))
590                }
591            }
592        } else {
593            return Err(CompileError::Unsupported(
594                "dynamic host callee; use the AST evaluator",
595            ));
596        };
597
598        let path_idx = self.add_string(path)?;
599        for e in &pos_args {
600            self.compile_expr(e)?;
601        }
602        if named_args.is_empty() {
603            self.emit_op(Op::CallHost)?;
604            self.emit_u16(path_idx)?;
605            self.emit_u8(pos_args.len() as u8)
606        } else {
607            for na in &named_args {
608                let key_idx = self.add_string(&na.name)?;
609                self.emit_op(Op::PushString)?;
610                self.emit_u16(key_idx)?;
611                self.compile_expr(&na.value)?;
612            }
613            self.emit_op(Op::CallHostNamed)?;
614            self.emit_u16(path_idx)?;
615            self.emit_u8(pos_args.len() as u8)?;
616            self.emit_u8(named_args.len() as u8)
617        }
618    }
619
620    // ── Statement compilation ────────────────────────────────────
621
622    fn compile_stmt(&mut self, stmt: &Stmt) -> Result<(), CompileError> {
623        match stmt {
624            Stmt::Let { name, value, .. } => {
625                if let Some(v) = value {
626                    self.compile_expr(v)?;
627                } else {
628                    self.emit_op(Op::PushNull)?;
629                }
630                let slot = self.declare_var(name)?;
631                self.emit_op(Op::StoreVar)?;
632                self.emit_u16(slot)
633            }
634            Stmt::LetPat { pattern, value, .. } => {
635                if let Pattern::Ident(name) = pattern {
636                    self.compile_expr(value)?;
637                    let slot = self.declare_var(name)?;
638                    self.emit_op(Op::StoreVar)?;
639                    self.emit_u16(slot)
640                } else {
641                    self.compile_expr(value)?;
642                    self.emit_op(Op::Dup)?;
643                    self.compile_pattern_check(pattern)?;
644                    self.emit_op(Op::JumpIfFalse)?;
645                    let fail_jump = self.emit_placeholder()?;
646                    self.compile_pattern_bind(pattern)?;
647                    self.emit_op(Op::Pop)?;
648                    self.emit_op(Op::Jump)?;
649                    let done_jump = self.emit_placeholder()?;
650                    let fail_off = self.chunk.current_offset();
651                    self.patch(fail_jump, fail_off);
652                    self.emit_op(Op::Pop)?;
653                    self.emit_op(Op::TrapMatch)?;
654                    let done_off = self.chunk.current_offset();
655                    self.patch(done_jump, done_off);
656                    Ok(())
657                }
658            }
659            Stmt::Assign { target, value, .. } => {
660                // Only simple variable assignment supported in 0.1 bytecode.
661                if let Some(name) = target.ident_name() {
662                    if let Some(slot) = self.lookup(name) {
663                        self.compile_expr(value)?;
664                        self.emit_op(Op::StoreVar)?;
665                        self.emit_u16(slot)?;
666                        Ok(())
667                    } else {
668                        Err(CompileError::Unsupported(
669                            "assignment to undeclared variable",
670                        ))
671                    }
672                } else {
673                    Err(CompileError::Unsupported("compound assignment target"))
674                }
675            }
676            Stmt::If {
677                cond,
678                then_block,
679                else_block,
680                ..
681            } => {
682                self.compile_expr(cond)?;
683                self.emit_op(Op::JumpIfFalse)?;
684                let else_jump = self.emit_placeholder()?;
685                self.compile_block(then_block)?;
686                if let Some(else_stmt) = else_block {
687                    // Jump over the else branch.
688                    self.emit_op(Op::Jump)?;
689                    let end_jump = self.emit_placeholder()?;
690                    // Patch else_jump to here.
691                    let else_start = self.chunk.current_offset();
692                    self.patch(else_jump, else_start);
693                    self.compile_stmt(else_stmt)?;
694                    let end = self.chunk.current_offset();
695                    self.patch(end_jump, end);
696                } else {
697                    let end = self.chunk.current_offset();
698                    self.patch(else_jump, end);
699                }
700                Ok(())
701            }
702            Stmt::For {
703                name, iter, body, ..
704            } => {
705                // For loop: store iter in a local, use index counter, loop
706                // fetching elements until GetIndex returns Null.
707                self.push_scope();
708                let list_slot = self.declare_var("__for_list")?;
709                let idx_slot = self.declare_var("__for_idx")?;
710                let elem_slot = self.declare_var(name)?;
711
712                // Store the iterator list.
713                self.compile_expr(iter)?;
714                self.emit_op(Op::StoreVar)?;
715                self.emit_u16(list_slot)?;
716
717                // Initialize index to 0.
718                self.emit_op(Op::PushInt)?;
719                self.emit_i64(0)?;
720                self.emit_op(Op::StoreVar)?;
721                self.emit_u16(idx_slot)?;
722
723                let loop_start = self.chunk.current_offset();
724
725                // Load list[idx] — VM returns Null for out-of-bounds.
726                self.emit_op(Op::LoadVar)?;
727                self.emit_u16(list_slot)?;
728                self.emit_op(Op::LoadVar)?;
729                self.emit_u16(idx_slot)?;
730                self.emit_op(Op::GetIndex)?;
731
732                // Check for Null (end of list).
733                self.emit_op(Op::Dup)?;
734                self.emit_op(Op::PushNull)?;
735                self.emit_op(Op::Eq)?;
736                self.emit_op(Op::JumpIfTrue)?;
737                let end_jump = self.emit_placeholder()?;
738
739                // Not null — store element to loop variable.
740                self.emit_op(Op::StoreVar)?;
741                self.emit_u16(elem_slot)?;
742
743                // Compile body.
744                self.loops.push(LoopCtx {
745                    continues: Vec::new(),
746                    breaks: Vec::new(),
747                });
748                self.compile_block(body)?;
749                let loop_ctx = self.loops.pop().unwrap();
750
751                // Increment index.
752                self.emit_op(Op::LoadVar)?;
753                self.emit_u16(idx_slot)?;
754                self.emit_op(Op::PushInt)?;
755                self.emit_i64(1)?;
756                self.emit_op(Op::Add)?;
757                self.emit_op(Op::StoreVar)?;
758                self.emit_u16(idx_slot)?;
759
760                // Patch continues to jump here (before the back-jump).
761                let continue_target = self.chunk.current_offset();
762                for pj in &loop_ctx.continues {
763                    self.patch(pj.operand_offset, continue_target);
764                }
765
766                // Jump back to loop start.
767                self.emit_op(Op::Jump)?;
768                self.emit_u16(loop_start)?;
769
770                // Loop end — patch end_jump and breaks.
771                let loop_end = self.chunk.current_offset();
772                self.patch(end_jump, loop_end);
773                for pj in &loop_ctx.breaks {
774                    self.patch(pj.operand_offset, loop_end);
775                }
776
777                // Pop the Null left on the stack from the end check.
778                self.emit_op(Op::Pop)?;
779
780                self.pop_scope();
781                Ok(())
782            }
783            Stmt::While { cond, body, .. } => {
784                let loop_start = self.chunk.current_offset();
785                self.compile_expr(cond)?;
786                self.emit_op(Op::JumpIfFalse)?;
787                let end_jump = self.emit_placeholder()?;
788
789                self.loops.push(LoopCtx {
790                    continues: Vec::new(),
791                    breaks: Vec::new(),
792                });
793                self.compile_block(body)?;
794                let loop_ctx = self.loops.pop().unwrap();
795
796                // Patch continues to loop start.
797                for pj in &loop_ctx.continues {
798                    self.patch(pj.operand_offset, loop_start);
799                }
800
801                // Jump back to condition.
802                self.emit_op(Op::Jump)?;
803                self.emit_u16(loop_start)?;
804
805                let loop_end = self.chunk.current_offset();
806                self.patch(end_jump, loop_end);
807                for pj in &loop_ctx.breaks {
808                    self.patch(pj.operand_offset, loop_end);
809                }
810                Ok(())
811            }
812            Stmt::Match {
813                scrutinee, arms, ..
814            } => {
815                // Match: compile scrutinee, then a chain of equality checks.
816                self.compile_expr(scrutinee)?;
817                let mut end_jumps: Vec<usize> = Vec::new();
818
819                for arm in arms {
820                    // Duplicate scrutinee for comparison.
821                    self.emit_op(Op::Dup)?;
822                    self.compile_pattern_check(&arm.pattern)?;
823                    self.emit_op(Op::JumpIfFalse)?;
824                    let next_jump = self.emit_placeholder()?;
825
826                    // Pattern matched — bind pattern variables from scrutinee before popping it.
827                    self.push_scope();
828                    self.compile_pattern_bind(&arm.pattern)?;
829                    self.emit_op(Op::Pop)?;
830                    // Compile arm body.
831                    match &arm.body {
832                        ArmBody::Block(b) => self.compile_block(b)?,
833                        ArmBody::Expr(e) => self.compile_expr(e)?,
834                    }
835                    self.pop_scope();
836                    // Jump to end.
837                    self.emit_op(Op::Jump)?;
838                    let end_jump = self.emit_placeholder()?;
839                    end_jumps.push(end_jump);
840
841                    // Patch next_jump to here.
842                    let next = self.chunk.current_offset();
843                    self.patch(next_jump, next);
844                }
845
846                // No arm matched — pop scrutinee, push null.
847                self.emit_op(Op::Pop)?;
848                self.emit_op(Op::PushNull)?;
849
850                let end = self.chunk.current_offset();
851                for ej in &end_jumps {
852                    self.patch(*ej, end);
853                }
854                Ok(())
855            }
856            Stmt::Return { value, .. } => {
857                if let Some(v) = value {
858                    self.compile_expr(v)?;
859                    self.emit_op(Op::Return)
860                } else {
861                    self.emit_op(Op::ReturnNull)
862                }
863            }
864            Stmt::Yield { value, .. } => {
865                // Yield in 0.1: evaluate and push (treated like return in generators).
866                if let Some(v) = value {
867                    self.compile_expr(v)?;
868                } else {
869                    self.emit_op(Op::PushNull)?;
870                }
871                self.emit_op(Op::Return)
872            }
873            Stmt::Transaction { body, .. } => {
874                // Transaction: compile body as a block. Transaction semantics
875                // are handled by the host.
876                self.compile_block(body)
877            }
878            Stmt::Effect { expr, .. } => {
879                self.compile_expr(expr)?;
880                self.emit_op(Op::Effect)
881            }
882            Stmt::Expr { expr, .. } => self.compile_expr(expr),
883            Stmt::Block(b) => self.compile_block(b),
884        }
885    }
886
887    /// Compile a pattern check — pushes a boolean indicating whether the
888    /// stack-top value matches the pattern, consuming the tested value.
889    fn compile_pattern_check(&mut self, pat: &Pattern) -> Result<(), CompileError> {
890        match pat {
891            Pattern::Wildcard | Pattern::Ident(_) => {
892                self.emit_op(Op::Pop)?;
893                self.emit_op(Op::PushBool)?;
894                self.emit_u8(1)
895            }
896            Pattern::Literal(lit) => {
897                self.compile_literal(lit)?;
898                self.emit_op(Op::Eq)
899            }
900            Pattern::None => {
901                self.compile_literal(&Literal::Null)?;
902                self.emit_op(Op::Eq)
903            }
904            Pattern::Some(inner) => {
905                self.emit_op(Op::Dup)?;
906                self.emit_op(Op::PushNull)?;
907                self.emit_op(Op::Ne)?;
908                self.emit_op(Op::JumpIfFalse)?;
909                let fail_jump = self.emit_placeholder()?;
910                self.compile_pattern_check(inner)?;
911                self.emit_op(Op::Jump)?;
912                let done_jump = self.emit_placeholder()?;
913                let fail_off = self.chunk.current_offset();
914                self.patch(fail_jump, fail_off);
915                self.emit_op(Op::Pop)?;
916                self.emit_op(Op::PushBool)?;
917                self.emit_u8(0)?;
918                let done_off = self.chunk.current_offset();
919                self.patch(done_jump, done_off);
920                Ok(())
921            }
922            Pattern::Ok(inner) => self.compile_wrapped_pattern_check(Op::IsOk, Op::UnwrapOk, inner),
923            Pattern::Err(inner) => {
924                self.compile_wrapped_pattern_check(Op::IsErr, Op::UnwrapErr, inner)
925            }
926            Pattern::Record(fields) => self.compile_record_pattern_check(fields),
927            Pattern::List(elements) => self.compile_list_pattern_check(elements),
928            Pattern::Constructor { name, args } => {
929                if matches!(name.as_str(), "vec2" | "vec3" | "vec4" | "mat3" | "mat4") {
930                    self.compile_list_pattern_check(args)
931                } else {
932                    self.emit_op(Op::Pop)?;
933                    self.emit_op(Op::PushBool)?;
934                    self.emit_u8(0)
935                }
936            }
937            Pattern::Variant {
938                enum_name,
939                variant_name,
940                args,
941            } => self.compile_variant_pattern_check(enum_name, variant_name, args),
942        }
943    }
944
945    fn compile_wrapped_pattern_check(
946        &mut self,
947        tag_op: Op,
948        unwrap_op: Op,
949        inner: &Pattern,
950    ) -> Result<(), CompileError> {
951        self.emit_op(Op::Dup)?;
952        self.emit_op(tag_op)?;
953        self.emit_op(Op::JumpIfFalse)?;
954        let fail_jump = self.emit_placeholder()?;
955        self.emit_op(unwrap_op)?;
956        self.compile_pattern_check(inner)?;
957        self.emit_op(Op::Jump)?;
958        let done_jump = self.emit_placeholder()?;
959        let fail_off = self.chunk.current_offset();
960        self.patch(fail_jump, fail_off);
961        self.emit_op(Op::Pop)?;
962        self.emit_op(Op::PushBool)?;
963        self.emit_u8(0)?;
964        let done_off = self.chunk.current_offset();
965        self.patch(done_jump, done_off);
966        Ok(())
967    }
968
969    fn compile_list_pattern_check(&mut self, elements: &[Pattern]) -> Result<(), CompileError> {
970        if elements.len() > u16::MAX as usize {
971            return Err(CompileError::CodeTooLarge);
972        }
973        let mut fail_jumps = Vec::with_capacity(elements.len() + 1);
974        self.emit_op(Op::Dup)?;
975        self.emit_op(Op::IsListLen)?;
976        self.emit_u16(elements.len() as u16)?;
977        self.emit_op(Op::JumpIfFalse)?;
978        fail_jumps.push(self.emit_placeholder()?);
979        for (i, pat) in elements.iter().enumerate() {
980            self.emit_op(Op::Dup)?;
981            self.emit_op(Op::PushInt)?;
982            self.emit_i64(i as i64)?;
983            self.emit_op(Op::GetIndex)?;
984            self.compile_pattern_check(pat)?;
985            self.emit_op(Op::JumpIfFalse)?;
986            fail_jumps.push(self.emit_placeholder()?);
987        }
988        self.emit_op(Op::Pop)?;
989        self.emit_op(Op::PushBool)?;
990        self.emit_u8(1)?;
991        self.emit_op(Op::Jump)?;
992        let done_jump = self.emit_placeholder()?;
993        let fail_off = self.chunk.current_offset();
994        for fj in fail_jumps {
995            self.patch(fj, fail_off);
996        }
997        self.emit_op(Op::Pop)?;
998        self.emit_op(Op::PushBool)?;
999        self.emit_u8(0)?;
1000        let done_off = self.chunk.current_offset();
1001        self.patch(done_jump, done_off);
1002        Ok(())
1003    }
1004
1005    fn compile_record_pattern_check(
1006        &mut self,
1007        fields: &[(String, Pattern)],
1008    ) -> Result<(), CompileError> {
1009        let mut fail_jumps = Vec::with_capacity(fields.len() * 2 + 1);
1010        self.emit_op(Op::Dup)?;
1011        self.emit_op(Op::IsRecord)?;
1012        self.emit_op(Op::JumpIfFalse)?;
1013        fail_jumps.push(self.emit_placeholder()?);
1014        for (key, pat) in fields {
1015            let key_idx = self.add_string(key)?;
1016            self.emit_op(Op::Dup)?;
1017            self.emit_op(Op::HasMember)?;
1018            self.emit_u16(key_idx)?;
1019            self.emit_op(Op::JumpIfFalse)?;
1020            fail_jumps.push(self.emit_placeholder()?);
1021            self.emit_op(Op::Dup)?;
1022            self.emit_op(Op::GetMember)?;
1023            self.emit_u16(key_idx)?;
1024            self.compile_pattern_check(pat)?;
1025            self.emit_op(Op::JumpIfFalse)?;
1026            fail_jumps.push(self.emit_placeholder()?);
1027        }
1028        self.emit_op(Op::Pop)?;
1029        self.emit_op(Op::PushBool)?;
1030        self.emit_u8(1)?;
1031        self.emit_op(Op::Jump)?;
1032        let done_jump = self.emit_placeholder()?;
1033        let fail_off = self.chunk.current_offset();
1034        for fj in fail_jumps {
1035            self.patch(fj, fail_off);
1036        }
1037        self.emit_op(Op::Pop)?;
1038        self.emit_op(Op::PushBool)?;
1039        self.emit_u8(0)?;
1040        let done_off = self.chunk.current_offset();
1041        self.patch(done_jump, done_off);
1042        Ok(())
1043    }
1044
1045    fn compile_variant_pattern_check(
1046        &mut self,
1047        enum_name: &str,
1048        variant_name: &str,
1049        args: &[Pattern],
1050    ) -> Result<(), CompileError> {
1051        if args.len() > u8::MAX as usize {
1052            return Err(CompileError::CodeTooLarge);
1053        }
1054        let enum_idx = self.add_string(enum_name)?;
1055        let var_idx = self.add_string(variant_name)?;
1056        let mut fail_jumps = Vec::with_capacity(args.len() + 1);
1057        self.emit_op(Op::Dup)?;
1058        self.emit_op(Op::IsVariant)?;
1059        self.emit_u16(enum_idx)?;
1060        self.emit_u16(var_idx)?;
1061        self.emit_u8(args.len() as u8)?;
1062        self.emit_op(Op::JumpIfFalse)?;
1063        fail_jumps.push(self.emit_placeholder()?);
1064        for (i, pat) in args.iter().enumerate() {
1065            self.emit_op(Op::Dup)?;
1066            self.emit_op(Op::GetVariantField)?;
1067            self.emit_u8(i as u8)?;
1068            self.compile_pattern_check(pat)?;
1069            self.emit_op(Op::JumpIfFalse)?;
1070            fail_jumps.push(self.emit_placeholder()?);
1071        }
1072        self.emit_op(Op::Pop)?;
1073        self.emit_op(Op::PushBool)?;
1074        self.emit_u8(1)?;
1075        self.emit_op(Op::Jump)?;
1076        let done_jump = self.emit_placeholder()?;
1077        let fail_off = self.chunk.current_offset();
1078        for fj in fail_jumps {
1079            self.patch(fj, fail_off);
1080        }
1081        self.emit_op(Op::Pop)?;
1082        self.emit_op(Op::PushBool)?;
1083        self.emit_u8(0)?;
1084        let done_off = self.chunk.current_offset();
1085        self.patch(done_jump, done_off);
1086        Ok(())
1087    }
1088
1089    /// Bind pattern variables to the value on top of the stack.
1090    /// Preserves the matched value on top of the stack for caller cleanup.
1091    fn compile_pattern_bind(&mut self, pat: &Pattern) -> Result<(), CompileError> {
1092        match pat {
1093            Pattern::Ident(name) => {
1094                self.emit_op(Op::Dup)?;
1095                let slot = self.declare_var(name)?;
1096                self.emit_op(Op::StoreVar)?;
1097                self.emit_u16(slot)
1098            }
1099            Pattern::Wildcard | Pattern::Literal(_) | Pattern::None => Ok(()),
1100            Pattern::Some(inner) => self.compile_pattern_bind(inner),
1101            Pattern::Ok(inner) => {
1102                self.emit_op(Op::Dup)?;
1103                self.emit_op(Op::UnwrapOk)?;
1104                self.compile_pattern_bind(inner)?;
1105                self.emit_op(Op::Pop)
1106            }
1107            Pattern::Err(inner) => {
1108                self.emit_op(Op::Dup)?;
1109                self.emit_op(Op::UnwrapErr)?;
1110                self.compile_pattern_bind(inner)?;
1111                self.emit_op(Op::Pop)
1112            }
1113            Pattern::Record(fields) => {
1114                for (key, p) in fields {
1115                    let key_idx = self.add_string(key)?;
1116                    self.emit_op(Op::Dup)?;
1117                    self.emit_op(Op::GetMember)?;
1118                    self.emit_u16(key_idx)?;
1119                    self.compile_pattern_bind(p)?;
1120                    self.emit_op(Op::Pop)?;
1121                }
1122                Ok(())
1123            }
1124            Pattern::List(elements) | Pattern::Constructor { args: elements, .. } => {
1125                for (i, p) in elements.iter().enumerate() {
1126                    self.emit_op(Op::Dup)?;
1127                    self.emit_op(Op::PushInt)?;
1128                    self.emit_i64(i as i64)?;
1129                    self.emit_op(Op::GetIndex)?;
1130                    self.compile_pattern_bind(p)?;
1131                    self.emit_op(Op::Pop)?;
1132                }
1133                Ok(())
1134            }
1135            Pattern::Variant { args, .. } => {
1136                for (i, p) in args.iter().enumerate() {
1137                    self.emit_op(Op::Dup)?;
1138                    self.emit_op(Op::GetVariantField)?;
1139                    self.emit_u8(i as u8)?;
1140                    self.compile_pattern_bind(p)?;
1141                    self.emit_op(Op::Pop)?;
1142                }
1143                Ok(())
1144            }
1145        }
1146    }
1147
1148    fn compile_block(&mut self, block: &Block) -> Result<(), CompileError> {
1149        self.push_scope();
1150        for stmt in &block.stmts {
1151            self.compile_stmt(stmt)?;
1152        }
1153        self.pop_scope();
1154        Ok(())
1155    }
1156
1157    // ── Function compilation ─────────────────────────────────────
1158
1159    fn compile_function(
1160        &mut self,
1161        fd: &FunctionDecl,
1162        func_iter: usize,
1163    ) -> Result<(), CompileError> {
1164        let code_offset = self.chunk.current_offset();
1165
1166        // Reset local counter and scope frame for this function.
1167        // Each function has its own local slot space starting at 0.
1168        let saved_next_local = self.next_local;
1169        let saved_local_base = self.local_base;
1170        let saved_scopes = std::mem::replace(&mut self.scopes, vec![HashMap::new()]);
1171        self.next_local = 0;
1172        self.local_base = 1;
1173
1174        for p in &fd.params {
1175            self.declare_var(&p.name)?;
1176        }
1177
1178        // Compile body first so every local declared inside the function
1179        // (including loop/match temporaries) is included in `local_count`.
1180        let compile_res = self.compile_block(&fd.body);
1181        let local_count = self.next_local;
1182
1183        self.scopes = saved_scopes;
1184        self.local_base = saved_local_base;
1185        self.next_local = saved_next_local;
1186        compile_res?;
1187
1188        // Every forward edge patched to the function's current end needs a real
1189        // landing instruction, even when a branch ends in Return. A raw last byte
1190        // may also be an operand rather than an opcode. Explicit returns bypass
1191        // this harmless fallback; fallthrough cannot enter the next function.
1192        self.emit_op(Op::ReturnNull)?;
1193
1194        // Parse budget steps if present.
1195        let budget_steps = fd
1196            .budget
1197            .iter()
1198            .find(|a| a.name == "steps")
1199            .and_then(|a| match &a.value.kind {
1200                ExprKind::Literal(Literal::UInt(n)) => Some(*n),
1201                ExprKind::Literal(Literal::Int(n)) if *n >= 0 => Some(*n as u64),
1202                _ => None,
1203            })
1204            .unwrap_or(0);
1205
1206        // Record/update function metadata.
1207        self.chunk.functions[func_iter].code_offset = code_offset;
1208        self.chunk.functions[func_iter].local_count = local_count;
1209        self.chunk.functions[func_iter].budget_steps = budget_steps;
1210
1211        Ok(())
1212    }
1213
1214    // ── Program compilation ──────────────────────────────────────
1215
1216    fn compile_program(&mut self, program: &Program) -> Result<&Chunk, CompileError> {
1217        for req in &program.requires {
1218            if req.id.trim().is_empty() {
1219                return Err(CompileError::Unsupported(
1220                    "empty capability requirement in bytecode program",
1221                ));
1222            }
1223        }
1224        for import in &program.imports {
1225            let namespace = import
1226                .path
1227                .strip_prefix("vibe:0.1/")
1228                .unwrap_or(&import.path);
1229            self.aliases.insert(
1230                import.alias.as_deref().unwrap_or(namespace).to_string(),
1231                namespace.to_string(),
1232            );
1233        }
1234        // First pass: register enums and all function names so calls can resolve
1235        // even if a function is called before its definition.
1236        for item in &program.items {
1237            match item {
1238                Item::Enum(ed) => {
1239                    self.enums.insert(ed.name.clone(), ed.clone());
1240                }
1241                Item::Function(fd) => {
1242                    if fd.params.len() > u8::MAX as usize {
1243                        return Err(CompileError::Unsupported(
1244                            "more than 255 function parameters",
1245                        ));
1246                    }
1247                    if self.chunk.functions.len() >= crate::bytecode::op::MAX_FUNCTIONS {
1248                        return Err(CompileError::TooManyFunctions);
1249                    }
1250                    let idx = self.chunk.functions.len() as u16;
1251                    self.func_indices.insert(fd.name.clone(), idx);
1252                    // Reserve a FuncMeta slot — we'll fill it in the third pass.
1253                    self.chunk.functions.push(FuncMeta {
1254                        name: fd.name.clone(),
1255                        param_count: fd.params.len() as u8,
1256                        local_count: 0,
1257                        code_offset: 0, // placeholder
1258                        budget_steps: 0,
1259                    });
1260                }
1261                _ => {}
1262            }
1263        }
1264
1265        // Second pass: compile top-level statements and functions.
1266        // Top-level statements go into the preamble (before function code).
1267        // Functions are compiled after.
1268
1269        // First, compile top-level statements (consts, top-level stmts).
1270        for item in &program.items {
1271            match item {
1272                Item::Const(cd) => {
1273                    self.compile_expr(&cd.value)?;
1274                    let slot = self.declare_var(&cd.name)?;
1275                    self.emit_op(Op::StoreVar)?;
1276                    self.emit_u16(slot)?;
1277                }
1278                Item::Cell(cd) => {
1279                    self.compile_expr(&cd.expr)?;
1280                    let slot = self.declare_var(&cd.name)?;
1281                    self.emit_op(Op::StoreVar)?;
1282                    self.emit_u16(slot)?;
1283                }
1284                Item::Statement(stmt) => {
1285                    self.compile_stmt(stmt)?;
1286                }
1287                Item::Function(_) | Item::Enum(_) => {}
1288                Item::Hook(_)
1289                | Item::Field(_)
1290                | Item::Material(_)
1291                | Item::Law(_)
1292                | Item::Present(_)
1293                | Item::Bind(_) => {
1294                    return Err(CompileError::Unsupported(
1295                        "hooks/fields/materials/laws/present/bind require the AST evaluator",
1296                    ));
1297                }
1298            }
1299        }
1300
1301        // Emit Halt after the preamble.
1302        self.emit_op(Op::Halt)?;
1303
1304        // Now compile functions, updating their code_offset.
1305        let mut func_iter = 0;
1306        for item in &program.items {
1307            if let Item::Function(fd) = item {
1308                self.compile_function(fd, func_iter)?;
1309                func_iter += 1;
1310            }
1311        }
1312
1313        Ok(&self.chunk)
1314    }
1315}
1316
1317/// Compile a full `Program` AST into a `Chunk`.
1318pub fn compile(program: &Program) -> Result<Chunk, CompileError> {
1319    let mut compiler = Compiler::new();
1320    let chunk = compiler.compile_program(program)?;
1321    super::task_admission::validate(chunk).map_err(|_| {
1322        CompileError::Unsupported("bytecode runtime admission failed; use the AST evaluator")
1323    })?;
1324    Ok(chunk.clone())
1325}
1326
1327/// Compile a single expression (for cell bodies) into a `Chunk`.
1328/// The chunk's preamble evaluates the expression and returns it.
1329pub fn compile_expr(expr: &Expr) -> Result<Chunk, CompileError> {
1330    let mut compiler = Compiler::new();
1331    compiler.compile_expr(expr)?;
1332    compiler.emit_op(Op::Return)?;
1333    super::task_admission::validate(&compiler.chunk).map_err(|_| {
1334        CompileError::Unsupported("bytecode runtime admission failed; use the AST evaluator")
1335    })?;
1336    Ok(compiler.chunk)
1337}
1338
1339#[cfg(test)]
1340mod tests {
1341    use super::*;
1342    use crate::bytecode::op::Const;
1343    use crate::parse::parse_program;
1344
1345    fn compile_src(src: &str) -> Result<Chunk, CompileError> {
1346        let prog = parse_program(src).expect("parse should succeed");
1347        compile(&prog)
1348    }
1349
1350    #[test]
1351    fn compile_simple_arithmetic() {
1352        // Cell expression: 1 + 2 * 3
1353        let chunk = compile_expr(&crate::parse::parse_cell("= 1 + 2 * 3").expect("parse"))
1354            .expect("compile");
1355        // Should contain: PushInt(1), PushInt(2), PushInt(3), Mul, Add, Return
1356        assert!(chunk.code.contains(&(Op::PushInt as u8)));
1357        assert!(chunk.code.contains(&(Op::Mul as u8)));
1358        assert!(chunk.code.contains(&(Op::Add as u8)));
1359        assert_eq!(*chunk.code.last().unwrap(), Op::Return as u8);
1360    }
1361
1362    #[test]
1363    fn compile_let_and_return() {
1364        let src = "fn add(a: i64, b: i64) -> i64 { let s = a + b; return s; }";
1365        let chunk = compile_src(src).expect("compile");
1366        assert!(chunk.code.contains(&(Op::StoreVar as u8)));
1367        assert!(chunk.code.contains(&(Op::Return as u8)));
1368        assert_eq!(chunk.functions.len(), 1);
1369        assert_eq!(chunk.functions[0].name, "add");
1370        assert_eq!(chunk.functions[0].param_count, 2);
1371    }
1372
1373    #[test]
1374    fn compile_if_else() {
1375        let src = "fn f(x: i64) -> i64 { if x > 0 { return 1; } else { return 0; } }";
1376        let chunk = compile_src(src).expect("compile");
1377        assert!(chunk.code.contains(&(Op::JumpIfFalse as u8)));
1378        assert!(chunk.code.contains(&(Op::Jump as u8)));
1379    }
1380
1381    #[test]
1382    fn compile_while_loop() {
1383        let src =
1384            "fn f() budget(steps: 100) -> i64 { let i = 0; while i < 10 { i = i + 1; } return i; }";
1385        let chunk = compile_src(src).expect("compile");
1386        assert!(chunk.code.contains(&(Op::JumpIfFalse as u8)));
1387        assert!(chunk.code.contains(&(Op::Jump as u8)));
1388        assert_eq!(chunk.functions[0].budget_steps, 100);
1389    }
1390
1391    #[test]
1392    fn compile_list_literal() {
1393        let chunk = compile_expr(&crate::parse::parse_cell("= [1, 2, 3]").expect("parse"))
1394            .expect("compile");
1395        assert!(chunk.code.contains(&(Op::MakeList as u8)));
1396    }
1397
1398    #[test]
1399    fn compile_record_literal() {
1400        let chunk = compile_expr(&crate::parse::parse_cell("= { x: 1, y: 2 }").expect("parse"))
1401            .expect("compile");
1402        assert!(chunk.code.contains(&(Op::MakeRecord as u8)));
1403    }
1404
1405    #[test]
1406    fn compile_string_constant_dedup() {
1407        let chunk = compile_expr(&crate::parse::parse_cell(r#"= "hello""#).expect("parse"))
1408            .expect("compile");
1409        assert!(!chunk.constants.is_empty());
1410        if let Some(Const::String(s)) = chunk.constants.first() {
1411            assert_eq!(s, "hello");
1412        } else {
1413            panic!("expected string constant");
1414        }
1415    }
1416
1417    #[test]
1418    fn compile_function_call() {
1419        let src =
1420            "fn double(x: i64) -> i64 { return x + x; } fn main() -> i64 { return double(5); }";
1421        let chunk = compile_src(src).expect("compile");
1422        assert!(chunk.code.contains(&(Op::CallUser as u8)));
1423        assert_eq!(chunk.functions.len(), 2);
1424    }
1425
1426    #[test]
1427    fn compile_host_call() {
1428        let src = "fn f() -> f64 { return math.sqrt(16.0); }";
1429        let chunk = compile_src(src).expect("compile");
1430        assert!(chunk.code.contains(&(Op::CallHost as u8)));
1431    }
1432
1433    #[test]
1434    fn compile_for_loop() {
1435        let src = "fn f() budget(steps: 100) -> i64 { let s = 0; for x in [1, 2, 3] { s = s + x; } return s; }";
1436        let chunk = compile_src(src).expect("compile");
1437        assert!(chunk.code.contains(&(Op::GetIndex as u8)));
1438        assert!(chunk.code.contains(&(Op::Jump as u8)));
1439    }
1440
1441    #[test]
1442    fn compile_logical_and() {
1443        let chunk = compile_expr(&crate::parse::parse_cell("= true && false").expect("parse"))
1444            .expect("compile");
1445        assert!(chunk.code.contains(&(Op::Dup as u8)));
1446        assert!(chunk.code.contains(&(Op::JumpIfFalse as u8)));
1447    }
1448
1449    #[test]
1450    fn compile_match() {
1451        let src = "fn f(x: i64) -> i64 { match x { 1 => { return 10; } _ => { return 0; } } }";
1452        let chunk = compile_src(src).expect("compile");
1453        assert!(chunk.code.contains(&(Op::Eq as u8)));
1454        assert!(chunk.code.contains(&(Op::JumpIfFalse as u8)));
1455    }
1456
1457    #[test]
1458    fn compile_quantity_keeps_unit_opcode() {
1459        let chunk =
1460            compile_expr(&crate::parse::parse_cell("= 500ms").expect("parse")).expect("compile");
1461        assert!(
1462            chunk.code.contains(&(Op::PushQuantity as u8)),
1463            "quantity literal must emit PushQuantity, not a bare float"
1464        );
1465        let has_unit = chunk.constants.iter().any(|c| match c {
1466            Const::String(s) => s == "ms",
1467            _ => false,
1468        });
1469        assert!(has_unit, "unit string must stay in the constant pool");
1470    }
1471}