1use crate::bind::Host;
8use crate::budget::Budget;
9use crate::bytecode::op::{Chunk, Const, Op};
10use crate::error::{DiagCode, Diagnostic};
11use crate::extension_registry::{
12 route_call, CallExecutionContext, DispatchOutcome, ExtensionRegistry, PreparedCallCache,
13};
14use crate::span::Span;
15use crate::value::{EnumValue, Value};
16use std::collections::BTreeMap;
17use vibescript_abi::{q_hash_str, ExecutionMode, SentinelPolicyGate};
18
19#[derive(Debug, Clone, PartialEq)]
21pub enum VmError {
22 Diagnostic(Diagnostic),
24 StackUnderflow,
26 StackOverflow,
28 InvalidOpcode(u8),
30 CodeOutOfBounds,
32 InvalidConstant(u16),
34 InvalidFunction(u16),
36 InvalidLocal(u16),
38 DivisionByZero,
40 BudgetExhausted,
42 TypeMismatch(&'static str),
44 NoReturnValue,
46}
47
48impl std::fmt::Display for VmError {
49 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50 match self {
51 Self::Diagnostic(d) => write!(f, "{d}"),
52 Self::StackUnderflow => write!(f, "vm: stack underflow"),
53 Self::StackOverflow => write!(f, "vm: stack overflow"),
54 Self::InvalidOpcode(b) => write!(f, "vm: invalid opcode 0x{b:02X}"),
55 Self::CodeOutOfBounds => write!(f, "vm: code pointer out of bounds"),
56 Self::InvalidConstant(i) => write!(f, "vm: invalid constant index {i}"),
57 Self::InvalidFunction(i) => write!(f, "vm: invalid function index {i}"),
58 Self::InvalidLocal(i) => write!(f, "vm: invalid local slot {i}"),
59 Self::DivisionByZero => write!(f, "vm: division by zero"),
60 Self::BudgetExhausted => write!(f, "vm: budget exhausted"),
61 Self::TypeMismatch(what) => write!(f, "vm: type mismatch: {what}"),
62 Self::NoReturnValue => write!(f, "vm: no return value"),
63 }
64 }
65}
66
67impl std::error::Error for VmError {}
68
69impl From<Diagnostic> for VmError {
70 fn from(d: Diagnostic) -> Self {
71 Self::Diagnostic(d)
72 }
73}
74
75const MAX_STACK: usize = 1024;
76
77pub struct Vm<'a, H: Host> {
79 chunk: &'a Chunk,
80 host: &'a mut H,
81 budget: Budget,
82 stack: Vec<Value>,
84 frames: Vec<Frame>,
86 extension_registry: ExtensionRegistry<'a>,
88 prepared_cache: PreparedCallCache,
90 call_context: CallExecutionContext,
92 sentinel_gate: Option<&'a mut dyn SentinelPolicyGate>,
94 last_extension_outcome: Option<DispatchOutcome>,
96}
97
98struct Frame {
100 return_pc: usize,
102 locals: Vec<Value>,
104}
105
106impl<'a, H: Host> Vm<'a, H> {
107 pub fn new(chunk: &'a Chunk, host: &'a mut H, budget: Budget) -> Self {
109 Self {
110 chunk,
111 host,
112 budget,
113 stack: Vec::with_capacity(256),
114 frames: Vec::new(),
115 extension_registry: ExtensionRegistry::with_builtin_providers(),
116 prepared_cache: PreparedCallCache::new(),
117 call_context: CallExecutionContext {
118 actor_did_hash: q_hash_str("did:q42:local_vm"),
119 context_world_hash: 1,
120 lamport_timestamp: 1,
121 mode: ExecutionMode::StandaloneDeveloper,
122 },
123 sentinel_gate: None,
124 last_extension_outcome: None,
125 }
126 }
127
128 pub fn with_extension_governance(
130 mut self,
131 call_context: CallExecutionContext,
132 sentinel_gate: Option<&'a mut dyn SentinelPolicyGate>,
133 ) -> Self {
134 self.call_context = call_context;
135 self.sentinel_gate = sentinel_gate;
136 self
137 }
138
139 pub fn extension_registry_mut(&mut self) -> &mut ExtensionRegistry<'a> {
141 &mut self.extension_registry
142 }
143
144 pub fn last_extension_outcome(&self) -> Option<&DispatchOutcome> {
146 self.last_extension_outcome.as_ref()
147 }
148
149 pub fn run(&mut self) -> Result<Value, VmError> {
151 super::task_admission::validate(self.chunk)?;
152 let mut pc: usize = 0;
153 let top_locals = vec![Value::Null; self.chunk.top_locals as usize];
155 self.frames.push(Frame {
156 return_pc: usize::MAX,
157 locals: top_locals,
158 });
159
160 loop {
161 self.budget.tick(Span::new(0, 0)).map_err(VmError::from)?;
162 let op_byte = self.read_u8(&mut pc)?;
163 let op = Op::from_byte(op_byte).ok_or(VmError::InvalidOpcode(op_byte))?;
164
165 if op == Op::Return {
167 self.frames.pop();
168 break;
169 }
170 if op == Op::ReturnNull {
171 self.frames.pop();
172 self.push(Value::Null)?;
173 break;
174 }
175
176 self.exec_op(op, &mut pc)?;
177
178 if op == Op::Halt {
179 break;
180 }
181 }
182
183 if let Some(v) = self.stack.pop() {
185 Ok(v)
186 } else {
187 Ok(Value::Null)
188 }
189 }
190
191 pub fn call_function(&mut self, fn_idx: u16, args: &[Value]) -> Result<Value, VmError> {
193 super::task_admission::validate(self.chunk)?;
194 let meta = self
195 .chunk
196 .functions
197 .get(fn_idx as usize)
198 .ok_or(VmError::InvalidFunction(fn_idx))?
199 .clone();
200
201 if meta.budget_steps > 0 {
202 self.budget.steps_left = self.budget.steps_left.min(meta.budget_steps);
203 }
204
205 let mut locals = vec![Value::Null; meta.local_count as usize];
206 for (i, arg) in args.iter().enumerate() {
207 if i < meta.param_count as usize && i < locals.len() {
208 locals[i] = arg.clone();
209 }
210 }
211
212 self.frames.push(Frame {
214 return_pc: usize::MAX,
215 locals,
216 });
217
218 let mut pc = meta.code_offset as usize;
219 self.exec_function_body(&mut pc)
220 }
221
222 fn exec_function_body(&mut self, pc: &mut usize) -> Result<Value, VmError> {
223 loop {
224 self.budget.tick(Span::new(0, 0)).map_err(VmError::from)?;
225 let op_byte = self.read_u8(pc)?;
226 let op = Op::from_byte(op_byte).ok_or(VmError::InvalidOpcode(op_byte))?;
227
228 match op {
229 Op::Return => {
230 let v = self.pop()?;
231 self.frames.pop();
232 return Ok(v);
233 }
234 Op::ReturnNull => {
235 self.frames.pop();
236 return Ok(Value::Null);
237 }
238 _ => self.exec_op(op, pc)?,
239 }
240 }
241 }
242
243 fn exec_op(&mut self, op: Op, pc: &mut usize) -> Result<(), VmError> {
244 match op {
245 Op::PushNull => self.push(Value::Null),
246 Op::PushBool => {
247 let b = self.read_u8(pc)?;
248 self.push(Value::Bool(b != 0))
249 }
250 Op::PushInt => {
251 let v = self.read_i64(pc)?;
252 self.push(Value::I64(v))
253 }
254 Op::PushUInt => {
255 let v = self.read_u64(pc)?;
256 self.push(Value::U64(v))
257 }
258 Op::PushFloat => {
259 let bits = self.read_u64(pc)?;
260 self.push(Value::F64(f64::from_bits(bits)))
261 }
262 Op::PushQuantity => {
263 let bits = self.read_u64(pc)?;
264 let idx = self.read_u16(pc)?;
265 let unit = self.get_string_const(idx)?;
266 self.push(Value::Quantity(crate::value::Quantity {
267 value: f64::from_bits(bits),
268 unit,
269 }))
270 }
271 Op::PushString => {
272 let idx = self.read_u16(pc)?;
273 let s = self.get_string_const(idx)?;
274 self.push(Value::String(s))
275 }
276 Op::PushIri => {
277 let idx = self.read_u16(pc)?;
278 let s = self.get_iri_const(idx)?;
279 self.push(Value::Iri(s))
280 }
281 Op::LoadVar => {
282 let slot = self.read_u16(pc)?;
283 let v = self.load_local(slot)?;
284 self.push(v)
285 }
286 Op::StoreVar => {
287 let slot = self.read_u16(pc)?;
288 let v = self.pop()?;
289 self.store_local(slot, v)
290 }
291 Op::Pop => {
292 self.pop()?;
293 Ok(())
294 }
295 Op::Dup => {
296 let v = self.peek()?.clone();
297 self.push(v)
298 }
299
300 Op::Add => self.binop_num(
302 |a, b| a + b,
303 |a, b| a + b,
304 |a, b| a + b,
305 |a, b| a.wrapping_add(b),
306 ),
307 Op::Sub => self.binop_num(
308 |a, b| a - b,
309 |a, b| a - b,
310 |a, b| a - b,
311 |a, b| a.wrapping_sub(b),
312 ),
313 Op::Mul => self.binop_num(
314 |a, b| a * b,
315 |a, b| a * b,
316 |a, b| a * b,
317 |a, b| a.wrapping_mul(b),
318 ),
319 Op::Div => {
320 let b = self.pop()?;
321 let a = self.pop()?;
322 self.div_op(a, b)
323 }
324 Op::Rem => {
325 let b = self.pop()?;
326 let a = self.pop()?;
327 self.rem_op(a, b)
328 }
329 Op::Neg => {
330 let a = self.pop()?;
331 match a {
332 Value::I64(v) => self.push(Value::I64(-v)),
333 Value::F64(v) => self.push(Value::F64(-v)),
334 Value::U64(v) => self.push(Value::I64(-(v as i64))),
335 _ => Err(VmError::TypeMismatch("neg")),
336 }
337 }
338 Op::Not => {
339 let a = self.pop()?;
340 match a {
341 Value::Bool(b) => self.push(Value::Bool(!b)),
342 _ => Err(VmError::TypeMismatch("not")),
343 }
344 }
345
346 Op::Eq => {
348 let b = self.pop()?;
349 let a = self.pop()?;
350 self.push(Value::Bool(a == b))
351 }
352 Op::Ne => {
353 let b = self.pop()?;
354 let a = self.pop()?;
355 self.push(Value::Bool(a != b))
356 }
357 Op::Lt => self.cmp_op(|o| o == std::cmp::Ordering::Less),
358 Op::Le => self.cmp_op(|o| o != std::cmp::Ordering::Greater),
359 Op::Gt => self.cmp_op(|o| o == std::cmp::Ordering::Greater),
360 Op::Ge => self.cmp_op(|o| o != std::cmp::Ordering::Less),
361 Op::And => {
362 let b = self.pop()?;
363 let a = self.pop()?;
364 match (a, b) {
365 (Value::Bool(x), Value::Bool(y)) => self.push(Value::Bool(x && y)),
366 _ => Err(VmError::TypeMismatch("and")),
367 }
368 }
369 Op::Or => {
370 let b = self.pop()?;
371 let a = self.pop()?;
372 match (a, b) {
373 (Value::Bool(x), Value::Bool(y)) => self.push(Value::Bool(x || y)),
374 _ => Err(VmError::TypeMismatch("or")),
375 }
376 }
377
378 Op::Jump => {
380 let target = self.read_u16(pc)? as usize;
381 *pc = target;
382 Ok(())
383 }
384 Op::JumpIfFalse => {
385 let target = self.read_u16(pc)? as usize;
386 let cond = self.pop()?;
387 let is_false = !cond.is_truthy();
389 if is_false {
390 *pc = target;
391 }
392 Ok(())
393 }
394 Op::JumpIfTrue => {
395 let target = self.read_u16(pc)? as usize;
396 let cond = self.pop()?;
397 let is_true = cond.is_truthy();
398 if is_true {
399 *pc = target;
400 }
401 Ok(())
402 }
403
404 Op::CallHost => {
406 let path_idx = self.read_u16(pc)?;
407 let argc = self.read_u8(pc)? as usize;
408 self.call_host(path_idx, argc, 0)
409 }
410 Op::CallHostNamed => {
411 let path_idx = self.read_u16(pc)?;
412 let pos_argc = self.read_u8(pc)? as usize;
413 let named_pairs = self.read_u8(pc)? as usize;
414 self.call_host(path_idx, pos_argc, named_pairs)
415 }
416 Op::CallUser => {
417 let fn_idx = self.read_u16(pc)?;
418 let argc = self.read_u8(pc)? as usize;
419 self.call_user(fn_idx, argc, pc)
420 }
421 Op::Return => {
422 Ok(())
425 }
426 Op::ReturnNull => Ok(()),
427
428 Op::MakeList => {
430 let count = self.read_u16(pc)? as usize;
431 let mut elements = Vec::with_capacity(count);
432 for _ in 0..count {
433 elements.push(self.pop()?);
434 }
435 elements.reverse();
436 self.push(Value::List(elements))
437 }
438 Op::MakeRecord => {
439 let count = self.read_u16(pc)? as usize;
440 let mut fields: BTreeMap<String, Value> = BTreeMap::new();
441 for _ in 0..count {
442 let val = self.pop()?;
443 let key = self.pop()?;
444 if let Value::String(k) = key {
445 fields.insert(k, val);
446 } else {
447 return Err(VmError::TypeMismatch("record key"));
448 }
449 }
450 self.push(Value::Record(fields))
451 }
452 Op::GetMember => {
453 let name_idx = self.read_u16(pc)?;
454 let name = self.get_string_const(name_idx)?;
455 let recv = self.pop()?;
456 match recv {
457 Value::Record(fields) => {
458 let v = fields.get(&name).cloned().unwrap_or(Value::Null);
459 self.push(v)
460 }
461 _ => Err(VmError::TypeMismatch("member access on non-record")),
462 }
463 }
464 Op::GetIndex => {
465 let index = self.pop()?;
466 let recv = self.pop()?;
467 match (recv, index) {
468 (Value::List(items), Value::I64(i)) => {
469 if i >= 0 && (i as usize) < items.len() {
470 self.push(items[i as usize].clone())
471 } else {
472 self.push(Value::Null)
473 }
474 }
475 (Value::List(items), Value::U64(i)) => {
476 if (i as usize) < items.len() {
477 self.push(items[i as usize].clone())
478 } else {
479 self.push(Value::Null)
480 }
481 }
482 _ => Err(VmError::TypeMismatch("index on non-list")),
483 }
484 }
485 Op::TryUnwrap => {
486 let catch_off = self.read_u16(pc)? as usize;
487 match self.pop()? {
488 Value::Ok(inner) => self.push(*inner),
489 Value::Err(err_val) => {
490 if catch_off != *pc {
491 self.push(Value::Err(err_val))?;
492 *pc = catch_off;
493 Ok(())
494 } else {
495 Err(VmError::Diagnostic(Diagnostic::new(
496 DiagCode::E600,
497 Span::new(0, 0),
498 format!("? on Err: {err_val:?}"),
499 )))
500 }
501 }
502 other => self.push(other),
503 }
504 }
505 Op::Effect => {
506 self.pop()?;
508 Ok(())
509 }
510 Op::IsOk => {
511 let v = self.pop()?;
512 self.push(Value::Bool(matches!(v, Value::Ok(_))))
513 }
514 Op::UnwrapOk => match self.pop()? {
515 Value::Ok(inner) => self.push(*inner),
516 _ => Err(VmError::TypeMismatch("unwrap Ok")),
517 },
518 Op::IsErr => {
519 let v = self.pop()?;
520 self.push(Value::Bool(matches!(v, Value::Err(_))))
521 }
522 Op::UnwrapErr => match self.pop()? {
523 Value::Err(inner) => self.push(*inner),
524 _ => Err(VmError::TypeMismatch("unwrap Err")),
525 },
526 Op::IsVariant => {
527 let enum_idx = self.read_u16(pc)?;
528 let var_idx = self.read_u16(pc)?;
529 let arity = self.read_u8(pc)? as usize;
530 let enum_name = self.get_string_const(enum_idx)?;
531 let variant_name = self.get_string_const(var_idx)?;
532 let v = self.pop()?;
533 let matched = matches!(
534 v,
535 Value::Enum(ref e)
536 if e.enum_name == enum_name
537 && e.variant_name == variant_name
538 && e.payload.len() == arity
539 );
540 self.push(Value::Bool(matched))
541 }
542 Op::GetVariantField => {
543 let idx = self.read_u8(pc)? as usize;
544 match self.pop()? {
545 Value::Enum(e) => {
546 let field = e
547 .payload
548 .get(idx)
549 .cloned()
550 .ok_or(VmError::TypeMismatch("enum field index"))?;
551 self.push(field)
552 }
553 _ => Err(VmError::TypeMismatch("enum variant field")),
554 }
555 }
556 Op::IsRecord => {
557 let v = self.pop()?;
558 self.push(Value::Bool(matches!(v, Value::Record(_))))
559 }
560 Op::HasMember => {
561 let key_idx = self.read_u16(pc)?;
562 let key = self.get_string_const(key_idx)?;
563 let v = self.pop()?;
564 let matched = matches!(v, Value::Record(ref r) if r.contains_key(&key));
565 self.push(Value::Bool(matched))
566 }
567 Op::IsListLen => {
568 let len = self.read_u16(pc)? as usize;
569 let v = self.pop()?;
570 let matched = matches!(v, Value::List(ref xs) if xs.len() == len);
571 self.push(Value::Bool(matched))
572 }
573 Op::TrapMatch => Err(VmError::Diagnostic(Diagnostic::new(
574 DiagCode::E600,
575 Span::new(0, 0),
576 "destructuring let pattern failed to match",
577 ))),
578 Op::MakeVariant => {
579 let enum_idx = self.read_u16(pc)?;
580 let var_idx = self.read_u16(pc)?;
581 let argc = self.read_u8(pc)? as usize;
582 let enum_name = self.get_string_const(enum_idx)?;
583 let variant_name = self.get_string_const(var_idx)?;
584 let mut payload = Vec::with_capacity(argc);
585 for _ in 0..argc {
586 payload.push(self.pop()?);
587 }
588 payload.reverse();
589 self.push(Value::Enum(EnumValue::with_payload(
590 &enum_name,
591 &variant_name,
592 payload,
593 )))
594 }
595 Op::MakeOk => {
596 let v = self.pop()?;
597 self.push(Value::Ok(Box::new(v)))
598 }
599 Op::MakeErr => {
600 let v = self.pop()?;
601 self.push(Value::Err(Box::new(v)))
602 }
603 Op::Halt => Ok(()),
604 }
605 }
606
607 fn push(&mut self, v: Value) -> Result<(), VmError> {
610 if self.stack.len() >= MAX_STACK {
611 return Err(VmError::StackOverflow);
612 }
613 self.stack.push(v);
614 Ok(())
615 }
616
617 fn pop(&mut self) -> Result<Value, VmError> {
618 self.stack.pop().ok_or(VmError::StackUnderflow)
619 }
620
621 fn peek(&self) -> Result<&Value, VmError> {
622 self.stack.last().ok_or(VmError::StackUnderflow)
623 }
624
625 fn read_u8(&self, pc: &mut usize) -> Result<u8, VmError> {
628 if *pc >= self.chunk.code.len() {
629 return Err(VmError::CodeOutOfBounds);
630 }
631 let b = self.chunk.code[*pc];
632 *pc += 1;
633 Ok(b)
634 }
635
636 fn read_u16(&self, pc: &mut usize) -> Result<u16, VmError> {
637 let lo = self.read_u8(pc)? as u16;
638 let hi = self.read_u8(pc)? as u16;
639 Ok(lo | (hi << 8))
640 }
641
642 fn read_i64(&self, pc: &mut usize) -> Result<i64, VmError> {
643 let mut bytes = [0u8; 8];
644 for b in &mut bytes {
645 *b = self.read_u8(pc)?;
646 }
647 Ok(i64::from_le_bytes(bytes))
648 }
649
650 fn read_u64(&self, pc: &mut usize) -> Result<u64, VmError> {
651 let mut bytes = [0u8; 8];
652 for b in &mut bytes {
653 *b = self.read_u8(pc)?;
654 }
655 Ok(u64::from_le_bytes(bytes))
656 }
657
658 fn get_string_const(&self, idx: u16) -> Result<String, VmError> {
661 match self.chunk.constants.get(idx as usize) {
662 Some(Const::String(s)) => Ok(s.clone()),
663 Some(Const::Iri(s)) => Ok(s.clone()),
664 None => Err(VmError::InvalidConstant(idx)),
665 }
666 }
667
668 fn get_iri_const(&self, idx: u16) -> Result<String, VmError> {
669 match self.chunk.constants.get(idx as usize) {
670 Some(Const::Iri(s)) => Ok(s.clone()),
671 Some(Const::String(s)) => Ok(s.clone()),
672 None => Err(VmError::InvalidConstant(idx)),
673 }
674 }
675
676 fn load_local(&self, slot: u16) -> Result<Value, VmError> {
679 let frame = self.frames.last().ok_or(VmError::StackUnderflow)?;
680 frame
681 .locals
682 .get(slot as usize)
683 .cloned()
684 .ok_or(VmError::InvalidLocal(slot))
685 }
686
687 fn store_local(&mut self, slot: u16, value: Value) -> Result<(), VmError> {
688 let frame = self.frames.last_mut().ok_or(VmError::StackUnderflow)?;
689 if slot as usize >= frame.locals.len() {
690 return Err(VmError::InvalidLocal(slot));
691 }
692 frame.locals[slot as usize] = value;
693 Ok(())
694 }
695
696 fn binop_num(
699 &mut self,
700 f64f: impl Fn(f64, f64) -> f64,
701 i64f: impl Fn(i64, i64) -> i64,
702 u64f: impl Fn(u64, u64) -> u64,
703 _i64wrap: impl Fn(i64, i64) -> i64,
704 ) -> Result<(), VmError> {
705 let b = self.pop()?;
706 let a = self.pop()?;
707 let result = match (a, b) {
708 (Value::F64(x), Value::F64(y)) => Value::F64(f64f(x, y)),
709 (Value::I64(x), Value::I64(y)) => Value::I64(i64f(x, y)),
710 (Value::U64(x), Value::U64(y)) => Value::U64(u64f(x, y)),
711 (Value::F64(x), Value::I64(y)) => Value::F64(f64f(x, y as f64)),
712 (Value::I64(x), Value::F64(y)) => Value::F64(f64f(x as f64, y)),
713 (Value::U64(x), Value::F64(y)) => Value::F64(f64f(x as f64, y)),
714 (Value::F64(x), Value::U64(y)) => Value::F64(f64f(x, y as f64)),
715 (Value::I64(x), Value::U64(y)) => Value::I64(i64f(x, y as i64)),
716 (Value::U64(x), Value::I64(y)) => Value::I64(i64f(x as i64, y)),
717 (Value::Quantity(x), Value::Quantity(y)) if x.unit == y.unit => {
718 Value::Quantity(crate::value::Quantity {
719 value: f64f(x.value, y.value),
720 unit: x.unit,
721 })
722 }
723 _ => return Err(VmError::TypeMismatch("arithmetic")),
724 };
725 self.push(result)
726 }
727
728 fn div_op(&mut self, a: Value, b: Value) -> Result<(), VmError> {
729 let result = match (a, b) {
730 (Value::F64(x), Value::F64(y)) => {
731 if y == 0.0 {
732 return Err(VmError::Diagnostic(Diagnostic::new(
733 DiagCode::E600,
734 Span::new(0, 0),
735 "division by zero",
736 )));
737 }
738 Value::F64(x / y)
739 }
740 (Value::I64(x), Value::I64(y)) => {
741 if y == 0 {
742 return Err(VmError::Diagnostic(Diagnostic::new(
743 DiagCode::E600,
744 Span::new(0, 0),
745 "division by zero",
746 )));
747 }
748 Value::I64(x / y)
749 }
750 (Value::U64(x), Value::U64(y)) => {
751 if y == 0 {
752 return Err(VmError::Diagnostic(Diagnostic::new(
753 DiagCode::E600,
754 Span::new(0, 0),
755 "division by zero",
756 )));
757 }
758 Value::U64(x / y)
759 }
760 (Value::F64(x), Value::I64(y)) => {
761 if y == 0 {
762 return Err(VmError::Diagnostic(Diagnostic::new(
763 DiagCode::E600,
764 Span::new(0, 0),
765 "division by zero",
766 )));
767 }
768 Value::F64(x / y as f64)
769 }
770 (Value::I64(x), Value::F64(y)) => {
771 if y == 0.0 {
772 return Err(VmError::Diagnostic(Diagnostic::new(
773 DiagCode::E600,
774 Span::new(0, 0),
775 "division by zero",
776 )));
777 }
778 Value::F64(x as f64 / y)
779 }
780 _ => return Err(VmError::TypeMismatch("division")),
781 };
782 self.push(result)
783 }
784
785 fn rem_op(&mut self, a: Value, b: Value) -> Result<(), VmError> {
786 let result = match (a, b) {
787 (Value::F64(x), Value::F64(y)) => {
788 if y == 0.0 {
789 return Err(VmError::Diagnostic(Diagnostic::new(
790 DiagCode::E600,
791 Span::new(0, 0),
792 "division by zero",
793 )));
794 }
795 Value::F64(x % y)
796 }
797 (Value::I64(x), Value::I64(y)) => {
798 if y == 0 {
799 return Err(VmError::Diagnostic(Diagnostic::new(
800 DiagCode::E600,
801 Span::new(0, 0),
802 "division by zero",
803 )));
804 }
805 Value::I64(x % y)
806 }
807 (Value::U64(x), Value::U64(y)) => {
808 if y == 0 {
809 return Err(VmError::Diagnostic(Diagnostic::new(
810 DiagCode::E600,
811 Span::new(0, 0),
812 "division by zero",
813 )));
814 }
815 Value::U64(x % y)
816 }
817 _ => return Err(VmError::TypeMismatch("remainder")),
818 };
819 self.push(result)
820 }
821
822 fn cmp_op(&mut self, check: impl Fn(std::cmp::Ordering) -> bool) -> Result<(), VmError> {
823 let b = self.pop()?;
824 let a = self.pop()?;
825 let result = match (a, b) {
826 (Value::F64(x), Value::F64(y)) => {
827 check(x.partial_cmp(&y).unwrap_or(std::cmp::Ordering::Equal))
828 }
829 (Value::I64(x), Value::I64(y)) => check(x.cmp(&y)),
830 (Value::U64(x), Value::U64(y)) => check(x.cmp(&y)),
831 (Value::F64(x), Value::I64(y)) => check(
832 x.partial_cmp(&(y as f64))
833 .unwrap_or(std::cmp::Ordering::Equal),
834 ),
835 (Value::I64(x), Value::F64(y)) => check(
836 (x as f64)
837 .partial_cmp(&y)
838 .unwrap_or(std::cmp::Ordering::Equal),
839 ),
840 (Value::String(x), Value::String(y)) => check(x.cmp(&y)),
841 _ => return Err(VmError::TypeMismatch("comparison")),
842 };
843 self.push(Value::Bool(result))
844 }
845
846 fn call_host(
847 &mut self,
848 path_idx: u16,
849 pos_argc: usize,
850 named_pairs: usize,
851 ) -> Result<(), VmError> {
852 let mut named_args = Vec::with_capacity(named_pairs);
853 for _ in 0..named_pairs {
854 let val = self.pop()?;
855 let key = match self.pop()? {
856 Value::String(k) => k,
857 _ => return Err(VmError::TypeMismatch("named argument key")),
858 };
859 named_args.push((key, val));
860 }
861 named_args.reverse();
862
863 let mut pos_args = Vec::with_capacity(pos_argc);
864 for _ in 0..pos_argc {
865 pos_args.push(self.pop()?);
866 }
867 pos_args.reverse();
868
869 if path_idx == 0xFFFF {
870 let _callee = self.pop()?;
871 self.push(Value::Null)?;
872 return Ok(());
873 }
874
875 let path = self.get_string_const(path_idx)?;
876 let span = Span::new(0, 0);
877
878 let result = route_call(
879 self.host,
880 &self.extension_registry,
881 &mut self.prepared_cache,
882 &self.call_context,
883 self.sentinel_gate.as_deref_mut(),
884 &mut self.last_extension_outcome,
885 &mut self.budget,
886 &path,
887 &pos_args,
888 &named_args,
889 span,
890 )?;
891 self.push(result)
892 }
893
894 fn call_user(&mut self, fn_idx: u16, argc: usize, pc: &mut usize) -> Result<(), VmError> {
895 let meta = self
896 .chunk
897 .functions
898 .get(fn_idx as usize)
899 .ok_or(VmError::InvalidFunction(fn_idx))?
900 .clone();
901
902 if meta.budget_steps > 0 {
903 self.budget.steps_left = self.budget.steps_left.min(meta.budget_steps);
904 }
905
906 let mut args = Vec::with_capacity(argc);
908 for _ in 0..argc {
909 args.push(self.pop()?);
910 }
911 args.reverse();
912
913 let mut locals = vec![Value::Null; meta.local_count as usize];
915 for (i, arg) in args.iter().enumerate() {
916 if i < meta.param_count as usize && i < locals.len() {
917 locals[i] = arg.clone();
918 }
919 }
920
921 let return_pc = *pc;
922 self.frames.push(Frame { return_pc, locals });
923
924 *pc = meta.code_offset as usize;
926
927 loop {
930 self.budget.tick(Span::new(0, 0)).map_err(VmError::from)?;
931 let op_byte = self.read_u8(pc)?;
932 let op = Op::from_byte(op_byte).ok_or(VmError::InvalidOpcode(op_byte))?;
933
934 match op {
935 Op::Return => {
936 let v = self.pop()?;
937 let frame = self.frames.pop().ok_or(VmError::StackUnderflow)?;
938 *pc = frame.return_pc;
939 self.push(v)?;
940 break;
941 }
942 Op::ReturnNull => {
943 let frame = self.frames.pop().ok_or(VmError::StackUnderflow)?;
944 *pc = frame.return_pc;
945 self.push(Value::Null)?;
946 break;
947 }
948 _ => self.exec_op(op, pc)?,
949 }
950 }
951
952 Ok(())
953 }
954}
955
956#[cfg(test)]
957mod tests {
958 use super::*;
959 use crate::bind::LocalHost;
960 use crate::bytecode::compiler::{compile, compile_expr};
961 use crate::parse::parse_cell;
962
963 fn run_cell(src: &str) -> Result<Value, VmError> {
964 let expr = parse_cell(src).expect("parse");
965 let chunk = compile_expr(&expr).expect("compile");
966 let mut host = LocalHost::default();
967 let mut vm = Vm::new(&chunk, &mut host, Budget::default());
968 vm.run()
969 }
970
971 #[test]
972 fn vm_arithmetic() {
973 let v = run_cell("= 1 + 2 * 3").expect("vm");
974 assert_eq!(v, Value::I64(7));
975 }
976
977 #[test]
978 fn vm_float_arithmetic() {
979 let v = run_cell("= 1.5 + 2.5").expect("vm");
980 assert_eq!(v, Value::F64(4.0));
981 }
982
983 #[test]
984 fn vm_division_by_zero() {
985 let err = run_cell("= 1 / 0").expect_err("should error");
986 assert!(matches!(err, VmError::Diagnostic(_)));
987 }
988
989 #[test]
990 fn vm_float_division_by_zero() {
991 let err = run_cell("= 1.0 / 0.0").expect_err("should error");
992 assert!(matches!(err, VmError::Diagnostic(_)));
993 }
994
995 #[test]
996 fn vm_comparison() {
997 let v = run_cell("= 3 > 2").expect("vm");
998 assert_eq!(v, Value::Bool(true));
999
1000 let v = run_cell("= 2 > 3").expect("vm");
1001 assert_eq!(v, Value::Bool(false));
1002 }
1003
1004 #[test]
1005 fn vm_logical_and() {
1006 let v = run_cell("= true && false").expect("vm");
1007 assert_eq!(v, Value::Bool(false));
1008
1009 let v = run_cell("= true && true").expect("vm");
1010 assert_eq!(v, Value::Bool(true));
1011 }
1012
1013 #[test]
1014 fn vm_logical_or() {
1015 let v = run_cell("= false || true").expect("vm");
1016 assert_eq!(v, Value::Bool(true));
1017 }
1018
1019 #[test]
1020 fn vm_negation() {
1021 let v = run_cell("= -5").expect("vm");
1022 assert_eq!(v, Value::I64(-5));
1023 }
1024
1025 #[test]
1026 fn vm_not() {
1027 let v = run_cell("= !true").expect("vm");
1028 assert_eq!(v, Value::Bool(false));
1029 }
1030
1031 #[test]
1032 fn vm_string_literal() {
1033 let v = run_cell(r#"= "hello""#).expect("vm");
1034 assert_eq!(v, Value::String("hello".into()));
1035 }
1036
1037 #[test]
1038 fn vm_list_literal() {
1039 let v = run_cell("= [1, 2, 3]").expect("vm");
1040 match v {
1041 Value::List(items) => {
1042 assert_eq!(items.len(), 3);
1043 assert_eq!(items[0], Value::I64(1));
1044 assert_eq!(items[1], Value::I64(2));
1045 assert_eq!(items[2], Value::I64(3));
1046 }
1047 _ => panic!("expected list"),
1048 }
1049 }
1050
1051 #[test]
1052 fn vm_record_literal() {
1053 let v = run_cell("= { x: 1, y: 2 }").expect("vm");
1054 match v {
1055 Value::Record(fields) => {
1056 assert_eq!(fields.len(), 2);
1057 assert_eq!(fields.get("x"), Some(&Value::I64(1)));
1058 assert_eq!(fields.get("y"), Some(&Value::I64(2)));
1059 }
1060 _ => panic!("expected record"),
1061 }
1062 }
1063
1064 #[test]
1065 fn vm_member_access() {
1066 let v = run_cell("= { x: 42, y: 10 }.x").expect("vm");
1067 assert_eq!(v, Value::I64(42));
1068 }
1069
1070 #[test]
1071 fn vm_index_access() {
1072 let v = run_cell("= [10, 20, 30][1]").expect("vm");
1073 assert_eq!(v, Value::I64(20));
1074 }
1075
1076 #[test]
1077 fn vm_index_out_of_bounds() {
1078 let v = run_cell("= [10, 20, 30][10]").expect("vm");
1079 assert_eq!(v, Value::Null);
1080 }
1081
1082 #[test]
1083 fn vm_remainder() {
1084 let v = run_cell("= 10 % 3").expect("vm");
1085 assert_eq!(v, Value::I64(1));
1086 }
1087
1088 #[test]
1089 fn vm_null_literal() {
1090 let v = run_cell("= null").expect("vm");
1091 assert_eq!(v, Value::Null);
1092 }
1093
1094 #[test]
1095 fn vm_bool_literals() {
1096 let v = run_cell("= true").expect("vm");
1097 assert_eq!(v, Value::Bool(true));
1098
1099 let v = run_cell("= false").expect("vm");
1100 assert_eq!(v, Value::Bool(false));
1101 }
1102
1103 #[test]
1104 fn vm_uint_literal() {
1105 let v = run_cell("= 42u64").expect("vm");
1106 assert_eq!(v, Value::U64(42));
1107 }
1108
1109 #[test]
1110 fn vm_nested_arithmetic() {
1111 let v = run_cell("= (1 + 2) * (3 + 4)").expect("vm");
1112 assert_eq!(v, Value::I64(21));
1113 }
1114
1115 #[test]
1116 fn vm_equality() {
1117 let v = run_cell("= 42 == 42").expect("vm");
1118 assert_eq!(v, Value::Bool(true));
1119
1120 let v = run_cell("= 42 != 43").expect("vm");
1121 assert_eq!(v, Value::Bool(true));
1122 }
1123
1124 #[test]
1125 fn vm_string_equality() {
1126 let v = run_cell(r#"= "abc" == "abc""#).expect("vm");
1127 assert_eq!(v, Value::Bool(true));
1128 }
1129
1130 #[test]
1131 fn vm_program_with_function() {
1132 use crate::parse::parse_program;
1133 let src =
1134 "fn double(x: i64) -> i64 { return x + x; } fn main() -> i64 { return double(21); }";
1135 let prog = parse_program(src).expect("parse");
1136 let chunk = compile(&prog).expect("compile");
1137 let mut host = LocalHost::default();
1138 let mut vm = Vm::new(&chunk, &mut host, Budget::default());
1139
1140 vm.run().expect("run preamble");
1142
1143 let main_idx = chunk.find_function("main").expect("main exists");
1145 let result = vm.call_function(main_idx, &[]).expect("call main");
1146 assert_eq!(result, Value::I64(42));
1147 }
1148
1149 #[test]
1150 fn vm_program_with_if() {
1151 use crate::parse::parse_program;
1152 let src = "fn sign(x: i64) -> i64 { if x > 0 { return 1; } else { return -1; } }";
1153 let prog = parse_program(src).expect("parse");
1154 let chunk = compile(&prog).expect("compile");
1155 let mut host = LocalHost::default();
1156
1157 let mut vm = Vm::new(&chunk, &mut host, Budget::default());
1158 vm.run().expect("preamble");
1159
1160 let sign_idx = chunk.find_function("sign").expect("sign exists");
1161 let r1 = vm.call_function(sign_idx, &[Value::I64(5)]).expect("call");
1162 assert_eq!(r1, Value::I64(1));
1163
1164 let r2 = vm.call_function(sign_idx, &[Value::I64(-5)]).expect("call");
1165 assert_eq!(r2, Value::I64(-1));
1166 }
1167
1168 #[test]
1169 fn vm_program_with_while() {
1170 use crate::parse::parse_program;
1171 let src = "fn sum_to(n: i64) budget(steps: 10000) -> i64 { let s = 0; let i = 0; while i < n { s = s + i; i = i + 1; } return s; }";
1172 let prog = parse_program(src).expect("parse");
1173 let chunk = compile(&prog).expect("compile");
1174 let mut host = LocalHost::default();
1175
1176 let mut vm = Vm::new(&chunk, &mut host, Budget::default());
1177 vm.run().expect("preamble");
1178
1179 let idx = chunk.find_function("sum_to").expect("function exists");
1180 let result = vm.call_function(idx, &[Value::I64(10)]).expect("call");
1181 assert_eq!(result, Value::I64(45)); }
1183
1184 #[test]
1185 fn vm_program_with_for() {
1186 use crate::parse::parse_program;
1187 let src = "fn sum_list() budget(steps: 10000) -> i64 { let s = 0; for x in [1, 2, 3, 4, 5] { s = s + x; } return s; }";
1188 let prog = parse_program(src).expect("parse");
1189 let chunk = compile(&prog).expect("compile");
1190 let mut host = LocalHost::default();
1191
1192 let mut vm = Vm::new(&chunk, &mut host, Budget::default());
1193 vm.run().expect("preamble");
1194
1195 let idx = chunk.find_function("sum_list").expect("function exists");
1196 let result = vm.call_function(idx, &[]).expect("call");
1197 assert_eq!(result, Value::I64(15));
1198 }
1199
1200 #[test]
1201 fn vm_quantity_add_same_unit() {
1202 let v = run_cell("= 500ms + 20ms").expect("vm");
1203 match v {
1204 Value::Quantity(q) => {
1205 assert_eq!(q.unit, "ms");
1206 assert!((q.value - 520.0).abs() < 1e-9, "got {}", q.value);
1207 }
1208 other => panic!("expected Quantity, got {other:?}"),
1209 }
1210 }
1211
1212 #[test]
1213 fn vm_quantity_mismatched_units_fail() {
1214 let err = run_cell("= 500ms + 1s").expect_err("unit mismatch");
1215 assert!(matches!(err, VmError::TypeMismatch(_)));
1216 }
1217
1218 #[test]
1219 fn vm_ast_parity_patterns_letpat_try_budget_and_args() {
1220 use crate::eval::{Engine, Env};
1221 use crate::parse::parse_program;
1222
1223 let src = r#"
1225enum Color { Red, Rgb(i64, i64, i64) }
1226fn inspect_all(opt: i64, res: i64, tag: i64) -> i64 {
1227 let [a, b] = [10, 20];
1228 let { x, y } = { x: 3, y: 4 };
1229 let mut v_opt = 0;
1230 match opt {
1231 Some(n) => { v_opt = n + 1; }
1232 None => { v_opt = 0; }
1233 }
1234 let r_val = if res > 0 { Ok(res * 2) } else { Err("neg") };
1235 let mut v_res = 0;
1236 match r_val {
1237 Ok(k) => { v_res = k; }
1238 Err(_e) => { v_res = -1; }
1239 }
1240 let c = if tag == 1 { Color.Rgb(1, 2, 3) } else { Color.Red() };
1241 let mut v_col = 0;
1242 match c {
1243 Color.Rgb(r, g, bl) => { v_col = r + g + bl; }
1244 Color.Red() => { v_col = 9; }
1245 _ => { v_col = 0; }
1246 }
1247 let unwrapped = Ok(5)?;
1248 return a + b + x + y + v_opt + v_res + v_col + unwrapped;
1249}
1250"#;
1251 let prog = parse_program(src).expect("parse");
1252 let chunk = compile(&prog).expect("compile");
1253 let idx = chunk.find_function("inspect_all").expect("fn");
1254
1255 for (opt, res, tag) in [
1256 (Value::I64(7), Value::I64(4), Value::I64(1)),
1257 (Value::Null, Value::I64(-1), Value::I64(0)),
1258 ] {
1259 let mut h1 = LocalHost::default();
1260 let mut vm = Vm::new(&chunk, &mut h1, Budget::default());
1261 vm.run().expect("preamble");
1262 let vm_out = vm
1263 .call_function(idx, &[opt.clone(), res.clone(), tag.clone()])
1264 .expect("vm call");
1265
1266 let mut h2 = LocalHost::default();
1267 let mut engine = Engine::new(&mut h2, Budget::default());
1268 let mut env = Env::default();
1269 let ast_out = engine
1270 .call_function(&prog, "inspect_all", vec![opt, res, tag], &mut env)
1271 .expect("ast call");
1272 assert_eq!(vm_out, ast_out);
1273 }
1274
1275 let err_try = parse_program(r#"fn fail_try() -> i64 { return Err("boom")?; }"#).unwrap();
1277 let err_chunk = compile(&err_try).unwrap();
1278 let mut h = LocalHost::default();
1279 let mut vm = Vm::new(&err_chunk, &mut h, Budget::default());
1280 vm.run().unwrap();
1281 let f_idx = err_chunk.find_function("fail_try").unwrap();
1282 assert!(matches!(
1283 vm.call_function(f_idx, &[]),
1284 Err(VmError::Diagnostic(d)) if d.code == DiagCode::E600
1285 ));
1286
1287 let query_src = r#"fn q() -> List { return graph.query("s", "p", take: 3); }"#;
1289 let q_prog = parse_program(query_src).unwrap();
1290 let q_chunk = compile(&q_prog).unwrap();
1291 let mut qh = LocalHost {
1292 query_rows: 10,
1293 ..LocalHost::default()
1294 };
1295 let mut qvm = Vm::new(&q_chunk, &mut qh, Budget::default());
1296 qvm.run().unwrap();
1297 let q_idx = q_chunk.find_function("q").unwrap();
1298 let q_res = qvm.call_function(q_idx, &[]).expect("query");
1299 assert_eq!(q_res, Value::List(vec![Value::I64(1); 3]));
1300
1301 let str_src = r#"fn eqs() -> bool { return str.eq("hello", "hello"); }"#;
1303 let str_prog = parse_program(str_src).unwrap();
1304 let str_chunk = compile(&str_prog).unwrap();
1305 let mut sh = LocalHost::default();
1306 let mut svm = Vm::new(&str_chunk, &mut sh, Budget::default());
1307 svm.run().unwrap();
1308 let eqs_idx = str_chunk.find_function("eqs").unwrap();
1309 assert_eq!(svm.call_function(eqs_idx, &[]).unwrap(), Value::Bool(true));
1310
1311 let spin_src = r#"fn spin() budget(steps: 5) -> i64 { let i = 0; while i < 100 { i = i + 1; } return i; }"#;
1313 let spin_prog = parse_program(spin_src).unwrap();
1314 let spin_chunk = compile(&spin_prog).unwrap();
1315 let mut bh = LocalHost::default();
1316 let mut bvm = Vm::new(&spin_chunk, &mut bh, Budget::default());
1317 bvm.run().unwrap();
1318 let s_idx = spin_chunk.find_function("spin").unwrap();
1319 assert!(matches!(
1320 bvm.call_function(s_idx, &[]),
1321 Err(VmError::Diagnostic(d)) if d.code == DiagCode::E400
1322 ));
1323
1324 let mut bad_chunk = Chunk::new();
1326 bad_chunk.top_locals = 0;
1327 bad_chunk.emit_op(Op::LoadVar);
1328 bad_chunk.emit_u16(0);
1329 bad_chunk.emit_op(Op::Halt);
1330 let mut bh2 = LocalHost::default();
1331 let mut bvm2 = Vm::new(&bad_chunk, &mut bh2, Budget::default());
1332 assert!(matches!(bvm2.run(), Err(VmError::InvalidLocal(0))));
1333 }
1334}