Skip to main content

Options

Struct Options 

Source
pub struct Options<'a> { /* private fields */ }
Expand description

The options an evaluation is run with, built per call: nothing is configured globally.

The clock is the one a program that reads the current time (a relative_date instruction) reads it from: a callable answering the current instant, or None when it has none to give. A run reads it at most once, the first time the program reads the time, and never when the program does not; every later read in the same run answers the same instant. A clock that answers None fails the run with an EvaluationError, reason clock_failed. Without one, the run reads the system clock, to the microsecond. A clock is Send and Sync and may borrow from its caller, so Options is Send and Sync whether or not it names one.

A host function is passed by name (Options::function) and is called by the call instruction with the call’s arguments and nothing else. It answers a value, which is checked against the value domain, or refuses with a message, which fails the run with an EvaluationError whose reason is that message. A name passed this way shadows the library function of that name for the runs these options are given to, and no other.

A function passed in (a host function, the clock, the random source) is called by the run, on the caller’s thread, and may borrow from the caller for the length of the call. A panic inside one is not caught: it unwinds out of the entry point to the caller, as a panic in the caller’s own code would.

The random source is the one Math.random draws from (Options::random). Without one, a run draws from a source seeded from the standard library’s per-process hash keys, which is not cryptographic and must not be used where a guess at the next draw would matter.

The loop budget (Options::loop_budget) is how many back edges (the jump_backward instruction) one run may take, 10,000 unless the options say otherwise; a run that has spent it fails at its next back edge with an EvaluationError, reason loop_budget_exceeded. The protected roots (Options::protected_roots) are the context roots a statement program may not store into; evaluate does not read them.

use predicator_rs::{Date, DateTime, OnUnbound, Options};

let strict = Options::new().on_unbound(OnUnbound::Error);
let noon = DateTime::new(Date::new(2030, 1, 15).unwrap(), 12, 0, 0, 0);
let fixed = Options::new().clock(move || noon);
let hosted = Options::new()
    .function("double", |arguments| match arguments {
        [predicator_rs::Value::Integer(x)] => Ok(predicator_rs::Value::from(x * 2)),
        _ => Err("double expects one integer".to_owned()),
    })
    .random(|| 0);

Implementations§

Source§

impl<'a> Options<'a>

Source

pub fn new() -> Options<'a>

The default options.

use predicator_rs::{Context, Options, Value, evaluate};

assert_eq!(evaluate("1 + 1", &Context::new(), &Options::new()), Ok(Value::from(2)));
Source

pub fn on_unbound(self, policy: OnUnbound) -> Options<'a>

The same options with policy as what a load of an unbound variable does.

use predicator_rs::{Context, OnUnbound, Options, Value, evaluate};

let lenient = Options::new();
assert_eq!(evaluate("x is defined", &Context::new(), &lenient), Ok(Value::from(false)));
let strict = Options::new().on_unbound(OnUnbound::Error);
let refused = evaluate("x is defined", &Context::new(), &strict).unwrap_err();
assert_eq!(refused.reason(), "unbound_variable");
Source

pub fn clock( self, clock: impl Fn() -> Option<DateTime> + Send + Sync + 'a, ) -> Options<'a>

The same options with clock as the clock a run reads the current time from, in place of the system clock. A clock that answers None fails the run with the reason clock_failed; a panic inside it is not caught.

use predicator_rs::{Context, DateTime, Options, Value, evaluate};

let epoch = Options::new().clock(|| DateTime::from_unix(0, 0));
let year = evaluate("Date.year(Date.now())", &Context::new(), &epoch);
assert_eq!(year, Ok(Value::from(1970)));
let none = Options::new().clock(|| None);
let refused = evaluate("Date.now()", &Context::new(), &none).unwrap_err();
assert_eq!(refused.reason(), "clock_failed");
Source

pub fn function( self, name: impl Into<String>, function: impl Fn(&[Value]) -> Result<Value, String> + Send + Sync + 'a, ) -> Options<'a>

The same options with function passed in under name, replacing a function these options already pass under that name. The call instruction calls it with the call’s arguments, deepest first, in place of any library function of that name. It answers the call’s value or refuses with a message; a refusal fails the run with an EvaluationError whose reason and message are that message, and an answer outside the value domain (a float that is not finite, lists and maps nested past 100 levels) fails it with the reason the domain check gives. No arity is checked: the function sees however many arguments the call passes. A panic inside the function is not caught; it unwinds out of the entry point.

use predicator_rs::{Context, Instructions, Options, Value, evaluate};

let options = Options::new().function("len", |arguments| Ok(Value::from(arguments.len() as i64)));
let program = Instructions::from_json(r#"[["lit","x"],["lit","y"],["call","len",2]]"#)?;
assert_eq!(evaluate(&program, &Context::new(), &options)?, Value::from(2));
Source

pub fn random(self, random: impl Fn() -> u64 + Send + Sync + 'a) -> Options<'a>

The same options with random as the source Math.random draws from, in place of the default. Each draw calls it once and turns the 64 bits it answers into a float in [0, 1): the top 53 bits, over 2^53. A source that must change state between draws keeps that state behind a shared reference (an atomic, a mutex). A panic inside it is not caught.

use predicator_rs::{Context, Instructions, Options, Value, evaluate};

let program = Instructions::from_json(r#"[["call","Math.random",0]]"#)?;
let half = Options::new().random(|| 1 << 63);
assert_eq!(evaluate(&program, &Context::new(), &half)?, Value::from(0.5));
Source

pub fn loop_budget(self, budget: u64) -> Options<'a>

The same options with budget as how many back edges (the jump_backward instruction) one run may take, in place of the default 10,000. Every back edge a run takes spends one; a run that reaches a back edge with none left fails there with an EvaluationError, reason loop_budget_exceeded. A budget of 0 lets a run take no back edge. A program with no back edge never spends any.

use predicator_rs::{Context, Instructions, Options, evaluate};

let forever = Instructions::from_json(r#"[["lit",true],["pop_jump_if_falsy",2],["jump_backward",2]]"#)?;
let spent = evaluate(&forever, &Context::new(), &Options::new().loop_budget(3)).unwrap_err();
assert_eq!(spent.reason(), "loop_budget_exceeded");
Source

pub fn protected_roots<I>(self, roots: I) -> Options<'a>
where I: IntoIterator, I::Item: Into<String>,

The same options with each of roots protected: a store whose path’s root is one of them is refused when it is reached, with an EvaluationError, reason protected_root, that names the root (EvaluationError::root). A root is protected whole: there is no protecting a.b while leaving a.c writable. The check comes after the path’s segments are checked, so a malformed path still fails on its segment first. The roots add to any these options already protect. execute and execute_value read them; evaluate does not.

use predicator_rs::{Context, Error, Instructions, Options, execute};

let program = Instructions::from_json(r#"[["lit","x"],["lit",1],["store",1],["lit","locked"],["lit",2],["store",1]]"#)?;
let stopped = execute(&program, &Context::new(), &Options::new().protected_roots(["locked"])).unwrap_err();
let Error::Evaluation(refusal) = stopped.error() else { unreachable!() };
assert_eq!((refusal.reason(), refusal.root()), ("protected_root", Some("locked")));

Trait Implementations§

Source§

impl Debug for Options<'_>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Options<'_>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<'a> !RefUnwindSafe for Options<'a>

§

impl<'a> !UnwindSafe for Options<'a>

§

impl<'a> Forget for Options<'a>

§

impl<'a> Freeze for Options<'a>

§

impl<'a> Move for Options<'a>

§

impl<'a> Send for Options<'a>

§

impl<'a> Sync for Options<'a>

§

impl<'a> Unpin for Options<'a>

§

impl<'a> UnsafeUnpin for Options<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.