Skip to main content

predicator_rs/
options.rs

1//! The options one evaluation is run with, built per call.
2
3use crate::{DateTime, Value};
4use core::fmt;
5use std::collections::{BTreeMap, BTreeSet};
6
7/// What a `load` of a variable the context does not bind does.
8///
9/// ```
10/// use predicator_rs::OnUnbound;
11///
12/// assert_eq!(OnUnbound::default(), OnUnbound::Undefined);
13/// ```
14///
15/// The enum is `non_exhaustive`: a later version may add a policy.
16#[non_exhaustive]
17#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
18pub enum OnUnbound {
19    /// The load pushes undefined, and the evaluation fails with an
20    /// [`UndefinedVariableError`](crate::UndefinedVariableError) only when
21    /// undefined is its answer, or when an instruction refuses that
22    /// undefined as an operand. The default.
23    #[default]
24    Undefined,
25    /// The load itself fails the evaluation with an
26    /// [`UndefinedVariableError`](crate::UndefinedVariableError).
27    Error,
28}
29
30/// The clock a run reads the current time from. It is `Send` and `Sync`,
31/// so options may be shared between threads whether or not they name one.
32type Clock<'a> = Box<dyn Fn() -> Option<DateTime> + Send + Sync + 'a>;
33
34/// A function the host passes in by name: it takes the call's arguments
35/// and answers a value, or refuses with a message.
36type HostFunction<'a> = Box<dyn Fn(&[Value]) -> Result<Value, String> + Send + Sync + 'a>;
37
38/// The random source `Math.random` draws from: each call answers 64 random
39/// bits.
40type Random<'a> = Box<dyn Fn() -> u64 + Send + Sync + 'a>;
41
42/// The options an evaluation is run with, built per call: nothing is
43/// configured globally.
44///
45/// The clock is the one a program that reads the current time (a
46/// `relative_date` instruction) reads it from: a callable answering the
47/// current instant, or `None` when it has none to give. A run reads it at
48/// most once, the first time the program reads the time, and never when the
49/// program does not; every later read in the same run answers the same
50/// instant. A clock that answers `None` fails the run with an
51/// [`EvaluationError`](crate::EvaluationError), reason `clock_failed`.
52/// Without one, the run reads the system clock, to the microsecond. A clock
53/// is `Send` and `Sync` and may borrow from its caller, so `Options` is
54/// `Send` and `Sync` whether or not it names one.
55///
56/// A host function is passed by name ([`Options::function`]) and is called
57/// by the `call` instruction with the call's arguments and nothing else. It
58/// answers a value, which is checked against the value domain, or refuses
59/// with a message, which fails the run with an
60/// [`EvaluationError`](crate::EvaluationError) whose reason is that
61/// message. A name passed this way shadows the library function of that
62/// name for the runs these options are given to, and no other.
63///
64/// A function passed in (a host function, the clock, the random source) is
65/// called by the run, on the caller's thread, and may borrow from the caller
66/// for the length of the call. A panic inside one is not caught: it unwinds
67/// out of the entry point to the caller, as a panic in the caller's own
68/// code would.
69///
70/// The random source is the one `Math.random` draws from
71/// ([`Options::random`]). Without one, a run draws from a source seeded
72/// from the standard library's per-process hash keys, which is not
73/// cryptographic and must not be used where a guess at the next draw would
74/// matter.
75///
76/// The loop budget ([`Options::loop_budget`]) is how many back edges (the
77/// `jump_backward` instruction) one run may take, 10,000 unless the options
78/// say otherwise; a run that has spent it fails at its next back edge with
79/// an [`EvaluationError`](crate::EvaluationError), reason
80/// `loop_budget_exceeded`. The protected roots
81/// ([`Options::protected_roots`]) are the context roots a statement program
82/// may not store into; [`evaluate`](crate::evaluate) does not read them.
83///
84/// ```
85/// use predicator_rs::{Date, DateTime, OnUnbound, Options};
86///
87/// let strict = Options::new().on_unbound(OnUnbound::Error);
88/// # let _ = strict;
89/// let noon = DateTime::new(Date::new(2030, 1, 15).unwrap(), 12, 0, 0, 0);
90/// let fixed = Options::new().clock(move || noon);
91/// # let _ = fixed;
92/// let hosted = Options::new()
93///     .function("double", |arguments| match arguments {
94///         [predicator_rs::Value::Integer(x)] => Ok(predicator_rs::Value::from(x * 2)),
95///         _ => Err("double expects one integer".to_owned()),
96///     })
97///     .random(|| 0);
98/// # let _ = hosted;
99/// ```
100pub struct Options<'a> {
101    pub(crate) on_unbound: OnUnbound,
102    pub(crate) clock: Option<Clock<'a>>,
103    pub(crate) functions: BTreeMap<String, HostFunction<'a>>,
104    pub(crate) random: Option<Random<'a>>,
105    pub(crate) loop_budget: u64,
106    pub(crate) protected_roots: BTreeSet<String>,
107}
108
109/// How many back edges a run may take when the options do not say.
110pub(crate) const DEFAULT_LOOP_BUDGET: u64 = 10_000;
111
112impl Default for Options<'_> {
113    fn default() -> Self {
114        Options {
115            on_unbound: OnUnbound::default(),
116            clock: None,
117            functions: BTreeMap::new(),
118            random: None,
119            loop_budget: DEFAULT_LOOP_BUDGET,
120            protected_roots: BTreeSet::new(),
121        }
122    }
123}
124
125impl<'a> Options<'a> {
126    /// The default options.
127    ///
128    /// ```
129    /// use predicator_rs::{Context, Options, Value, evaluate};
130    ///
131    /// assert_eq!(evaluate("1 + 1", &Context::new(), &Options::new()), Ok(Value::from(2)));
132    /// ```
133    pub fn new() -> Options<'a> {
134        Options::default()
135    }
136
137    /// The same options with `policy` as what a load of an unbound
138    /// variable does.
139    ///
140    /// ```
141    /// use predicator_rs::{Context, OnUnbound, Options, Value, evaluate};
142    ///
143    /// let lenient = Options::new();
144    /// assert_eq!(evaluate("x is defined", &Context::new(), &lenient), Ok(Value::from(false)));
145    /// let strict = Options::new().on_unbound(OnUnbound::Error);
146    /// let refused = evaluate("x is defined", &Context::new(), &strict).unwrap_err();
147    /// assert_eq!(refused.reason(), "unbound_variable");
148    /// ```
149    #[must_use]
150    pub fn on_unbound(mut self, policy: OnUnbound) -> Options<'a> {
151        self.on_unbound = policy;
152        self
153    }
154
155    /// The same options with `clock` as the clock a run reads the current
156    /// time from, in place of the system clock. A clock that answers `None`
157    /// fails the run with the reason `clock_failed`; a panic inside it is
158    /// not caught.
159    ///
160    /// ```
161    /// use predicator_rs::{Context, DateTime, Options, Value, evaluate};
162    ///
163    /// let epoch = Options::new().clock(|| DateTime::from_unix(0, 0));
164    /// let year = evaluate("Date.year(Date.now())", &Context::new(), &epoch);
165    /// assert_eq!(year, Ok(Value::from(1970)));
166    /// let none = Options::new().clock(|| None);
167    /// let refused = evaluate("Date.now()", &Context::new(), &none).unwrap_err();
168    /// assert_eq!(refused.reason(), "clock_failed");
169    /// ```
170    #[must_use]
171    pub fn clock(mut self, clock: impl Fn() -> Option<DateTime> + Send + Sync + 'a) -> Options<'a> {
172        self.clock = Some(Box::new(clock));
173        self
174    }
175
176    /// The same options with `function` passed in under `name`, replacing a
177    /// function these options already pass under that name. The `call`
178    /// instruction calls it with the call's arguments, deepest first, in
179    /// place of any library function of that name. It answers the call's
180    /// value or refuses with a message; a refusal fails the run with an
181    /// [`EvaluationError`](crate::EvaluationError) whose reason and message
182    /// are that message, and an answer outside the value domain (a float
183    /// that is not finite, lists and maps nested past 100 levels) fails it
184    /// with the reason the domain check gives. No arity is checked: the
185    /// function sees however many arguments the call passes. A panic inside
186    /// the function is not caught; it unwinds out of the entry point.
187    ///
188    /// ```
189    /// use predicator_rs::{Context, Instructions, Options, Value, evaluate};
190    ///
191    /// let options = Options::new().function("len", |arguments| Ok(Value::from(arguments.len() as i64)));
192    /// let program = Instructions::from_json(r#"[["lit","x"],["lit","y"],["call","len",2]]"#)?;
193    /// assert_eq!(evaluate(&program, &Context::new(), &options)?, Value::from(2));
194    /// # Ok::<(), predicator_rs::Error>(())
195    /// ```
196    #[must_use]
197    pub fn function(
198        mut self,
199        name: impl Into<String>,
200        function: impl Fn(&[Value]) -> Result<Value, String> + Send + Sync + 'a,
201    ) -> Options<'a> {
202        self.functions.insert(name.into(), Box::new(function));
203        self
204    }
205
206    /// The same options with `random` as the source `Math.random` draws
207    /// from, in place of the default. Each draw calls it once and turns the
208    /// 64 bits it answers into a float in `[0, 1)`: the top 53 bits, over
209    /// 2^53. A source that must change state between draws keeps that state
210    /// behind a shared reference (an atomic, a mutex). A panic inside it is
211    /// not caught.
212    ///
213    /// ```
214    /// use predicator_rs::{Context, Instructions, Options, Value, evaluate};
215    ///
216    /// let program = Instructions::from_json(r#"[["call","Math.random",0]]"#)?;
217    /// let half = Options::new().random(|| 1 << 63);
218    /// assert_eq!(evaluate(&program, &Context::new(), &half)?, Value::from(0.5));
219    /// # Ok::<(), predicator_rs::Error>(())
220    /// ```
221    #[must_use]
222    pub fn random(mut self, random: impl Fn() -> u64 + Send + Sync + 'a) -> Options<'a> {
223        self.random = Some(Box::new(random));
224        self
225    }
226
227    /// The same options with `budget` as how many back edges (the
228    /// `jump_backward` instruction) one run may take, in place of the
229    /// default 10,000. Every back edge a run takes spends one; a run that
230    /// reaches a back edge with none left fails there with an
231    /// [`EvaluationError`](crate::EvaluationError), reason
232    /// `loop_budget_exceeded`. A budget of 0 lets a run take no back edge.
233    /// A program with no back edge never spends any.
234    ///
235    /// ```
236    /// use predicator_rs::{Context, Instructions, Options, evaluate};
237    ///
238    /// let forever = Instructions::from_json(r#"[["lit",true],["pop_jump_if_falsy",2],["jump_backward",2]]"#)?;
239    /// let spent = evaluate(&forever, &Context::new(), &Options::new().loop_budget(3)).unwrap_err();
240    /// assert_eq!(spent.reason(), "loop_budget_exceeded");
241    /// # Ok::<(), predicator_rs::Error>(())
242    /// ```
243    #[must_use]
244    pub fn loop_budget(mut self, budget: u64) -> Options<'a> {
245        self.loop_budget = budget;
246        self
247    }
248
249    /// The same options with each of `roots` protected: a `store` whose
250    /// path's root is one of them is refused when it is reached, with an
251    /// [`EvaluationError`](crate::EvaluationError), reason `protected_root`,
252    /// that names the root ([`EvaluationError::root`](crate::EvaluationError::root)).
253    /// A root is protected whole: there is no protecting `a.b` while
254    /// leaving `a.c` writable. The check comes after the path's segments
255    /// are checked, so a malformed path still fails on its segment first.
256    /// The roots add to any these options already protect.
257    /// [`execute`](crate::execute) and
258    /// [`execute_value`](crate::execute_value) read them;
259    /// [`evaluate`](crate::evaluate) does not.
260    ///
261    /// ```
262    /// use predicator_rs::{Context, Error, Instructions, Options, execute};
263    ///
264    /// let program = Instructions::from_json(r#"[["lit","x"],["lit",1],["store",1],["lit","locked"],["lit",2],["store",1]]"#)?;
265    /// let stopped = execute(&program, &Context::new(), &Options::new().protected_roots(["locked"])).unwrap_err();
266    /// let Error::Evaluation(refusal) = stopped.error() else { unreachable!() };
267    /// assert_eq!((refusal.reason(), refusal.root()), ("protected_root", Some("locked")));
268    /// # Ok::<(), predicator_rs::Error>(())
269    /// ```
270    #[must_use]
271    pub fn protected_roots<I>(mut self, roots: I) -> Options<'a>
272    where
273        I: IntoIterator,
274        I::Item: Into<String>,
275    {
276        self.protected_roots
277            .extend(roots.into_iter().map(Into::into));
278        self
279    }
280
281    /// Whether these options protect the root `name`.
282    pub(crate) fn protects(&self, name: &str) -> bool {
283        self.protected_roots.contains(name)
284    }
285
286    /// The host function these options pass under `name`, if any.
287    pub(crate) fn host_function(&self, name: &str) -> Option<&HostFunction<'a>> {
288        self.functions.get(name)
289    }
290
291    /// The random source these options name, if any.
292    pub(crate) fn random_source(&self) -> Option<&Random<'a>> {
293        self.random.as_ref()
294    }
295
296    /// The current time from the clock these options name, or the system
297    /// clock when they name none.
298    pub(crate) fn now(&self) -> Option<DateTime> {
299        match &self.clock {
300            Some(clock) => clock(),
301            None => system_now(),
302        }
303    }
304}
305
306impl fmt::Debug for Options<'_> {
307    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
308        let clock = if self.clock.is_some() {
309            "given"
310        } else {
311            "system"
312        };
313        let random = if self.random.is_some() {
314            "given"
315        } else {
316            "default"
317        };
318        let functions: Vec<&str> = self.functions.keys().map(String::as_str).collect();
319        f.debug_struct("Options")
320            .field("on_unbound", &self.on_unbound)
321            .field("clock", &clock)
322            .field("functions", &functions)
323            .field("random", &random)
324            .field("loop_budget", &self.loop_budget)
325            .field("protected_roots", &self.protected_roots)
326            .finish()
327    }
328}
329
330/// The system clock's current time, to the microsecond, or `None` when it
331/// names an instant this crate cannot hold.
332fn system_now() -> Option<DateTime> {
333    use std::time::{SystemTime, UNIX_EPOCH};
334    let (sign, since) = match SystemTime::now().duration_since(UNIX_EPOCH) {
335        Ok(since) => (1, since),
336        Err(before) => (-1, before.duration()),
337    };
338    let micros = i128::from(sign) * i128::try_from(since.as_micros()).ok()?;
339    let seconds = i64::try_from(micros.div_euclid(1_000_000)).ok()?;
340    let microsecond = u32::try_from(micros.rem_euclid(1_000_000)).ok()?;
341    DateTime::from_unix(seconds, microsecond)
342}
343
344#[cfg(test)]
345mod tests {
346    use super::*;
347
348    fn thread_safe<T: Send + Sync>(_: &T) {}
349
350    // Sabotage: with the Send + Sync bound removed from Clock and from
351    // Options::clock (or from HostFunction and Options::function, or from
352    // Random and Options::random), or with an Rc field added to Execution
353    // or Stopped, this test fails to compile.
354    #[test]
355    fn options_and_a_context_may_be_shared_between_threads() {
356        let reads = std::sync::atomic::AtomicU32::new(0);
357        let draws = std::sync::atomic::AtomicU64::new(0);
358        thread_safe(&Options::new());
359        thread_safe(&Options::new().clock(|| {
360            reads.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
361            None
362        }));
363        thread_safe(
364            &Options::new()
365                .function("f", |_| {
366                    reads.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
367                    Ok(Value::Null)
368                })
369                .random(|| draws.fetch_add(1, std::sync::atomic::Ordering::SeqCst))
370                .loop_budget(1)
371                .protected_roots(["p"]),
372        );
373        thread_safe(&crate::Context::new());
374        let program = crate::Instructions::from_json("[[\"lit\",1],[\"pop\"]]").unwrap();
375        thread_safe(&crate::execute(&program, &crate::Context::new(), &Options::new()).unwrap());
376        thread_safe(&crate::execute("(", &crate::Context::new(), &Options::new()).unwrap_err());
377    }
378
379    // Sabotage: with now always reading the system clock, this test fails.
380    #[test]
381    fn a_given_clock_replaces_the_system_clock() {
382        let epoch = DateTime::from_unix(0, 0);
383        assert_eq!(Options::new().clock(move || epoch).now(), epoch);
384        assert_eq!(Options::new().clock(|| None).now(), None);
385        let system = Options::new().now().unwrap();
386        // The system clock reads a time after this test was written.
387        assert!(system.unix_seconds() > 1_790_000_000);
388        assert_eq!(
389            format!("{:?}", Options::new()),
390            "Options { on_unbound: Undefined, clock: \"system\", functions: [], random: \"default\", loop_budget: 10000, protected_roots: {} }"
391        );
392        assert_eq!(
393            format!(
394                "{:?}",
395                Options::new()
396                    .clock(|| None)
397                    .function("b", |_| Ok(Value::Null))
398                    .function("a", |_| Ok(Value::Null))
399                    .random(|| 0)
400                    .loop_budget(5)
401                    .protected_roots(["q", "p"])
402            ),
403            "Options { on_unbound: Undefined, clock: \"given\", functions: [\"a\", \"b\"], random: \"given\", loop_budget: 5, protected_roots: {\"p\", \"q\"} }"
404        );
405    }
406
407    // Sabotage: with Options::function keeping the first function passed
408    // under a name rather than the last, this test fails.
409    #[test]
410    fn a_function_passed_twice_under_one_name_is_the_last() {
411        let options = Options::new()
412            .function("f", |_| Ok(Value::from(1)))
413            .function("f", |_| Ok(Value::from(2)));
414        let answer = options.host_function("f").map(|function| function(&[]));
415        assert_eq!(answer, Some(Ok(Value::from(2))));
416        assert!(options.host_function("g").is_none());
417        assert_eq!(
418            Options::new()
419                .random(|| 7)
420                .random_source()
421                .map(|random| random()),
422            Some(7)
423        );
424        assert!(Options::new().random_source().is_none());
425    }
426
427    // Sabotage: with Default setting loop_budget to 0, this test fails.
428    #[test]
429    fn the_loop_budget_defaults_to_ten_thousand_and_protected_roots_add_up() {
430        assert_eq!(Options::new().loop_budget, 10_000);
431        assert_eq!(Options::new().loop_budget(0).loop_budget, 0);
432        let options = Options::new()
433            .protected_roots(["a"])
434            .protected_roots(vec![String::from("b")]);
435        assert!(options.protects("a") && options.protects("b"));
436        assert!(!options.protects("c"));
437        assert!(!Options::new().protects("a"));
438    }
439}