1mod access;
23mod arithmetic;
24mod cast;
25mod library;
26mod presence;
27mod rich;
28mod store;
29
30use crate::compare::{self, Operator};
31use crate::options::OnUnbound;
32use crate::{
33 Context, Error, EvaluationError, Execution, Instructions, Key, Options, Stopped,
34 TypeMismatchError, UndefinedVariableError, Value,
35};
36use arithmetic::Arithmetic;
37use cast::Target;
38use presence::Presence;
39use sealed::Mode;
40use std::borrow::Cow;
41use std::collections::BTreeSet;
42use std::collections::hash_map::RandomState;
43use std::hash::BuildHasher;
44
45pub trait Program: sealed::Sealed {}
62
63mod sealed {
64 use crate::{Error, Instructions, compile, compile_program};
65 use std::borrow::Cow;
66
67 #[derive(Debug, Clone, Copy)]
70 pub enum Mode {
71 Expression,
73 Statements,
76 }
77
78 pub trait Sealed {
80 fn resolve(&self, mode: Mode) -> Result<Cow<'_, Instructions>, Error>;
82 }
83
84 impl Sealed for &Instructions {
85 fn resolve(&self, _mode: Mode) -> Result<Cow<'_, Instructions>, Error> {
86 Ok(Cow::Borrowed(*self))
87 }
88 }
89
90 impl Sealed for &str {
91 fn resolve(&self, mode: Mode) -> Result<Cow<'_, Instructions>, Error> {
92 match mode {
93 Mode::Expression => compile(self),
94 Mode::Statements => compile_program(self),
95 }
96 .map(Cow::Owned)
97 }
98 }
99}
100
101impl Program for &Instructions {}
102
103impl Program for &str {}
104
105#[derive(Debug)]
107enum Op<'a> {
108 Lit(&'a Value),
109 Load(&'a str),
110 Compare(Operator),
111 Not,
112 UnaryBang,
113 UnaryMinus,
114 JumpIfFalsyOrPop(usize),
115 JumpIfTrueOrPop(usize),
116 Arithmetic(Arithmetic),
117 Access(&'a str),
118 BracketAccess,
119 In,
120 Contains,
121 MakeList(usize),
122 ObjectNew,
123 ObjectSet(&'a str),
124 Duration(&'a [Value]),
125 RelativeDate(&'a str),
126 Call(&'a str, usize),
127 Store(usize),
128 Pop,
129 Jump(usize),
130 PopJumpIfFalsy(usize),
131 JumpBackward(usize),
132 Cast(Target),
133 Presence(Presence),
134 Intersects,
135}
136
137pub(crate) struct Row {
140 pub(crate) name: &'static str,
141 read: for<'a> fn(&'a [Value]) -> Option<Op<'a>>,
142}
143
144pub(crate) const OPCODES: &[Row] = &[
146 Row {
147 name: "lit",
148 read: read_lit,
149 },
150 Row {
151 name: "load",
152 read: read_load,
153 },
154 Row {
155 name: "compare",
156 read: read_compare,
157 },
158 Row {
159 name: "not",
160 read: |operands| bare(operands, Op::Not),
161 },
162 Row {
163 name: "unary_bang",
164 read: |operands| bare(operands, Op::UnaryBang),
165 },
166 Row {
167 name: "unary_minus",
168 read: |operands| bare(operands, Op::UnaryMinus),
169 },
170 Row {
171 name: "jump_if_falsy_or_pop",
172 read: |operands| offset(operands).map(Op::JumpIfFalsyOrPop),
173 },
174 Row {
175 name: "jump_if_true_or_pop",
176 read: |operands| offset(operands).map(Op::JumpIfTrueOrPop),
177 },
178 Row {
179 name: "add",
180 read: |operands| bare(operands, Op::Arithmetic(Arithmetic::Add)),
181 },
182 Row {
183 name: "subtract",
184 read: |operands| bare(operands, Op::Arithmetic(Arithmetic::Subtract)),
185 },
186 Row {
187 name: "multiply",
188 read: |operands| bare(operands, Op::Arithmetic(Arithmetic::Multiply)),
189 },
190 Row {
191 name: "divide",
192 read: |operands| bare(operands, Op::Arithmetic(Arithmetic::Divide)),
193 },
194 Row {
195 name: "modulo",
196 read: |operands| bare(operands, Op::Arithmetic(Arithmetic::Modulo)),
197 },
198 Row {
199 name: "access",
200 read: read_access,
201 },
202 Row {
203 name: "bracket_access",
204 read: |operands| bare(operands, Op::BracketAccess),
205 },
206 Row {
207 name: "in",
208 read: |operands| bare(operands, Op::In),
209 },
210 Row {
211 name: "contains",
212 read: |operands| bare(operands, Op::Contains),
213 },
214 Row {
215 name: "make_list",
216 read: read_make_list,
217 },
218 Row {
219 name: "object_new",
220 read: |operands| bare(operands, Op::ObjectNew),
221 },
222 Row {
223 name: "object_set",
224 read: |operands| string(operands).map(Op::ObjectSet),
225 },
226 Row {
227 name: "duration",
228 read: read_duration,
229 },
230 Row {
231 name: "relative_date",
232 read: |operands| string(operands).map(Op::RelativeDate),
233 },
234 Row {
235 name: "call",
236 read: read_call,
237 },
238 Row {
239 name: "store",
240 read: read_store,
241 },
242 Row {
243 name: "pop",
244 read: |operands| bare(operands, Op::Pop),
245 },
246 Row {
247 name: "jump",
248 read: |operands| offset(operands).map(Op::Jump),
249 },
250 Row {
251 name: "pop_jump_if_falsy",
252 read: |operands| offset(operands).map(Op::PopJumpIfFalsy),
253 },
254 Row {
255 name: "jump_backward",
256 read: |operands| offset(operands).map(Op::JumpBackward),
257 },
258 Row {
259 name: "cast",
260 read: |operands| string(operands).and_then(Target::named).map(Op::Cast),
261 },
262 Row {
263 name: "presence",
264 read: |operands| string(operands).and_then(Presence::named).map(Op::Presence),
265 },
266 Row {
267 name: "intersects",
268 read: |operands| bare(operands, Op::Intersects),
269 },
270];
271
272const RETIRED: &[(&str, u32)] = &[("and", 3), ("or", 3)];
275
276fn read_lit(operands: &[Value]) -> Option<Op<'_>> {
277 match operands {
278 [value] => Some(Op::Lit(value)),
279 _ => None,
280 }
281}
282
283fn read_load(operands: &[Value]) -> Option<Op<'_>> {
284 match operands {
285 [Value::String(name)] => Some(Op::Load(name)),
286 _ => None,
287 }
288}
289
290fn read_access(operands: &[Value]) -> Option<Op<'_>> {
291 match operands {
292 [Value::String(property)] => Some(Op::Access(property)),
293 _ => None,
294 }
295}
296
297fn read_make_list(operands: &[Value]) -> Option<Op<'_>> {
300 match operands {
301 [Value::Integer(count)] if *count >= 0 => {
302 Some(Op::MakeList(usize::try_from(*count).unwrap_or(usize::MAX)))
303 }
304 _ => None,
305 }
306}
307
308fn read_call(operands: &[Value]) -> Option<Op<'_>> {
312 match operands {
313 [Value::String(name), Value::Integer(count)] if *count >= 0 => Some(Op::Call(
314 name,
315 usize::try_from(*count).unwrap_or(usize::MAX),
316 )),
317 _ => None,
318 }
319}
320
321fn read_store(operands: &[Value]) -> Option<Op<'_>> {
324 match operands {
325 [Value::Integer(count)] if *count >= 0 => {
326 Some(Op::Store(usize::try_from(*count).unwrap_or(usize::MAX)))
327 }
328 _ => None,
329 }
330}
331
332fn read_compare(operands: &[Value]) -> Option<Op<'_>> {
333 match operands {
334 [Value::String(name)] => Operator::named(name).map(Op::Compare),
335 _ => None,
336 }
337}
338
339fn read_duration(operands: &[Value]) -> Option<Op<'_>> {
342 match operands {
343 [Value::List(pairs)] => Some(Op::Duration(pairs)),
344 _ => None,
345 }
346}
347
348fn string(operands: &[Value]) -> Option<&str> {
350 match operands {
351 [Value::String(text)] => Some(text),
352 _ => None,
353 }
354}
355
356fn bare<'a>(operands: &[Value], op: Op<'a>) -> Option<Op<'a>> {
358 operands.is_empty().then_some(op)
359}
360
361fn offset(operands: &[Value]) -> Option<usize> {
363 match operands {
364 [Value::Integer(offset)] if *offset > 0 => {
366 Some(usize::try_from(*offset).unwrap_or(usize::MAX))
367 }
368 _ => None,
369 }
370}
371
372fn unknown(name: &str) -> EvaluationError {
374 EvaluationError::new(
375 "unknown_instruction",
376 format!("unknown instruction: {name}"),
377 )
378}
379
380fn decode(instruction: &Value) -> Result<Op<'_>, EvaluationError> {
382 let Value::List(parts) = instruction else {
383 return Err(unknown("an instruction that is not a list"));
384 };
385 let Some((Value::String(name), operands)) = parts.split_first() else {
386 return Err(unknown("an instruction that names no opcode"));
387 };
388 if let Some(row) = OPCODES.iter().find(|row| row.name == name) {
389 return (row.read)(operands)
390 .ok_or_else(|| unknown(&format!("{name} with operands it does not take")));
391 }
392 match RETIRED.iter().find(|(retired, _)| retired == name) {
393 Some((_, version)) => Err(EvaluationError::new(
394 "retired_opcode",
395 format!("the instruction {name} was retired at instruction-set version {version}"),
396 )),
397 None => Err(unknown(name)),
398 }
399}
400
401enum Fault {
403 Error(Error),
405 RejectedUndefined(TypeMismatchError),
408}
409
410impl From<EvaluationError> for Fault {
411 fn from(error: EvaluationError) -> Fault {
412 Fault::Error(error.into())
413 }
414}
415
416struct Machine<'a> {
418 context: Cow<'a, Context>,
421 options: &'a Options<'a>,
422 protect: bool,
424 budget: u64,
426 stored: Vec<Key>,
429 stored_set: BTreeSet<Key>,
430 last: Value,
432 on_unbound: OnUnbound,
433 now: Option<crate::DateTime>,
435 stack: Vec<Value>,
436 unbound: Option<&'a str>,
438 random: Option<(RandomState, u64)>,
441}
442
443fn insufficient(operation: &str, wanted: usize) -> EvaluationError {
444 EvaluationError::new(
445 "insufficient_operands",
446 format!("{operation} takes {wanted} value(s) from the stack"),
447 )
448}
449
450fn type_name(value: &Value) -> &'static str {
451 match value {
452 Value::Null => "null",
453 Value::Undefined => "undefined",
454 Value::Bool(_) => "boolean",
455 Value::Integer(_) => "integer",
456 Value::Float(_) => "float",
457 Value::String(_) => "string",
458 Value::List(_) => "list",
459 Value::Map(_) => "map",
460 Value::Date(_) => "date",
461 Value::DateTime(_) => "datetime",
462 Value::Duration(_) => "duration",
463 }
464}
465
466fn mismatch(operation: &str, expected: &str, operand: &Value) -> Fault {
468 let error = TypeMismatchError::new(
469 operation,
470 format!(
471 "{operation} takes a {expected}, not a {}",
472 type_name(operand)
473 ),
474 );
475 match operand {
476 Value::Undefined => Fault::RejectedUndefined(error),
477 _ => Fault::Error(error.into()),
478 }
479}
480
481fn mismatch_pair(operation: &str, wanted: &str, left: &Value, right: &Value) -> Fault {
485 let error = TypeMismatchError::new(
486 operation,
487 format!(
488 "{operation} takes a {wanted}, not a {} and a {}",
489 type_name(left),
490 type_name(right)
491 ),
492 );
493 match (left, right) {
494 (Value::Undefined, _) | (_, Value::Undefined) => Fault::RejectedUndefined(error),
495 _ => Fault::Error(error.into()),
496 }
497}
498
499impl<'a> Machine<'a> {
500 fn new(context: &'a Context, options: &'a Options<'a>, protect: bool) -> Machine<'a> {
503 Machine {
504 context: Cow::Borrowed(context),
505 options,
506 protect,
507 budget: options.loop_budget,
508 stored: Vec::new(),
509 stored_set: BTreeSet::new(),
510 last: Value::Undefined,
511 on_unbound: options.on_unbound,
512 now: None,
513 stack: Vec::new(),
514 unbound: None,
515 random: None,
516 }
517 }
518
519 fn run(&mut self, list: &'a [Value]) -> Result<(), Fault> {
522 let mut at = 0;
523 while let Some(instruction) = list.get(at) {
524 at = self.step(decode(instruction)?, at)?;
525 }
526 Ok(())
527 }
528
529 fn store(&mut self, count: usize) -> Result<(), Fault> {
534 let wanted = count.saturating_add(1);
535 let at = self
536 .stack
537 .len()
538 .checked_sub(wanted)
539 .ok_or_else(|| insufficient("store", wanted))?;
540 let mut taken = self.stack.split_off(at);
541 let value = taken.pop().unwrap_or(Value::Undefined);
542 let path = store::segments(&taken)?;
543 let root = path.first().copied();
544 if let Some(store::Segment::Key(name)) = root {
545 if self.protect && self.options.protects(name) {
546 return Err(EvaluationError::new(
547 "protected_root",
548 format!("store cannot write the protected root {name}"),
549 )
550 .with_root(name)
551 .into());
552 }
553 }
554 store::check(self.context.bindings(), &path)?;
555 store::write(self.context.to_mut().bindings_mut(), &path, value);
556 if let Some(root) = root.map(store::Segment::key) {
557 if self.stored_set.insert(root.clone()) {
558 self.stored.push(root);
559 }
560 }
561 Ok(())
562 }
563
564 fn step(&mut self, op: Op<'a>, at: usize) -> Result<usize, Fault> {
566 let next = at.saturating_add(1);
567 match op {
568 Op::Lit(value) => self.stack.push(value.clone()),
569 Op::Load(name) => self.load(name)?,
570 Op::Compare(operator) => {
571 let (Some(right), Some(left)) = (self.stack.pop(), self.stack.pop()) else {
572 return Err(insufficient("compare", 2).into());
573 };
574 self.stack.push(compare::compare(operator, &left, &right));
575 }
576 Op::Not => self.negate("logical_not")?,
577 Op::UnaryBang => self.negate("unary_bang")?,
578 Op::UnaryMinus => {
579 let top = self
580 .stack
581 .last_mut()
582 .ok_or_else(|| insufficient("unary_minus", 1))?;
583 *top = match &*top {
584 Value::Integer(number) => {
585 Value::Integer(number.checked_neg().ok_or_else(|| {
586 EvaluationError::new(
587 "integer_overflow",
588 format!("-({number}) is outside the 64-bit integer range"),
589 )
590 })?)
591 }
592 Value::Float(number) => Value::Float(-number),
593 other => return Err(mismatch("unary_minus", "number", other)),
594 };
595 }
596 Op::Arithmetic(operation) => {
597 let (right, left) = self.pair(operation.name())?;
598 self.stack.push(arithmetic::apply(operation, left, right)?);
599 }
600 Op::Access(property) => {
601 let target = self.stack.pop().ok_or_else(|| insufficient("access", 1))?;
602 self.stack.push(access::access(target, property));
603 }
604 Op::BracketAccess => {
605 let (key, target) = self.pair("bracket_access")?;
606 self.stack.push(access::bracket(target, &key)?);
607 }
608 Op::In => {
609 let (container, needle) = self.pair("in")?;
610 self.stack.push(access::containment(&container, &needle));
611 }
612 Op::Contains => {
613 let (needle, container) = self.pair("contains")?;
614 self.stack.push(access::containment(&container, &needle));
615 }
616 Op::Cast(target) => {
617 let value = self.stack.pop().ok_or_else(|| insufficient("cast", 1))?;
618 self.stack.push(cast::cast(value, target)?);
619 }
620 Op::Presence(question) => {
621 let value = self
622 .stack
623 .pop()
624 .ok_or_else(|| insufficient("presence", 1))?;
625 self.stack.push(presence::presence(&value, question));
626 }
627 Op::Intersects => {
628 let (right, left) = self.pair("intersects")?;
629 self.stack.push(presence::intersects(&left, &right));
630 }
631 Op::MakeList(count) => {
632 let at = self
633 .stack
634 .len()
635 .checked_sub(count)
636 .ok_or_else(|| insufficient("make_list", count))?;
637 let items = self.stack.split_off(at);
638 self.stack.push(Value::List(items));
639 }
640 Op::ObjectNew => self.stack.push(Value::Map(crate::Map::new())),
641 Op::ObjectSet(key) => {
642 let (value, target) = self.pair("object_set")?;
643 self.stack.push(rich::object_set(target, key, value)?);
644 }
645 Op::Duration(pairs) => self.stack.push(Value::Duration(rich::duration(pairs)?)),
646 Op::RelativeDate(direction) => {
647 let top = self
648 .stack
649 .pop()
650 .ok_or_else(|| insufficient("relative_date", 1))?;
651 let (duration, sign) = rich::relative(&top, direction)?;
652 let now = self.now()?;
653 self.stack.push(rich::shift(now, &duration, sign)?);
654 }
655 Op::Call(name, count) => {
656 let depth = self.stack.len();
657 let at = depth.checked_sub(count).ok_or_else(|| {
658 EvaluationError::new(
659 "insufficient_arguments",
660 format!(
661 "Function {name}() expects {count} arguments, but only {depth} values on stack"
662 ),
663 )
664 })?;
665 let arguments = self.stack.split_off(at);
666 let answer = self.call(name, &arguments)?;
667 self.stack.push(answer);
668 }
669 Op::Store(count) => self.store(count)?,
670 Op::Pop => {
671 self.last = self.stack.pop().ok_or_else(|| insufficient("pop", 1))?;
672 }
673 Op::Jump(offset) => return Ok(at.saturating_add(offset)),
674 Op::PopJumpIfFalsy(offset) => {
675 let top = self
676 .stack
677 .pop()
678 .ok_or_else(|| insufficient("pop_jump_if_falsy", 1))?;
679 match top {
680 Value::Bool(true) => {}
681 Value::Bool(false) | Value::Null | Value::Undefined => {
682 return Ok(at.saturating_add(offset));
683 }
684 other => return Err(mismatch("pop_jump_if_falsy", "boolean", &other)),
685 }
686 }
687 Op::JumpBackward(offset) => {
688 let target = at
689 .checked_sub(offset)
690 .ok_or_else(|| unknown("jump_backward to before the first instruction"))?;
691 self.budget = self.budget.checked_sub(1).ok_or_else(|| {
692 EvaluationError::new(
693 "loop_budget_exceeded",
694 "the loop budget is spent at a backward jump",
695 )
696 })?;
697 return Ok(target);
698 }
699 Op::JumpIfFalsyOrPop(offset) => {
700 if !self.condition("jump_if_falsy_or_pop")? {
701 return Ok(at.saturating_add(offset));
702 }
703 self.stack.pop();
704 }
705 Op::JumpIfTrueOrPop(offset) => {
706 if self.condition("jump_if_true_or_pop")? {
707 return Ok(at.saturating_add(offset));
708 }
709 self.stack.pop();
710 }
711 }
712 Ok(next)
713 }
714
715 fn pair(&mut self, operation: &str) -> Result<(Value, Value), Fault> {
717 let (Some(top), Some(beneath)) = (self.stack.pop(), self.stack.pop()) else {
718 return Err(insufficient(operation, 2).into());
719 };
720 Ok((top, beneath))
721 }
722
723 fn now(&mut self) -> Result<crate::DateTime, EvaluationError> {
728 if let Some(now) = self.now {
729 return Ok(now);
730 }
731 let now = self.options.now().ok_or_else(|| {
732 EvaluationError::new("clock_failed", "the clock gave no current time")
733 })?;
734 self.now = Some(now);
735 Ok(now)
736 }
737
738 fn call(&mut self, name: &str, arguments: &[Value]) -> Result<Value, EvaluationError> {
744 if let Some(function) = self.options.host_function(name) {
745 let answer = function(arguments).map_err(library::refused)?;
746 crate::boundary::check(&answer)?;
747 return Ok(answer);
748 }
749 let Some(function) = library::find(name) else {
750 return Err(library::refused(format!("Unknown function: {name}")));
751 };
752 if !function.arity.admits(arguments.len()) {
753 return Err(library::refused(format!(
754 "Function {name}() expects {} arguments, got {}",
755 function.arity.describe(),
756 arguments.len()
757 )));
758 }
759 (function.body)(arguments, self)
760 }
761
762 fn load(&mut self, name: &'a str) -> Result<(), Fault> {
765 match self.context.root(name) {
766 Some(value) => self.stack.push(value.clone()),
767 None if self.on_unbound == OnUnbound::Error => {
768 return Err(Fault::Error(unbound(name).into()));
769 }
770 None => {
771 self.unbound.get_or_insert(name);
772 self.stack.push(Value::Undefined);
773 }
774 }
775 Ok(())
776 }
777
778 fn negate(&mut self, operation: &str) -> Result<(), Fault> {
781 let top = self
782 .stack
783 .last_mut()
784 .ok_or_else(|| insufficient(operation, 1))?;
785 match top {
786 Value::Bool(flag) => *flag = !*flag,
787 other => return Err(mismatch(operation, "boolean", other)),
788 }
789 Ok(())
790 }
791
792 fn condition(&self, operation: &str) -> Result<bool, Fault> {
795 match self.stack.last() {
796 Some(Value::Bool(flag)) => Ok(*flag),
797 Some(Value::Null | Value::Undefined) => Ok(false),
798 Some(other) => Err(mismatch(operation, "boolean", other)),
799 None => Err(insufficient(operation, 1).into()),
800 }
801 }
802}
803
804impl library::Run for Machine<'_> {
805 fn now(&mut self) -> Result<crate::DateTime, EvaluationError> {
806 Machine::now(self)
807 }
808
809 fn draw(&mut self) -> u64 {
812 if let Some(random) = self.options.random_source() {
813 return random();
814 }
815 let (keys, draws) = self.random.get_or_insert_with(|| (RandomState::new(), 0));
816 *draws = draws.wrapping_add(1);
817 keys.hash_one(*draws)
818 }
819}
820
821fn unbound(name: &str) -> UndefinedVariableError {
822 UndefinedVariableError::new(
823 "unbound_variable",
824 format!("the variable {name} is not bound"),
825 )
826}
827
828pub fn evaluate<P: Program>(
870 program: P,
871 context: &Context,
872 options: &Options,
873) -> Result<Value, Error> {
874 let instructions = program.resolve(Mode::Expression)?;
875 context.check()?;
876 let mut machine = Machine::new(context, options, false);
877 let outcome = machine.run(&instructions.list).and_then(|()| {
878 machine.stack.pop().ok_or_else(|| {
879 EvaluationError::new("empty_stack", "the run ended with nothing on the stack").into()
880 })
881 });
882 match outcome {
883 Ok(Value::Undefined) => match machine.unbound {
884 Some(name) => Err(unbound(name).into()),
885 None => Ok(Value::Undefined),
886 },
887 Ok(value) => Ok(value),
888 Err(fault) => Err(fault_error(fault, machine.unbound)),
889 }
890}
891
892fn fault_error(fault: Fault, first_unbound: Option<&str>) -> Error {
896 match fault {
897 Fault::RejectedUndefined(error) => match first_unbound {
898 Some(name) => unbound(name).into(),
899 None => error.into(),
900 },
901 Fault::Error(error) => error,
902 }
903}
904
905fn statements<P: Program>(
908 program: P,
909 context: &Context,
910 options: &Options,
911 keep_value: bool,
912) -> Result<Execution, Stopped> {
913 let refused = |error: Error| Stopped {
914 error: Box::new(error),
915 context: context.clone(),
916 stored_roots: Vec::new(),
917 };
918 let instructions = program.resolve(Mode::Statements).map_err(refused)?;
919 context.check().map_err(|error| refused(error.into()))?;
920 let mut machine = Machine::new(context, options, true);
921 let outcome = machine.run(&instructions.list);
922 let Machine {
923 context: left,
924 stored,
925 last,
926 unbound: first_unbound,
927 ..
928 } = machine;
929 let context = left.into_owned();
930 match outcome {
931 Ok(()) => Ok(Execution {
932 context,
933 value: keep_value.then_some(last),
934 stored_roots: stored,
935 }),
936 Err(fault) => Err(Stopped {
937 error: Box::new(fault_error(fault, first_unbound)),
938 context,
939 stored_roots: stored,
940 }),
941 }
942}
943
944pub fn execute<P: Program>(
990 program: P,
991 context: &Context,
992 options: &Options,
993) -> Result<Execution, Stopped> {
994 statements(program, context, options, false)
995}
996
997pub fn execute_value<P: Program>(
1016 program: P,
1017 context: &Context,
1018 options: &Options,
1019) -> Result<Execution, Stopped> {
1020 statements(program, context, options, true)
1021}
1022
1023#[cfg(test)]
1024mod tests {
1025 use super::*;
1026
1027 fn run_with(text: &str, context: &Context, options: &Options) -> Result<Value, Error> {
1028 evaluate(&Instructions::from_json(text).unwrap(), context, options)
1029 }
1030
1031 fn run(text: &str) -> Result<Value, Error> {
1032 run_with(text, &Context::new(), &Options::new())
1033 }
1034
1035 fn refusal(text: &str) -> (String, String) {
1038 match run(text) {
1039 Ok(value) => ("no error".to_owned(), format!("{value:?}")),
1040 Err(error) => (error.type_name().to_owned(), error.reason().to_owned()),
1041 }
1042 }
1043
1044 fn evaluation(reason: &str) -> (String, String) {
1045 ("EvaluationError".to_owned(), reason.to_owned())
1046 }
1047
1048 fn mismatched(reason: &str) -> (String, String) {
1049 ("TypeMismatchError".to_owned(), reason.to_owned())
1050 }
1051
1052 #[test]
1055 fn an_unknown_or_retired_opcode_is_refused_by_name_before_its_operands() {
1056 assert_eq!(refusal(r#"[["and"]]"#), evaluation("retired_opcode"));
1057 assert_eq!(
1058 refusal(r#"[["or",1,2,{"x":[]}]]"#),
1059 evaluation("retired_opcode")
1060 );
1061 for text in [
1062 r#"[["overlaps"]]"#,
1063 r#"[["bogus",1]]"#,
1064 r#"[[]]"#,
1065 r#"[[5]]"#,
1066 r#"[5]"#,
1067 r#"[["lit",1],"lit"]"#,
1068 ] {
1069 assert_eq!(refusal(text), evaluation("unknown_instruction"), "{text}");
1070 }
1071 assert!(
1072 RETIRED
1073 .iter()
1074 .all(|(name, _)| OPCODES.iter().all(|row| row.name != *name))
1075 );
1076 }
1077
1078 #[test]
1081 fn operands_of_the_wrong_shape_are_an_unknown_instruction() {
1082 for text in [
1083 r#"[["lit"]]"#,
1084 r#"[["lit",1,2]]"#,
1085 r#"[["load",5]]"#,
1086 r#"[["load"]]"#,
1087 r#"[["lit",1],["lit",1],["compare","FOO"]]"#,
1088 r#"[["lit",1],["lit",1],["compare",1]]"#,
1089 r#"[["lit",true],["not",1]]"#,
1090 r#"[["lit",true],["unary_bang",null]]"#,
1091 r#"[["lit",1],["unary_minus",1]]"#,
1092 r#"[["lit",true],["jump_if_falsy_or_pop",0]]"#,
1093 r#"[["lit",true],["jump_if_true_or_pop",-1]]"#,
1094 r#"[["lit",true],["jump_if_true_or_pop",1.0]]"#,
1095 r#"[["lit",true],["jump_if_true_or_pop"]]"#,
1096 r#"[["lit",1],["lit",2],["add",1]]"#,
1097 r#"[["lit",{}],["access"]]"#,
1098 r#"[["lit",{}],["access",1]]"#,
1099 r#"[["lit",{}],["lit","a"],["bracket_access","a"]]"#,
1100 r#"[["lit",1],["lit",[1]],["in",1]]"#,
1101 r#"[["lit",[1]],["lit",1],["contains",null]]"#,
1102 r#"[["make_list",-1]]"#,
1103 r#"[["make_list",1.0]]"#,
1104 r#"[["lit",1],["store",-1]]"#,
1105 r#"[["lit",1],["store","1"]]"#,
1106 r#"[["lit",1],["store"]]"#,
1107 r#"[["lit",1],["pop",1]]"#,
1108 r#"[["jump",0]]"#,
1109 r#"[["jump",-2]]"#,
1110 r#"[["lit",true],["pop_jump_if_falsy",0]]"#,
1111 r#"[["lit",1],["jump_backward",-1]]"#,
1112 r#"[["lit",1],["jump_backward",1.0]]"#,
1113 r#"[["make_list"]]"#,
1114 ] {
1115 assert_eq!(refusal(text), evaluation("unknown_instruction"), "{text}");
1116 }
1117 }
1118
1119 #[test]
1122 fn the_answer_is_the_top_of_the_stack() {
1123 assert_eq!(run(r#"[["lit",42]]"#).unwrap(), Value::from(42));
1124 assert_eq!(run(r#"[["lit",1],["lit",2]]"#).unwrap(), Value::from(2));
1125 assert_eq!(
1126 run(r#"[["lit",{"$type":"undefined"}]]"#).unwrap(),
1127 Value::Undefined
1128 );
1129 assert_eq!(refusal("[]"), evaluation("empty_stack"));
1130 }
1131
1132 #[test]
1135 fn compare_pops_the_right_operand_then_the_left() {
1136 assert_eq!(
1137 run(r#"[["lit",3],["lit",5],["compare","LT"]]"#).unwrap(),
1138 Value::from(true)
1139 );
1140 assert_eq!(
1141 run(r#"[["lit",3],["lit",5],["lit",4],["compare","GT"]]"#).unwrap(),
1142 Value::from(true)
1143 );
1144 assert_eq!(
1145 refusal(r#"[["lit",1],["compare","EQ"]]"#),
1146 evaluation("insufficient_operands")
1147 );
1148 assert_eq!(
1149 refusal(r#"[["compare","EQ"]]"#),
1150 evaluation("insufficient_operands")
1151 );
1152 }
1153
1154 #[test]
1157 fn not_and_unary_bang_negate_a_boolean_and_refuse_anything_else() {
1158 assert_eq!(
1159 run(r#"[["lit",true],["not"]]"#).unwrap(),
1160 Value::from(false)
1161 );
1162 assert_eq!(
1163 run(r#"[["lit",false],["unary_bang"]]"#).unwrap(),
1164 Value::from(true)
1165 );
1166 assert_eq!(refusal(r#"[["lit",5],["not"]]"#), mismatched("logical_not"));
1167 assert_eq!(
1168 refusal(r#"[["lit",null],["not"]]"#),
1169 mismatched("logical_not")
1170 );
1171 assert_eq!(
1172 refusal(r#"[["lit",{"$type":"undefined"}],["unary_bang"]]"#),
1173 mismatched("unary_bang")
1174 );
1175 assert_eq!(refusal(r#"[["not"]]"#), evaluation("insufficient_operands"));
1176 assert_eq!(
1177 refusal(r#"[["unary_bang"]]"#),
1178 evaluation("insufficient_operands")
1179 );
1180 }
1181
1182 #[test]
1184 fn unary_minus_negates_a_number_and_refuses_an_overflow() {
1185 assert_eq!(
1186 run(r#"[["lit",5],["unary_minus"]]"#).unwrap(),
1187 Value::from(-5)
1188 );
1189 assert_eq!(
1190 run(r#"[["lit",2.5],["unary_minus"]]"#).unwrap(),
1191 Value::from(-2.5)
1192 );
1193 assert_eq!(
1194 run(r#"[["lit",-9223372036854775807],["unary_minus"]]"#).unwrap(),
1195 Value::from(i64::MAX)
1196 );
1197 assert_eq!(
1198 refusal(r#"[["lit",-9223372036854775808],["unary_minus"]]"#),
1199 evaluation("integer_overflow")
1200 );
1201 assert_eq!(
1202 refusal(r#"[["lit","x"],["unary_minus"]]"#),
1203 mismatched("unary_minus")
1204 );
1205 assert_eq!(
1206 refusal(r#"[["unary_minus"]]"#),
1207 evaluation("insufficient_operands")
1208 );
1209 }
1210
1211 #[test]
1213 fn the_short_circuit_jumps_keep_the_value_they_jump_on() {
1214 let and =
1215 |left: &str| format!(r#"[["lit",{left}],["jump_if_falsy_or_pop",2],["lit","b"]]"#);
1216 let or = |left: &str| format!(r#"[["lit",{left}],["jump_if_true_or_pop",2],["lit","b"]]"#);
1217 assert_eq!(run(&and("true")).unwrap(), Value::from("b"));
1218 assert_eq!(run(&and("false")).unwrap(), Value::from(false));
1219 assert_eq!(run(&and("null")).unwrap(), Value::Null);
1220 assert_eq!(
1221 run(&and(r#"{"$type":"undefined"}"#)).unwrap(),
1222 Value::Undefined
1223 );
1224 assert_eq!(run(&or("true")).unwrap(), Value::from(true));
1225 assert_eq!(run(&or("false")).unwrap(), Value::from("b"));
1226 assert_eq!(run(&or("null")).unwrap(), Value::from("b"));
1227 assert_eq!(
1228 run(&or(r#"{"$type":"undefined"}"#)).unwrap(),
1229 Value::from("b")
1230 );
1231 assert_eq!(refusal(&and("1")), mismatched("jump_if_falsy_or_pop"));
1232 assert_eq!(refusal(&or("\"x\"")), mismatched("jump_if_true_or_pop"));
1233 assert_eq!(
1234 refusal(r#"[["jump_if_falsy_or_pop",1]]"#),
1235 evaluation("insufficient_operands")
1236 );
1237 assert_eq!(
1238 refusal(r#"[["jump_if_true_or_pop",1]]"#),
1239 evaluation("insufficient_operands")
1240 );
1241 }
1242
1243 #[test]
1246 fn a_jump_lands_at_its_offset_and_a_skipped_instruction_is_never_read() {
1247 assert_eq!(
1248 run(
1249 r#"[["lit",false],["jump_if_falsy_or_pop",2],["bogus"],["lit",1],["compare","EQ"]]"#
1250 )
1251 .ok(),
1252 Some(Value::Undefined)
1253 );
1254 assert_eq!(
1255 run(r#"[["lit",true],["jump_if_true_or_pop",2],["and"]]"#).unwrap(),
1256 Value::from(true)
1257 );
1258 assert_eq!(
1259 run(r#"[["lit",true],["jump_if_true_or_pop",9223372036854775807],["and"]]"#).unwrap(),
1260 Value::from(true)
1261 );
1262 }
1263
1264 #[test]
1267 fn an_unbound_root_is_reported_where_its_undefined_is_the_answer_or_refused() {
1268 let options = Options::new();
1269 let mut context = Context::new();
1270 context.insert("bound", Value::Undefined);
1271 context.insert("flag", Value::from(true));
1272 let at = |text: &str| run_with(text, &context, &options);
1273 let unbound_error = |text: &str| {
1274 let error = at(text).unwrap_err();
1275 (
1276 error.type_name().to_owned(),
1277 error.reason().to_owned(),
1278 error.message().to_owned(),
1279 )
1280 };
1281 let named = |name: &str| {
1282 (
1283 "UndefinedVariableError".to_owned(),
1284 "unbound_variable".to_owned(),
1285 format!("the variable {name} is not bound"),
1286 )
1287 };
1288 assert_eq!(unbound_error(r#"[["load","missing"]]"#), named("missing"));
1289 assert_eq!(
1290 unbound_error(r#"[["load","a"],["load","b"],["compare","EQ"]]"#),
1291 named("a")
1292 );
1293 assert_eq!(unbound_error(r#"[["load","a"],["not"]]"#), named("a"));
1294 assert_eq!(
1295 unbound_error(r#"[["load","a"],["pop_missing_opcode"]]"#).1,
1296 "unknown_instruction"
1297 );
1298 assert_eq!(at(r#"[["load","bound"]]"#).unwrap(), Value::Undefined);
1299 assert_eq!(
1300 at(r#"[["load","bound"],["not"]]"#).unwrap_err().type_name(),
1301 "TypeMismatchError"
1302 );
1303 assert_eq!(
1304 at(r#"[["load","flag"],["jump_if_true_or_pop",2],["load","skipped"]]"#).unwrap(),
1305 Value::from(true)
1306 );
1307 assert_eq!(
1308 at(r#"[["load","missing"],["jump_if_falsy_or_pop",2],["lit",1],["lit",true]]"#)
1309 .unwrap(),
1310 Value::from(true)
1311 );
1312 assert_eq!(
1313 at(r#"[["load","missing"],["lit",1],["unary_minus"],["not"]]"#)
1314 .unwrap_err()
1315 .type_name(),
1316 "TypeMismatchError"
1317 );
1318 }
1319
1320 #[test]
1322 fn under_the_error_policy_a_load_of_an_unbound_root_fails_at_once() {
1323 let options = Options::new().on_unbound(OnUnbound::Error);
1324 let mut context = Context::new();
1325 context.insert("x", Value::Undefined);
1326 let error = run_with(
1329 r#"[["load","missing"],["jump_if_falsy_or_pop",2],["lit",1],["lit",true]]"#,
1330 &context,
1331 &options,
1332 )
1333 .err()
1334 .map(|error| (error.type_name().to_owned(), error.reason().to_owned()));
1335 assert_eq!(
1336 error,
1337 Some((
1338 "UndefinedVariableError".to_owned(),
1339 "unbound_variable".to_owned()
1340 ))
1341 );
1342 assert_eq!(
1343 run_with(r#"[["load","x"]]"#, &context, &options).unwrap(),
1344 Value::Undefined
1345 );
1346 }
1347
1348 fn failure(text: &str, options: &Options) -> (String, String, String) {
1352 match run_with(text, &Context::new(), options) {
1353 Ok(value) => ("no error".to_owned(), format!("{value:?}"), String::new()),
1354 Err(error) => (
1355 error.type_name().to_owned(),
1356 error.reason().to_owned(),
1357 error.message().to_owned(),
1358 ),
1359 }
1360 }
1361
1362 fn function_error(message: &str) -> (String, String, String) {
1363 (
1364 "EvaluationError".to_owned(),
1365 message.to_owned(),
1366 message.to_owned(),
1367 )
1368 }
1369
1370 #[test]
1373 fn call_passes_its_arguments_deepest_first_and_leaves_the_rest() {
1374 assert_eq!(
1375 run(r#"[["lit",0],["lit","hello world"],["lit",6],["lit",3],["call","substring",3]]"#)
1376 .ok(),
1377 Some(Value::from("wor"))
1378 );
1379 assert_eq!(
1380 run(r#"[["lit",0],["lit","x"],["call","len",1],["make_list",2]]"#).unwrap(),
1381 Value::from(vec![0.into(), 1.into()])
1382 );
1383 assert_eq!(
1384 run(r#"[["call","Math.random",0],["lit",1],["compare","LT"]]"#).unwrap(),
1385 Value::from(true)
1386 );
1387 }
1388
1389 #[test]
1392 fn call_refuses_too_few_values_an_unknown_name_and_a_wrong_arity() {
1393 let options = Options::new();
1394 assert_eq!(
1395 failure(r#"[["lit",1],["call","Math.max",2]]"#, &options),
1396 (
1397 "EvaluationError".to_owned(),
1398 "insufficient_arguments".to_owned(),
1399 "Function Math.max() expects 2 arguments, but only 1 values on stack".to_owned()
1400 )
1401 );
1402 assert_eq!(
1403 failure(r#"[["call","nope",1]]"#, &options).1,
1404 "insufficient_arguments"
1405 );
1406 assert_eq!(
1407 failure(r#"[["lit",1],["call","nope",1]]"#, &options),
1408 function_error("Unknown function: nope")
1409 );
1410 assert_eq!(
1411 failure(r#"[["lit",1],["lit",2],["call","len",2]]"#, &options),
1412 function_error("Function len() expects 1 arguments, got 2")
1413 );
1414 assert_eq!(
1415 failure(r#"[["lit","a"],["call","substring",1]]"#, &options),
1416 function_error("Function substring() expects 2 or 3 arguments, got 1")
1417 );
1418 assert_eq!(
1419 failure(r#"[["lit",1],["call","Math.random",1]]"#, &options),
1420 function_error("Function Math.random() expects 0 arguments, got 1")
1421 );
1422 for text in [
1423 r#"[["call","len"]]"#,
1424 r#"[["call","len",-1]]"#,
1425 r#"[["call","len",1.0]]"#,
1426 r#"[["call",1,1]]"#,
1427 r#"[["call","len",1,1]]"#,
1428 ] {
1429 assert_eq!(refusal(text), evaluation("unknown_instruction"), "{text}");
1430 }
1431 assert_eq!(
1432 refusal(r#"[["call","len",9223372036854775807]]"#),
1433 evaluation("insufficient_arguments")
1434 );
1435 }
1436
1437 #[test]
1440 fn a_host_function_shadows_the_library_for_its_options_only() {
1441 let seen = std::sync::Mutex::new(Vec::new());
1442 let options = Options::new()
1443 .function("len", |arguments| {
1444 seen.lock().unwrap().push(arguments.to_vec());
1445 Ok(Value::from(-1))
1446 })
1447 .function("twice", |arguments| match arguments {
1448 [Value::Integer(x)] => Ok(Value::from(x * 2)),
1449 _ => Err("twice takes one integer".to_owned()),
1450 });
1451 let program = r#"[["lit","abc"],["lit",true],["call","len",2]]"#;
1452 assert_eq!(
1453 run_with(program, &Context::new(), &options).ok(),
1454 Some(Value::from(-1))
1455 );
1456 assert_eq!(
1457 *seen.lock().unwrap(),
1458 vec![vec![Value::from("abc"), Value::from(true)]]
1459 );
1460 assert_eq!(
1461 run(r#"[["lit","abc"],["call","len",1]]"#).unwrap(),
1462 Value::from(3)
1463 );
1464 assert_eq!(
1465 run_with(
1466 r#"[["lit",21],["call","twice",1]]"#,
1467 &Context::new(),
1468 &options
1469 )
1470 .unwrap(),
1471 Value::from(42)
1472 );
1473 assert_eq!(
1474 failure(r#"[["lit","x"],["call","twice",1]]"#, &options),
1475 function_error("twice takes one integer")
1476 );
1477 assert_eq!(
1478 failure(r#"[["lit",1],["call","twice",1]]"#, &Options::new()),
1479 function_error("Unknown function: twice")
1480 );
1481 }
1482
1483 #[test]
1486 fn a_host_functions_answer_is_checked_against_the_value_domain() {
1487 let options = Options::new()
1488 .function("infinite", |_| Ok(Value::Float(f64::INFINITY)))
1489 .function("deep", |_| {
1490 let mut deep = Value::Null;
1491 for _ in 0..101 {
1492 deep = Value::from(vec![deep]);
1493 }
1494 Ok(deep)
1495 })
1496 .function("nothing", |_| Ok(Value::Undefined));
1497 assert_eq!(
1498 failure(r#"[["call","infinite",0]]"#, &options).1,
1499 "non_finite_number"
1500 );
1501 assert_eq!(
1502 failure(r#"[["call","deep",0]]"#, &options).1,
1503 "depth_limit_exceeded"
1504 );
1505 assert_eq!(
1506 run_with(r#"[["call","nothing",0]]"#, &Context::new(), &options).unwrap(),
1507 Value::Undefined
1508 );
1509 }
1510
1511 #[test]
1514 fn math_random_draws_from_the_source_passed_per_call() {
1515 let draws = std::sync::atomic::AtomicU64::new(0);
1516 let options =
1517 Options::new().random(|| draws.fetch_add(1, std::sync::atomic::Ordering::SeqCst) << 62);
1518 let program = r#"[["call","Math.random",0],["call","Math.random",0],["make_list",2]]"#;
1519 assert_eq!(
1520 run_with(program, &Context::new(), &options).unwrap(),
1521 Value::from(vec![0.0.into(), 0.25.into()])
1522 );
1523 let drawn = run(program).unwrap();
1525 let Value::List(drawn) = &drawn else {
1526 panic!("a list")
1527 };
1528 assert_ne!(drawn[0], drawn[1]);
1529 for value in drawn {
1530 let Value::Float(number) = *value else {
1531 panic!("a float")
1532 };
1533 assert!((0.0..1.0).contains(&number));
1534 }
1535 }
1536
1537 #[test]
1540 fn date_now_reads_the_runs_clock_once() {
1541 let reads = std::sync::atomic::AtomicU32::new(0);
1542 let options = Options::new().clock(|| {
1543 let read = reads.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1544 crate::DateTime::from_unix(i64::from(read) * 86_400, 0)
1545 });
1546 let program = r#"[["call","Date.now",0],["call","Date.now",0],["make_list",2]]"#;
1547 let epoch = Value::from(crate::DateTime::from_unix(0, 0).unwrap());
1548 assert_eq!(
1549 run_with(program, &Context::new(), &options).unwrap(),
1550 Value::from(vec![epoch.clone(), epoch])
1551 );
1552 assert_eq!(reads.load(std::sync::atomic::Ordering::SeqCst), 1);
1553 assert_eq!(
1554 failure(r#"[["call","Date.now",0]]"#, &Options::new().clock(|| None)).1,
1555 "clock_failed"
1556 );
1557 }
1558
1559 #[test]
1562 fn a_function_refusing_an_unbound_argument_is_an_evaluation_error() {
1563 assert_eq!(
1564 failure(r#"[["load","missing"],["call","len",1]]"#, &Options::new()),
1565 function_error("len() expects a string argument")
1566 );
1567 }
1568
1569 #[test]
1571 fn a_context_outside_the_value_domain_is_refused_before_anything_runs() {
1572 let mut context = Context::new();
1573 context.insert("x", Value::Float(f64::INFINITY));
1574 let error = run_with(r#"[["lit",1]]"#, &context, &Options::new())
1575 .err()
1576 .map(|error| (error.type_name().to_owned(), error.reason().to_owned()));
1577 assert_eq!(
1578 error,
1579 Some(("EvaluationError".to_owned(), "non_finite_number".to_owned()))
1580 );
1581 }
1582
1583 #[test]
1586 fn pop_jump_if_falsy_pops_always_and_jumps_on_a_falsy_value() {
1587 let taken = |condition: &str| {
1588 run(&format!(
1589 r#"[["lit","kept"],["lit",{condition}],["pop_jump_if_falsy",2],["lit","fell"]]"#
1590 ))
1591 };
1592 for falsy in ["false", "null", r#"{"$type":"undefined"}"#] {
1593 assert_eq!(taken(falsy).unwrap(), Value::from("kept"), "{falsy}");
1594 }
1595 assert_eq!(taken("true").unwrap(), Value::from("fell"));
1596 assert_eq!(
1597 refusal(r#"[["lit",0],["pop_jump_if_falsy",1]]"#),
1598 mismatched("pop_jump_if_falsy")
1599 );
1600 assert_eq!(
1601 refusal(r#"[["pop_jump_if_falsy",1]]"#),
1602 evaluation("insufficient_operands")
1603 );
1604 assert_eq!(
1605 run(r#"[["lit",1],["jump",2],["bogus"],["lit",2]]"#).unwrap(),
1606 Value::from(2)
1607 );
1608 assert_eq!(
1609 run(r#"[["lit",1],["jump",9223372036854775807],["bogus"]]"#).unwrap(),
1610 Value::from(1)
1611 );
1612 }
1613
1614 #[test]
1617 fn jump_backward_before_the_first_instruction_is_unknown_before_the_budget_is_read() {
1618 let none = Options::new().loop_budget(0);
1619 let at = |text: &str| {
1620 run_with(text, &Context::new(), &none)
1621 .err()
1622 .map(|error| (error.type_name().to_owned(), error.reason().to_owned()))
1623 };
1624 assert_eq!(
1625 at(r#"[["lit",1],["jump_backward",2]]"#),
1626 Some(evaluation("unknown_instruction"))
1627 );
1628 assert_eq!(
1629 at(r#"[["lit",1],["jump_backward",1]]"#),
1630 Some(evaluation("loop_budget_exceeded"))
1631 );
1632 let once = Options::new().loop_budget(1);
1634 assert_eq!(
1635 run_with(
1636 r#"[["lit",1],["pop_jump_if_falsy",3],["lit",false],["jump_backward",3],["lit",0]]"#,
1637 &Context::new(),
1638 &once
1639 )
1640 .unwrap_err()
1641 .reason(),
1642 "pop_jump_if_falsy"
1643 );
1644 }
1645
1646 #[test]
1649 fn store_pops_the_value_then_its_segments_and_writes_root_first() {
1650 assert_eq!(
1651 run(r#"[["lit","a"],["lit","b"],["lit",1],["store",2],["load","a"]]"#).unwrap(),
1652 Value::Map([("b", Value::from(1))].into_iter().collect())
1653 );
1654 assert_eq!(
1655 run(r#"[["lit","rest"],["lit","x"],["lit",1],["store",1],["pop"],["load","x"]]"#)
1656 .unwrap(),
1657 Value::from(1)
1658 );
1659 assert_eq!(
1660 refusal(r#"[["lit",1],["store",0]]"#),
1661 evaluation("not_assignable")
1662 );
1663 assert_eq!(
1664 refusal(r#"[["lit","x"],["store",1]]"#),
1665 evaluation("insufficient_operands")
1666 );
1667 assert_eq!(
1668 refusal(r#"[["lit","x"],["store",9223372036854775807]]"#),
1669 evaluation("insufficient_operands")
1670 );
1671 assert_eq!(
1672 refusal(r#"[["lit",true],["lit",1],["store",1]]"#),
1673 mismatched("store")
1674 );
1675 assert_eq!(
1678 refusal(r#"[["load","missing"],["lit",1],["store",1]]"#),
1679 (
1680 "UndefinedVariableError".to_owned(),
1681 "unbound_variable".to_owned()
1682 )
1683 );
1684 assert_eq!(refusal(r#"[["pop"]]"#), evaluation("insufficient_operands"));
1685 }
1686}