Skip to main content

predicator_rs/
evaluator.rs

1//! The stack machine: it runs an instruction list over a context in
2//! expression mode, as the reference's instruction-set text states it.
3//!
4//! Dispatch is table driven. [`OPCODES`] holds one row per opcode this
5//! build runs, each reading its own operands into an [`Op`]; an opcode is
6//! looked up by name before any operand is read, so an opcode the build
7//! does not know, and one the instruction set has retired ([`RETIRED`]), is
8//! refused by its name alone. An opcode a later tier adds is a row added to
9//! the table and an arm added to [`Machine::step`].
10//!
11//! The arithmetic instructions live in `arithmetic`, reading into a value
12//! (`access`, `bracket_access`) and the containment `in` and `contains`
13//! share in `access`, the rich types (`object_new`, `object_set`,
14//! `duration`, `relative_date`) in `rich`, the function library `call`
15//! runs in `library`, the write `store` makes in `store`, the conversions
16//! `cast` makes in `cast`, and `presence` and `intersects` in `presence`.
17//!
18//! One machine runs both of the instruction set's modes: [`evaluate`]
19//! (expression mode) answers the top of the stack, and [`execute`] and
20//! [`execute_value`] (statement mode) answer the context the run leaves.
21
22mod 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
45/// The program an entry point is given: what can be run as an instruction
46/// list. The trait is sealed; it is implemented for `&Instructions`, which
47/// runs as it is, and for `&str`, a source, which [`evaluate`] compiles as
48/// an expression ([`compile`](crate::compile)) and [`execute`] and
49/// [`execute_value`] as a statement program
50/// ([`compile_program`](crate::compile_program)) before it runs.
51///
52/// ```
53/// use predicator_rs::{Context, Options, Value, compile, evaluate};
54///
55/// let options = Options::new();
56/// let from_source = evaluate("2 * 3", &Context::new(), &options)?;
57/// let from_list = evaluate(&compile("2 * 3")?, &Context::new(), &options)?;
58/// assert_eq!((from_source, from_list), (Value::from(6), Value::from(6)));
59/// # Ok::<(), predicator_rs::Error>(())
60/// ```
61pub trait Program: sealed::Sealed {}
62
63mod sealed {
64    use crate::{Error, Instructions, compile, compile_program};
65    use std::borrow::Cow;
66
67    /// How an entry point reads a source: as one expression or as a
68    /// statement program.
69    #[derive(Debug, Clone, Copy)]
70    pub enum Mode {
71        /// [`evaluate`](crate::evaluate)'s reading.
72        Expression,
73        /// [`execute`](crate::execute)'s and
74        /// [`execute_value`](crate::execute_value)'s reading.
75        Statements,
76    }
77
78    /// The one method a program has: the instruction list it runs.
79    pub trait Sealed {
80        /// The instruction list, or the error that stops it being one.
81        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/// One instruction, its operands read.
106#[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
137/// One row of the dispatch table: an opcode's name and the reader of its
138/// operands, which answers `None` for operands of the wrong shape.
139pub(crate) struct Row {
140    pub(crate) name: &'static str,
141    read: for<'a> fn(&'a [Value]) -> Option<Op<'a>>,
142}
143
144/// Every opcode this build runs.
145pub(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
272/// The opcodes the instruction set has retired, each with the version that
273/// removed it.
274const 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
297/// `make_list`'s count: one non-negative integer. A count past the address
298/// space asks for more values than any stack holds.
299fn 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
308/// `call`'s operands: the function's name and a non-negative argument
309/// count. A count past the address space asks for more values than any
310/// stack holds.
311fn 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
321/// `store`'s count of path segments: one non-negative integer. A count
322/// past the address space asks for more values than any stack holds.
323fn 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
339/// `duration`'s operand: one list of unit pairs, each read when the
340/// instruction runs.
341fn read_duration(operands: &[Value]) -> Option<Op<'_>> {
342    match operands {
343        [Value::List(pairs)] => Some(Op::Duration(pairs)),
344        _ => None,
345    }
346}
347
348/// An opcode whose one operand is a string.
349fn string(operands: &[Value]) -> Option<&str> {
350    match operands {
351        [Value::String(text)] => Some(text),
352        _ => None,
353    }
354}
355
356/// An opcode that takes no operand.
357fn bare<'a>(operands: &[Value], op: Op<'a>) -> Option<Op<'a>> {
358    operands.is_empty().then_some(op)
359}
360
361/// A jump's offset: one positive integer.
362fn offset(operands: &[Value]) -> Option<usize> {
363    match operands {
364        // An offset past the address space jumps past every instruction.
365        [Value::Integer(offset)] if *offset > 0 => {
366            Some(usize::try_from(*offset).unwrap_or(usize::MAX))
367        }
368        _ => None,
369    }
370}
371
372/// The refusal of an instruction this build cannot run.
373fn unknown(name: &str) -> EvaluationError {
374    EvaluationError::new(
375        "unknown_instruction",
376        format!("unknown instruction: {name}"),
377    )
378}
379
380/// Reads `instruction`: its opcode by name first, then its operands.
381fn 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
401/// Why a run stopped.
402enum Fault {
403    /// An error, as it is.
404    Error(Error),
405    /// A type mismatch on an undefined operand, which the entry point
406    /// reports as an unbound variable when the run loaded one.
407    RejectedUndefined(TypeMismatchError),
408}
409
410impl From<EvaluationError> for Fault {
411    fn from(error: EvaluationError) -> Fault {
412        Fault::Error(error.into())
413    }
414}
415
416/// The machine's state over one run.
417struct Machine<'a> {
418    /// The context the run reads, copied the first time a `store` writes
419    /// it.
420    context: Cow<'a, Context>,
421    options: &'a Options<'a>,
422    /// Whether a `store` reads the protected roots: statement mode only.
423    protect: bool,
424    /// The back edges the run may still take.
425    budget: u64,
426    /// The roots the run stored into, in the order of the first store, and
427    /// the same roots as a set.
428    stored: Vec<Key>,
429    stored_set: BTreeSet<Key>,
430    /// What the last `pop` discarded.
431    last: Value,
432    on_unbound: OnUnbound,
433    /// The current time, once this run has read the clock.
434    now: Option<crate::DateTime>,
435    stack: Vec<Value>,
436    /// The first root this run loaded and did not find bound.
437    unbound: Option<&'a str>,
438    /// The default random source, once this run has drawn from it: hash
439    /// keys from the standard library and a count of draws.
440    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
466/// The refusal of `operand` by `operation`, which wanted `expected`.
467fn 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
481/// The refusal of a pair by `operation`, which wanted a `wanted`. It names
482/// an undefined operand when either is one, so that an unbound load is
483/// reported as such.
484fn 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    /// A machine about to run over `context` with `options`; `protect` says
501    /// whether a `store` reads the protected roots.
502    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    /// Runs `list` from its first instruction until the instruction pointer
520    /// reaches or passes its end.
521    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    /// `store`: pops the value, then `count` path segments beneath it (the
530    /// root deepest), and writes the value at that path. A path whose root
531    /// the options protect is refused, in statement mode, after its
532    /// segments are checked and before anything is written.
533    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    /// Runs one instruction at `at` and answers where the next one is.
565    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    /// The top two values, popped: the top first, then the one beneath it.
716    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    /// The current time: the clock read the first time a run asks, and the
724    /// same instant every later time. A clock with no time to give fails
725    /// the run with the reason `clock_failed`, the one refusal every
726    /// instruction that reads the time answers.
727    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    /// Calls the function `name` with `arguments`: the host function the
739    /// options pass under that name, else the library function, else none
740    /// (`Unknown function: NAME`). A host function's answer is checked
741    /// against the value domain; a library function's arity is checked
742    /// before its body runs. Every refusal is an [`EvaluationError`].
743    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    /// Pushes the value bound to the root `name`, or undefined when it is
763    /// unbound (failing at once under [`OnUnbound::Error`]).
764    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    /// `not` and `unary_bang`: the top of the stack, which must be a
779    /// boolean, negated.
780    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    /// A jump's condition, the top of the stack: `true` when it is exactly
793    /// true, `false` when it is falsy (false, null or undefined).
794    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    /// A draw from the source the options name, or from the default: the
810    /// run's own hash keys over a count of its draws.
811    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
828/// Evaluates `program` over `context` and answers the value it leaves on
829/// top of the stack.
830///
831/// The program is an `&`[`Instructions`], or a `&str` source compiled as an
832/// expression ([`compile`](crate::compile)); a source that does not compile
833/// is refused with its [`Error::Parse`]. It runs in expression mode, as the
834/// reference's instruction-set text states it: from its first instruction
835/// to its end, and its answer is the top of the stack (a run that ends with
836/// nothing on it fails with the reason `empty_stack`).
837///
838/// A variable the context does not bind is read as `options` says
839/// ([`OnUnbound`]). Under the default, a run whose answer is undefined, or
840/// that fails because an instruction refused an undefined operand, fails
841/// instead with an [`UndefinedVariableError`] (reason `unbound_variable`)
842/// naming the first unbound variable it loaded, when it loaded one.
843///
844/// The run may take as many back edges (the `jump_backward` instruction)
845/// as [`Options::loop_budget`] says, and fails with the reason
846/// `loop_budget_exceeded` at one past that. A `store` writes a copy of
847/// the context that later instructions in the run read; the context passed
848/// in is never changed, and [`Options::protected_roots`] is not read.
849///
850/// Before anything runs, every value the context binds is checked against
851/// the value domain ([`Context`]).
852///
853/// ```
854/// use predicator_rs::{Context, Instructions, OnUnbound, Options, Value, evaluate};
855///
856/// let program = Instructions::from_json(r#"[["load","score"],["lit",85],["compare","GT"]]"#)?;
857/// let mut context = Context::new();
858/// context.insert("score", Value::from(90));
859/// assert_eq!(evaluate(&program, &context, &Options::new())?, Value::from(true));
860///
861/// let unbound = evaluate(&program, &Context::new(), &Options::new()).unwrap_err();
862/// assert_eq!(unbound.type_name(), "UndefinedVariableError");
863/// assert_eq!(unbound.reason(), "unbound_variable");
864///
865/// let strict = Options::new().on_unbound(OnUnbound::Error);
866/// assert_eq!(evaluate(&program, &Context::new(), &strict).unwrap_err().reason(), "unbound_variable");
867/// # Ok::<(), predicator_rs::Error>(())
868/// ```
869pub 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
892/// The error a run that stopped on `fault` answers: a refused undefined
893/// operand is reported as the first unbound variable the run loaded, when it
894/// loaded one.
895fn 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
905/// Runs `program` over `context` in statement mode, keeping what the last
906/// `pop` discarded when `keep_value` says so.
907fn 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
944/// Runs `program` over `context` as a statement program and answers the
945/// context it leaves, with the roots it stored into.
946///
947/// The program is an `&`[`Instructions`], or a `&str` source compiled as a
948/// statement program ([`compile_program`](crate::compile_program)); a
949/// source that does not compile stops before anything runs, the [`Stopped`]
950/// holding its [`Error::Parse`] and the context passed in. It runs in
951/// statement mode, as the reference's instruction-set text states it: from its first instruction
952/// to its end, its `store`s writing a copy of `context` (the one passed in
953/// is never changed), and what is left on the stack at the end is
954/// discarded. A run answers an [`Execution`]: the context it left and
955/// [`Execution::stored_roots`], the roots it stored into in the order of
956/// its first store.
957///
958/// A run that stops answers a [`Stopped`]: the [`Error`] it stopped on, the
959/// context as of the last statement it completed (every earlier write kept,
960/// the failing write not made) and the roots it had stored into. A
961/// `Stopped` converts into its `Error`, so `?` takes it where only the
962/// error matters.
963///
964/// The [`Options`] are read as [`evaluate`] reads them, and two more:
965/// [`Options::loop_budget`] bounds the back edges a run takes, as it does
966/// for [`evaluate`], and [`Options::protected_roots`] names the roots a
967/// `store` is refused for (reason `protected_root`). A variable the context
968/// does not bind is read as [`evaluate`] reads it, and a refused undefined
969/// operand is reported as the first unbound variable the run loaded; the
970/// run's answer is the context, so an undefined value is never one.
971///
972/// Before anything runs, every value the context binds is checked against
973/// the value domain ([`Context`]).
974///
975/// ```
976/// use predicator_rs::{Context, Instructions, Key, Options, Value, execute};
977///
978/// // x = 1; y = x + 2
979/// let program = Instructions::from_json(
980///     r#"[["lit","x"],["lit",1],["store",1],["lit","y"],["load","x"],["lit",2],["add"],["store",1]]"#,
981/// )?;
982/// let given = Context::new();
983/// let execution = execute(&program, &given, &Options::new())?;
984/// assert_eq!(execution.context().get(&Key::from("y")), Some(&Value::from(3)));
985/// assert_eq!(execution.stored_roots(), [Key::from("x"), Key::from("y")]);
986/// assert_eq!(given, Context::new());
987/// # Ok::<(), predicator_rs::Error>(())
988/// ```
989pub 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
997/// Runs `program` over `context` as [`execute`] does, and also answers the
998/// value of its last expression statement: what its last `pop` discarded,
999/// or undefined when it popped nothing ([`Execution::value`]).
1000///
1001/// A run that stops answers a [`Stopped`], exactly as [`execute`]'s does,
1002/// with no value.
1003///
1004/// ```
1005/// use predicator_rs::{Context, Instructions, Options, Value, execute_value};
1006///
1007/// // x = 2; x * 10
1008/// let program = Instructions::from_json(
1009///     r#"[["lit","x"],["lit",2],["store",1],["load","x"],["lit",10],["multiply"],["pop"]]"#,
1010/// )?;
1011/// let execution = execute_value(&program, &Context::new(), &Options::new())?;
1012/// assert_eq!(execution.value(), Some(&Value::from(20)));
1013/// # Ok::<(), predicator_rs::Error>(())
1014/// ```
1015pub 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    /// The type and reason of the error `text` fails with; an answer
1036    /// instead is reported in the same shape, so the assertion names it.
1037    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    // Sabotage: with the retired lookup in decode skipped (every unknown
1053    // name answering unknown_instruction), this test fails.
1054    #[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    // Sabotage: with read_load accepting any operand as an empty name, this
1079    // test fails.
1080    #[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    // Sabotage: with run answering Value::Null for an empty stack, this test
1120    // fails.
1121    #[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    // Sabotage: with compare popping the left operand first, this test
1133    // fails.
1134    #[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    // Sabotage: with negate's operation fixed to "logical_not", this test
1155    // fails.
1156    #[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    // Sabotage: with checked_neg replaced by wrapping_neg, this test fails.
1183    #[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    // Sabotage: with condition reading null as true, this test fails.
1212    #[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    // Sabotage: with a taken jump answering at + offset + 1, this test
1244    // fails.
1245    #[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    // Sabotage: with load recording the last unbound root instead of the
1265    // first, this test fails.
1266    #[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    // Sabotage: with load ignoring on_unbound, this test fails.
1321    #[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        // Under the default this program answers true, the unbound load
1327        // skipped by the jump it feeds.
1328        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    /// The type, reason and message of the error `text` fails with under
1349    /// `options`; an answer instead is reported in the same shape, so the
1350    /// assertion names it.
1351    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    // Sabotage: with the call arm splitting off the arguments in stack order
1371    // reversed, this test fails.
1372    #[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    // Sabotage: with the call arm skipping the stack-depth check (popping
1390    // what there is), this test fails.
1391    #[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    // Sabotage: with call looking up the library before the host's
1438    // functions, this test fails.
1439    #[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    // Sabotage: with call skipping the domain check of a host function's
1484    // answer, this test fails.
1485    #[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    // Sabotage: with draw ignoring the options' random source, this test
1512    // fails.
1513    #[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        // The default source draws differently each time, in [0, 1).
1524        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    // Sabotage: with Date.now reading the options' clock at each call
1538    // rather than once per run, this test fails.
1539    #[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    // Sabotage: with call answering an unbound argument's refusal as an
1560    // UndefinedVariableError, this test fails.
1561    #[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    // Sabotage: with evaluate skipping context.check, this test fails.
1570    #[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    // Sabotage: with pop_jump_if_falsy reading its condition without
1584    // popping it, this test fails.
1585    #[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    // Sabotage: with jump_backward's target check made after the budget is
1615    // spent, this test fails.
1616    #[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        // A back edge to the first instruction is in range.
1633        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    // Sabotage: with store reading its segments top first (leaf first),
1647    // this test fails.
1648    #[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        // An undefined segment from an unbound load is reported as the
1676        // unbound variable.
1677        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}