Skip to main content

Evaluator

Struct Evaluator 

Source
pub struct Evaluator { /* private fields */ }
Expand description

An evaluator for one specification and model.

Implementations§

Source§

impl Evaluator

Source

pub fn validate_scope(&self, scope: &Scope) -> Result<()>

Verifies that a scope was created by this evaluator.

§Errors

A scope created by another evaluator, even one over an equal IR.

Source§

impl Evaluator

Source

pub fn admits_scoped_expr(&self, scope: &Scope, expr: ExprId) -> bool

Whether expr may be evaluated in scope: the scope was created by this evaluator and, when the expression needs a lexical frame, the scope is that frame’s.

if !ev.admits_scoped_expr(scope, e) {
    // a foreign or mismatched scope
}
Source§

impl Evaluator

Source

pub fn validate_model_context( &self, ir: &Arc<Ir>, names: &Arc<Interner>, ) -> Result<(), ContextError>

Checks that public model metadata still describes this evaluator’s IR and name table. Cloning the same Arcs is valid; substituting another arena is not a certified binding, even when its numeric IDs happen to match.

§Errors

A foreign IR or name table.

Source

pub fn validate_predicate(&self, scope: &Scope, expr: ExprId) -> Result<()>

Admits a predicate’s ID and lexical frame before interpreting it. Closed expressions can be reused in any scope from the same IR.

§Errors

A foreign scope, missing expression or incompatible lexical frame.

Source§

impl Evaluator

Source

pub fn scope_selectseq_call( &self, scope: &Scope, operator: &OpRef, args: &[Arg], work: &mut usize, ) -> Result<Option<(ExprId, Vec<(ExprId, Scope)>)>>

Inspects an authoritative SelectSeq call without evaluating its sequence or predicate. Returns the original sequence and callback/capture bodies in their lexical scopes. Pure supported unary user callbacks qualify. Callers independently check purity and scoped levels on every body.

§Errors

Invalid ownership, unsupported callback contexts or exhausted work.

Source§

impl Evaluator

Source

pub fn named_state( &self, assignments: impl IntoIterator<Item = (DeclId, Value)>, ) -> Result<Arc<NamedState>>

Constructs a query-local partial assignment from real variable declarations.

Duplicate declarations of the same canonical name must agree. This checks stored value names without interning, enumeration or callbacks. Opaque deferred values cannot be supplied through this checked public constructor. The resulting state is not an ordinary Next transition or a graph state.

use std::sync::Arc;
use dive_eval::{Evaluator, Model, Options, St, StateRef};
use dive_value::Value;
let analysis = dive_sema::analyze_source("M.tla",
    "---- MODULE M ----\nVARIABLE x\nRead == x\n====\n", &Default::default());
let ir = Arc::new(dive_ir::lower(&analysis).expect("IR"));
let read = ir.root_def("Read").expect("Read");
let x = ir.vars()[0];
let evaluator = Evaluator::new(Model::new(ir), Options::tlc()).expect("evaluator");
let assignment = evaluator.named_state([(x, Value::TRUE)]).expect("assignment");
let mut state = St::empty();
state.s0 = StateRef::Named(assignment);
assert_eq!(evaluator.eval_def(read, &state).expect("read"), Value::TRUE);
§Errors

An unknown/nonvariable declaration, inconsistent duplicate assignment or stored value whose name-table ownership cannot be checked.

Source§

impl Evaluator

Source

pub fn init_predicate(&self, def: DefId, id: usize) -> Result<Action>

An initial predicate named by INIT (or a level-1 conjunct of a SPECIFICATION that is a use of def): def’s body in its own frame (SpecProcessor.processConfigInitAndNext).

§Errors

A bug if def has parameters.

Source

pub fn predicate( &self, frame: DefId, expr: ExprId, name: ActionName, id: usize, ) -> Result<Action>

An initial predicate or action that is the expression expr of the top-level definition frame, evaluated in a fresh frame of it (for example the Init conjunct of a SPECIFICATION, named Unnamed).

§Errors

An unknown ID, a foreign context or an incompatible lexical frame.

Source

pub fn predicate_in( &self, scope: &Scope, expr: ExprId, name: ActionName, id: usize, ) -> Result<Action>

An initial predicate or action expr evaluated in scope.

§Errors

An unknown ID, a foreign context or an incompatible lexical frame.

Source

pub fn actions( &self, split: &Split, frame: DefId, first_id: usize, ) -> Result<Vec<Action>>

Splits a next-state relation into TLC’s action list (Tool.getActions, Tool.java:250-419), expanding the tree dive_ir::actions::split built: each split \E is enumerated in the empty state and each inlined operator’s constant arguments are evaluated. frame is the top-level definition the relation is evaluated in; the actions are numbered from first_id.

§Errors

A refusal or bug while expanding, or TLC’s failure to split (an operator TLC cannot cast at the top of the relation), which is refused.

Source

pub fn actions_in( &self, scope: &Scope, split: &Split, first_id: usize, ) -> Result<Vec<Action>>

Evaluator::actions for a relation found in scope (inside a parameterized definition’s body, for example). A relation under a substitution is not split by TLC: build its one action with Evaluator::predicate_in instead.

§Errors

As Evaluator::actions.

Source

pub fn eval_action(&self, action: &Action, st: &St) -> Result<Value>

Evaluates an action’s predicate as an expression (TLC’s Tool.eval(pred, con, s0, s1, EvalControl.Clear)), for a checker’s invariants, constraints and implied actions found by a binding stage.

§Errors

Any evaluation error, refusal or resource limit.

Source

pub fn action_shares_side_effects(&self, action: &Action) -> bool

Evaluator::scope_shares_side_effects for an initial predicate or action.

Source

pub fn init_states( &self, inits: &[Action], sink: &mut dyn FnMut(&Successor<'_>) -> Flow, ) -> Result<Outcome, NextError>

Generates the initial states (Tool.getInitStates): every initial predicate in order, the first one enumerated and the others consed as its continuation. Each state, duplicates included, goes to sink (TLC’s DoInitFunctor.addElement counts every one).

§Errors

The evaluation error, refusal or resource limit that ended the enumeration, with the number of states emitted before it.

Source

pub fn init_states_diagnostic( &self, inits: &[Action], sink: &mut dyn FnMut(&Successor<'_>) -> Flow, ) -> Result<Outcome, NextError>

Runs the same initial generator with the diagnostic tool’s source hook. Cached/stored values are not relabelled; only actual fresh constructors acquire diagnostic sources. The current host owner remains installed.

§Errors

The actual generation error, refusal or owned interruption.

Source

pub fn next_states( &self, action: &Action, s0: &StateVals, ordinal: u64, sink: &mut dyn FnMut(&Successor<'_>) -> Flow, ) -> Result<Outcome, NextError>

Generates the successors of s0 under one action (Tool.getNextStates(functor, state, action)), in TLC’s order, duplicates included. ordinal is the number of successors of s0 already generated by earlier actions.

§Errors

The evaluation error, refusal or resource limit that ended the enumeration, with the number of successors emitted before it.

Source

pub fn next_states_generation( &self, action: &Action, s0: &StateVals, ordinal: u64, choose: &mut dyn FnMut(u64) -> u64, sink: &mut dyn FnMut(&Successor<'_>) -> Flow, ) -> Result<Outcome, NextError>

Traverses Next’s disjunctions and bounded existentials in a seeded constructive order. The sink stops after its first admitted complete state; returning Flow::Continue searches the remaining alternatives. Init and predicate evaluation, including ENABLED, retain their ordinary semantics. choose(n) must return an index below the positive n.

§Errors

The ordinary generation errors, an unsupported indexed domain, or an out-of-range index returned by the caller.

Source

pub fn next_states_diagnostic( &self, action: &Action, s0: &StateVals, ordinal: u64, sink: &mut dyn FnMut(&Successor<'_>) -> Flow, ) -> Result<Outcome, NextError>

Generates Next with the diagnostic tool’s source hook. Only receivers actually constructed during this execution acquire diagnostic sources; cached or stored values retain their original lifetime and provenance. The current host owner remains installed.

let result = ev.next_states_diagnostic(action, source, 0, &mut |_| {
    dive_eval::next::Flow::Continue
});
// Inspect the actual error's typed receiver source, never its text.
§Errors

The actual generation error, refusal or owned interruption.

Source

pub fn successors( &self, actions: &[Action], s0: &StateVals, sink: &mut dyn FnMut(&Successor<'_>) -> Flow, ) -> Result<Outcome, NextError>

Generates the successors of s0 under every action in order (Tool.getNextStates(functor, state)).

§Errors

As Evaluator::next_states; emitted counts all actions’ states.

Source§

impl Evaluator

Source

pub fn enabled_scoped( &self, scope: &Scope, action: ExprId, sub: Option<ExprId>, state: StateVals, ) -> Result<bool>

Decides whether a scoped action has a successor, using TLC’s existing ENABLED search. A subscript requests a non-stuttering successor, equivalent to ENABLED <<action>>_sub. The checker, the liveness checker and the trace validator all decide ENABLED here.

use std::sync::Arc;
use dive_eval::{Evaluator, Model, Options};
use dive_value::Value;
let src = "---- MODULE M ----\nVARIABLE x\nNext == x' = ~x\n====\n";
let analysis = dive_sema::analyze_source("M.tla", src, &dive_sema::Options::default());
let ir = Arc::new(dive_ir::lower(&analysis).expect("IR"));
let d = ir.root_def("Next").expect("Next");
let ev = Evaluator::new(Model::new(ir.clone()), Options::tlc()).expect("valid context");
assert!(ev.enabled_scoped(&ev.scope(d).expect("valid scope"), ir.def(d).body, None,
    Arc::from([Some(Value::Bool(false))])).expect("enabled"));
§Errors

Malformed current state or the existing TLC ENABLED evaluation errors.

Source§

impl Evaluator

Source

pub fn random_element_member( &self, scope: &Scope, expr: ExprId, st: &St, candidate: &Value, limit: usize, ) -> Result<Option<bool>>

Tests the support of one direct native RandomElement(S) application.

This evaluates the actual argument in scope and st, then checks candidate against an interval or a stored finite scalar set. It never invokes a random host or returns a candidate to ordinary evaluation. None means the expression is outside this relation operation (including aliases, configured native redirects and surrounding expressions). Callers must separately enforce single-occurrence, startup and complete predicate contracts. This operation is not a purity certificate.

The state must be constant context, or Init context with the correct number of entirely unassigned slots and no successor. Candidates are scalar: strings/model values must have tokens resolving to the same exact text in this evaluator. Compound candidates refuse before domain evaluation.

limit bounds stored-set entries before normalization, capped at 65,536; intervals use exact bounds without enumeration. Stored entries obey the same flat scalar/token check. Compound/deferred sets remain unsupported. Normal argument evaluation can execute effects under the installed host; this operation itself supplies no host authority or purity certificate.

use std::sync::Arc;
use dive_eval::{Evaluator, Model, Options, St};
let source = "---- MODULE M ----\nEXTENDS TLC\nChoice == RandomElement({7})\n====\n";
let analysis = dive_sema::analyze_source("M.tla", source, &Default::default());
let ir = Arc::new(dive_ir::lower(&analysis).unwrap());
let choice = ir.root_def("Choice").unwrap();
let expr = ir.def(choice).body;
let ev = Evaluator::new(Model::new(ir), Options::tlc()).unwrap();
let scope = ev.scope(choice).unwrap();
assert_eq!(ev.random_element_member(&scope, expr, &St::constant(), &7.into(), 10).unwrap(), Some(true));
assert_eq!(ev.random_element_member(&scope, expr, &St::constant(), &8.into(), 10).unwrap(), Some(false));
§Errors

Foreign context/value, argument evaluation errors, native empty/non-set domain errors, unsupported domains, comparison errors or entry limits.

Source§

impl Evaluator

Source

pub fn recursive_leaf(&self, def: DefId) -> bool

Whether a call of def, a top-level RECURSIVE operator, is a pure state-level evaluation leaf: its body and every definition it reaches are at most state level, with no operator argument, ENABLED, dynamic substitution or effect. Value-bound constants are supported; configured operator bindings and overrides retain their refusal. false for anything else, including a non-recursive or overridden definition.

use std::sync::Arc;
use dive_eval::{Evaluator, Model, Options};
let source = "---- MODULE M ----\nEXTENDS Naturals, Sequences\nVARIABLE v\n\
    RECURSIVE Sum(_)\nSum(q) == IF q = <<>> THEN 0 ELSE Head(q) + Sum(Tail(q))\n\
    RECURSIVE Any(_)\nAny(q) == IF q = <<>> THEN FALSE ELSE \\E x \\in {Head(q)} : x > 0 \\/ Any(Tail(q))\n\
    RECURSIVE Next(_)\nNext(q) == IF q = <<>> THEN v' = v ELSE Next(Tail(q))\n====\n";
let analysis = dive_sema::analyze_source("M.tla", source, &dive_sema::Options::default());
let ir = dive_ir::lower(&analysis).expect("IR");
let (sum, any, next) = (
    ir.root_def("Sum").expect("Sum"),
    ir.root_def("Any").expect("Any"),
    ir.root_def("Next").expect("Next"),
);
let evaluator = Evaluator::new(Model::new(Arc::new(ir)), Options::tlc()).expect("context");
assert!(evaluator.recursive_leaf(sum));
assert!(evaluator.recursive_leaf(any));
assert!(!evaluator.recursive_leaf(next));
Source§

impl Evaluator

Source

pub fn scope_operator_analysis( &self, scope: &Scope, operator: &OpRef, ) -> Result<Option<(DefId, Scope)>>

Resolves a known user operator for non-evaluating context analysis.

Preserves its lexical parent and dynamic substitution context. Each ordinary value formal is bound to SlotView::AnalysisBound, which is state-level for analysis and cannot be forced as a runtime value. This does not prove purity: callers must inspect the returned body and scope. Native, built-in, configured constant, unresolved, recursive, overridden and higher-order targets return None without evaluation or callbacks. A definition used by any configured operator constant is also refused, even when explicitly passed, because captured bindings erase its origin. Callers must also prove Self::scope_operator_captures, including unused lexical/dynamic operator arguments, under their own work budget. Use Self::scope_apply_param with real arguments for execution.

§Errors

An invalid definition, enclosing frame or foreign captured context.

Source

pub fn scope_native_operator_analysis( &self, scope: &Scope, operator: &OpRef, work: &mut usize, ) -> Result<Option<StdOp>>

Resolves an authoritative, bounded pure native operator actual.

Only Sequences!Len, Sequences!Head, Sequences!Append and FiniteSets!Cardinality are admitted. This is callback-free metadata inspection, not a purity or truth certificate. Callers must prove the captured context, arity and actual expression arguments independently. Configured targets and replacements conservatively refuse, including a directly supplied same native target; opaque, builtin and other native targets refuse. Each target/configuration inspection charges work before access.

§Errors

Invalid ownership/reference or exhausted inspection work.

Source

pub fn scope_operator_captures( &self, scope: &Scope, work: &mut usize, ) -> Result<Option<Vec<(ExprId, Scope)>>>

Projects every captured lazy expression and known user operator body.

This performs no evaluation, normalization or callback. Returned bodies retain lexical/dynamic ownership and analysis-only ordinary formals; callers must independently prove each one, including unused captures. Opaque functions/operators and configured/recursive/native targets return None. Each context, substitution link and slot consumes work before inspection or enqueue; retained context depth is capped at 128. Stored values are not forced and this is not a value-purity certificate. Dynamic @ bindings conservatively refuse instead of hashing values.

§Errors

Invalid ownership/reference or the supplied work/context depth bound.

Source

pub fn scope_apply( &self, scope: &Scope, def: DefId, args: &[Arg], ) -> Result<Scope>

Enters an application of def to args in scope, as TLC’s getOpContext does: each expression argument is bound lazily (a LazyValue over scope), each operator argument to the operator.

§Errors

An arity mismatch or a missing enclosing frame (bugs), or an operator argument TLC cannot look up.

Source

pub fn scope_apply_param( &self, scope: &Scope, r: LocalRef, args: &[Arg], ) -> Option<Result<(DefId, Scope)>>

Enters an application of an operator parameter: the definition TLC’s lookup of the parameter gives (the operator passed for it), entered as Evaluator::scope_apply enters a definition. None if the parameter is not bound to a user definition.

§Errors

As Evaluator::scope_apply.

Source

pub fn scope_unbound(&self, scope: &Scope, def: DefId) -> Result<Scope>

The scope of def’s body with none of its parameters bound, as TLC’s getLevelBound sees the body of an operator it looks into: a parameter it meets is not in the context. A LET operator or LAMBDA keeps scope’s frame as its parent; a zero-arity LET definition is evaluated in scope itself.

§Errors

A foreign scope, missing definition or missing enclosing frame.

Source

pub fn scope_call_values( &self, scope: &Scope, def: DefId, values: Vec<Value>, ) -> Result<Scope>

Enters an application of def whose parameters are bound to values, as Tool.getActionsAppl does when it inlines an operator (con1.cons(formals[i], aval)).

§Errors

An arity mismatch or a missing enclosing frame (bugs).

Source

pub fn scope_enter(&self, scope: &Scope, def: DefId) -> Result<Scope>

The scope of a zero-arity LET definition’s body (DefScope::LetValue evaluates in its parent’s frame) or of a definition with no parameters entered from scope.

§Errors

As Evaluator::scope_apply.

Source

pub fn scope(&self, def: DefId) -> Result<Scope>

A fresh frame of the top-level definition def: the context in which SpecProcessor finds a configured formula’s parts.

§Errors

A missing definition or a definition requiring an enclosing lexical frame.

Source

pub fn scope_subst(&self, scope: &Scope, subst: ExprId) -> Result<Scope>

scope under the substitutions of subst, an Expr::Subst node of its frame, as TLC wraps a formula found under an INSTANCE in a substitution (Specs.addSubsts) that the generator then evaluates as uncached lazy values (Tool.java:960-990, :488-498). Labels of actions in the result name the substitution’s location, as TLC’s wrapper does.

§Errors

A bug if subst is not a substitution; an evaluation error of a binding TLC evaluates eagerly (none: every expression binding is lazy).

Source

pub fn scope_call(&self, scope: &Scope, apply: ExprId) -> Result<(Scope, DefId)>

The context of a call apply (an application of a user definition) made in scope: a fresh frame of the definition with its arguments bound as uncached lazy values (getOpContext(..., false), as SpecProcessor.processConfigSpec inlines a parameterized formula). Returns the definition called.

§Errors

A bug if apply is not such an application.

Source

pub fn scope_let(&self, scope: &Scope, let_expr: ExprId) -> Result<Scope>

Binds the zero-arity definitions of a LET (an Expr::Let) in scope, so that its body can be evaluated there. TLC does not bind them when it walks a specification (processConfigSpec, getActions): it finds each definition by its node and evaluates its body at every use. The thunks are therefore not cached, which is indistinguishable from TLC.

§Errors

If let_expr is not a LET.

Source

pub fn scope_eval_let(&self, scope: &Scope, let_expr: ExprId) -> Result<Scope>

Enters a LET reached during actual expression/query evaluation. Each zero-arity value retains its lexical creation context and TLC cachability; no body is evaluated. Structural planning uses Self::scope_let.

§Errors

A foreign scope or an expression that is not an admitted LET.

Source

pub fn scope_without_substs(&self, scope: &Scope) -> Result<Scope>

The scope without its instance substitutions: what TLC’s context holds while processConfigProps walks under a substitution (TLC keeps the substitutions apart, to wrap them around what it finds).

§Errors

A foreign scope or inadmissible captured value.

Source

pub fn scope_bind(&self, scope: &Scope, slot: Slot, v: Value) -> Result<Scope>

Binds a slot of the scope’s own frame to a value: a variable of a split \E, or a parameter of an operator inlined with its value (Tool.getActionsAppl).

§Errors

A foreign scope, unknown slot or inadmissible value.

Source

pub fn scope_params(&self, scope: &Scope, def: DefId) -> Vec<Option<Value>>

The values bound to the parameters of def in the innermost frame of def in scope (walking out through enclosing frames), in parameter order; None for a parameter bound to anything but a value. This is what TLC prints in an action’s label (Action.getLocation).

Source

pub fn scope_enabled(&self, scope: &Scope) -> Result<Scope>

Branches at the current dynamic depth for one ENABLED query. Captured older scopes and bindings entered later retain their own cutoffs.

§Errors

A foreign scope.

Source

pub fn scope_substitution( &self, scope: &Scope, decl: DeclId, st: &St, primed: bool, ) -> Result<Option<SlotView>>

Looks up an actual substitution under the supplied evaluation control. None means absent; Some(SlotView::Unset) means explicitly unbound. Variable cutoff applies to primed reads inside ENABLED and all reads in its primed successor; constants are never hidden by that cutoff.

§Errors

A foreign scope/state or an unknown declaration.

Source

pub fn scope_subst_operator( &self, scope: &Scope, decl: DeclId, ) -> Result<Option<DefId>>

The uncaptured top-level definition substituted for an operator.

This only reads binding metadata. It does not execute the operator or prove its body pure. Lexical or dynamic captures and native/built-in operator values return None; a compiler must retain its named refusal for those contexts instead of dropping them.

§Errors

A foreign scope, unknown declaration, or inconsistent operator arity.

Source

pub fn scope_subst_slot(&self, scope: &Scope, decl: DeclId) -> SlotView

What the innermost substitution of decl in scope holds, if any.

Source

pub fn scope_slot(&self, scope: &Scope, r: LocalRef) -> SlotView

What a local reference in scope holds.

Source

pub fn scope_bindings( &self, scope: &Scope, quant: ExprId, st: &St, ) -> Result<Vec<Scope>>

The bindings of a bounded \E (an Expr::Quant) in scope, in TLC’s enumeration order (ContextEnumerator, first variable fastest): one scope per binding, each with the variables bound. The domains are evaluated in st (TLC’s getActions uses the empty state).

§Errors

Any error evaluating or enumerating a domain.

Source

pub fn scope_bindings_bounded( &self, scope: &Scope, quant: ExprId, st: &St, limit: usize, ) -> Result<Vec<Scope>>

Enumerates finite bindings of a quantifier, set filter/map or function constructor with entry-count bounds. Explicit sets, intervals and structurally finite lazy constructors are supported. Domain entries, materialized component/value slots and Cartesian bindings are each bounded by limit, before retaining them. Pure captured filters over bounded structural inputs are admitted; infinite, opaque and unresolved-effect domains remain explicit refusals. Order is the profile’s exploration order, first variable fastest. This is expression binding, not successor generation.

§Errors

Missing/nonfinite bounds, domain evaluation or tuple-pattern errors, and explicit domain/binding resource limits.

Source

pub fn scope_binder_analysis( &self, scope: &Scope, expr: ExprId, ) -> Result<Scope>

Binds each finite constructor/quantifier variable to a pure unknown. This context is only for conservative level and purity analysis of state-dependent domains. It does not evaluate a domain, assume it is finite, or choose a sample value. Every slot is conservatively state level and cannot be forced by the interpreter. Runtime evaluation must use the original scope with concrete bounded domain bindings.

§Errors

A non-binder expression or an unbounded domain.

Source

pub fn scope_constant_binder_analysis( &self, scope: &Scope, expr: ExprId, ) -> Result<Scope>

Binds each variable of a finite non-recursive binder over a constant domain to a pure constant-level unknown (SlotView::AnalysisConstant).

Static level and purity analysis visits the body once in this context instead of once per binding: a bound value is a constant that cannot change the body’s effects or the level of anything but itself. The domain is not evaluated, assumed finite or sampled; forcing a slot is the EvalError::is_analysis_only refusal. The caller must have established that every domain is constant level and pure. Runtime evaluation must use the original scope with concrete bindings.

§Errors

A non-binder or recursive-function expression, or an unbounded domain.

Source

pub fn eval_scoped(&self, scope: &Scope, expr: ExprId, st: &St) -> Result<Value>

Evaluates expr in scope.

§Errors

Any evaluation error, refusal or resource limit.

Source

pub fn eval_arg(&self, scope: &Scope, arg: &Arg, st: &St) -> Result<Value>

Evaluates an argument of an operator application in scope, as TLC’s getActionsAppl does before it inlines the operator (this.eval(args[i], con, TLCState.Empty)).

§Errors

Any evaluation error; an operator argument is not a value.

Source

pub fn precompute(&self, def: DefId) -> Result<Option<Value>>

Evaluates the body of a zero-arity definition at start-up and keeps the value for every later use, as SpecProcessor.processConstantDefns does (WorkerValue.demux(opDefEvaluator, opDef.getBody()), then opDef.setToolObject(toolId, val)). The body is evaluated every time this is called, as TLC evaluates it every time it meets it; the first value is kept (TLC keeps the last, which is the same value unless the definition draws random values). On failure nothing is kept and the definition stays lazy; TLC swallows the error.

A function TLC would keep as a lambda (FcnLambdaValue) is not kept: the definition stays lazy, and Ok(None) is returned. dive has no value form for such a function, and re-evaluating it is indistinguishable unless it is impure.

§Errors

The evaluation error, which the binding stage swallows as TLC does.

Source

pub fn precomputed(&self, def: DefId) -> Option<Value>

The value Evaluator::precompute kept for a definition.

Source§

impl Evaluator

Source

pub fn closed_predicate_stability_budgeted( &self, scope: &Scope, expr: ExprId, control: Option<&dyn HostControl>, ) -> Result<bool>

Inspects a pure predicate closure over closed function-tree state inputs. Immutable interval domains and stored closed general functions are admitted. Function constructors, CHOOSE, EXCEPT, raw/symbolic set history and ENABLED retain the existing explicit inspection refusal. Callers must prove the actual input rows are closed and must preserve EXCEPT warnings/errors through reference fallback. This is not the canonical producer certificate and does not attest arbitrary providers.

let eligible = ev.closed_predicate_stability_budgeted(scope, expr, None)?;
§Errors

An original interruption or inspection allocation failure.

Source

pub fn guarded_action_stability_budgeted( &self, scope: &Scope, expr: ExprId, control: Option<&dyn HostControl>, ) -> Result<bool>

Inspects an optional action closure whose single-key EXCEPT operations require a separate compiler/runtime proof of closed base, immutable interval binder, exact domain and scalar replacement. This fact alone never licenses evaluating an update or skipping reference warnings. The optional lane additionally inspects single scalar-bound interval constructors/CHOOSE and local integer enumeration/difference domains. A single-clause, single-key update may use lexical scalar @; runtime guards must establish its actual old leaf and replacement without skipping missing-key warnings. No real dynamic-@ capture is admitted. Recursive/nested updates, hidden queries, deferred providers and effects remain refused. The canonical producer and closed-predicate certificates keep their original boundaries. This inspection executes no constructor or CHOOSE and does not prove an arbitrary raw-set history.

let closure = ev.guarded_action_stability_budgeted(scope, expr, None)?;
// A successful inspection still requires compiler/runtime update guards.
§Errors

An original interruption or inspection allocation failure.

Source

pub fn canonical_producer_stability_budgeted( &self, producers: &[(ExprId, Scope)], predicates: &[(ExprId, Scope)], control: Option<&dyn HostControl>, ) -> Result<Option<ProducerStability>>

Inspects canonical producer and predicate storage under the run budget.

This callback-free inspection uses explicit traversal stacks, without a formula, value-depth or proof-work ceiling. Unknown representation or transfer semantics still return None. An explicit control is polled when supplied; otherwise the evaluator’s installed control is polled. No provider, expression or native permission callback is invoked. This grants neither private-host ownership nor completeness of the supplied producer roots. A single scalar CHOOSE binder may consume its own closed integer enumeration after element and scoped-body inspection. This does not relabel a retained raw set or certify an error, truth or demand order.

if let Some(fact) = ev.canonical_producer_stability_budgeted(&[root], &[], None)? {
    assert!(fact.belongs_to(ev));
}
§Errors

The original typed interruption, or failed traversal allocation.

Source§

impl Evaluator

Source

pub fn startup_fixed(&self, def: DefId) -> bool

Whether start-up fixed the value of def for the whole run: it was precomputed to an eager value, or the configuration assigns it a value, it is not redirected to another definition, and no configured redirect (Self::redirect_target) evaluates its body.

A precomputed value that holds a deferred set anywhere inside it ({x \in S : P} or {e : x \in S} kept lazy) is not fixed: each membership test or enumeration evaluates its predicate or map again while checking, so its body still runs after start-up.

if ev.startup_fixed(d) {
    assert!(ev.precomputed(d).is_some() || ev.is_value_override(d));
    assert!(!ev.redirect_target(d));
}
Source

pub fn redirect_target(&self, def: DefId) -> bool

Whether a configured redirect evaluates def’s body at each use, whatever value start-up gave def itself: it is the target of an Op <- def override (of a definition or of a Java-implemented operator), or of a constant bound by C <- def (SpecProcessor.java:276-316).

if ev.redirect_target(d) {
    assert!(!ev.startup_fixed(d));
}
Source

pub fn impure_after_startup(&self, expr: ExprId) -> bool

Whether evaluating expr while checking can have a side effect (output, registers, randomness, time, I/O or checker state): its IR Effects::IMPURE flag, except that a definition Self::startup_fixed is a value, and that a configured redirect (Op <- D, C <- D) reaches D’s body. When some redirect reaches an impure body, the IR’s flags, which follow syntactic references only, are not trusted and the walk visits every reachable node. Every source the walk does not resolve (operator parameters, instance substitutions, LET and parameter reads, an unknown node) counts as impure.

if !ev.impure_after_startup(e) {
    // Evaluating `e` while checking has no side effect.
}
Source§

impl Evaluator

Source

pub fn tuple_concat_sources( &self, roots: &[(ExprId, Scope)], definitions: &[DefId], control: Option<&dyn HostControl>, ) -> Result<Option<TupleConcatSources>>

Inspects complete source roots for constructor-grounded tuple concatenation.

Literal tuples and the unchanged native Append ground a finite monotone result analysis. All actuals remain unknown; recursion is never assumed tuple-valued. Every child is still inspected for its own calls. Opaque captures, native roots and unknown higher-order calls decline without forcing a value, calling a provider, or changing permissions or evaluation.

definitions are bare configuration/assumption roots, not merely native definitions seen as fully applied callees. This fact covers only the supplied roots; it does not grant model-wide name or parallel authority. The walk has no count or depth ceiling and polls the supplied control, or the installed evaluator control when it is absent.

let fact = ev.tuple_concat_sources(&[root], &[], None)?;
§Errors

Actual control interruption or a failed analysis allocation.

Source§

impl Evaluator

Source

pub fn shares_run_state(&self, other: &Self) -> bool

Whether both handles share the exact mutable evaluation core. This callback-free identity check binds deferred execution receipts to their original run; it is not semantic equality, graph or host authority.

Source

pub fn new(model: Model, opts: Options) -> Result<Self, ContextError>

An evaluator that collects Print output (see Evaluator::take_output). Admission checks IR references, override signatures/cycles and captured values before interning literals or invoking caller code. Bare numeric IDs are relative to model.ir; coincidentally equal foreign indices are not provenance certificates.

§Errors

A typed malformed context or bounded admission refusal.

Source

pub fn take_output(&self) -> Vec<String>

Takes the Print output collected so far (empty with a custom sink).

Source

pub fn has_print_event(&self) -> bool

Whether this evaluator has executed a Print or PrintT event.

This monotonic execution fact includes empty text, custom sinks and nested quiet captures. Warnings and unexecuted definitions do not set it; draining output does not reset it. It carries no replay certificate.

Source

pub fn release(&self, lines: Vec<Captured>)

Releases captured output (capture::PrintCapture) through the sink, in the order given. A captured warning is kept only if no warning with its text was printed before in the run.

Source

pub fn filter_captured_warnings(&self, lines: Vec<Captured>) -> Vec<Captured>

Applies the run’s warning history to captured output without calling any sink. Print events are retained even when their text repeats. This is an alternative to Self::release for drivers that return captured observations themselves; do not release the filtered warnings a second time, since they are already recorded in the run’s history.

use dive_eval::{Evaluator, capture::{Captured, PrintCapture}};
fn retained(ev: &Evaluator, cap: &PrintCapture) -> Vec<Captured> {
    ev.filter_captured_warnings(cap.take())
}
Source

pub fn scope_shares_side_effects(&self, scope: &Scope) -> bool

Whether evaluating in scope can run an expression with side effects (Print, TLCSet, randomness, …) through a lazily evaluated value that every evaluation shares: a cached LazyValue or a lazy function bound when the model was bound. Which evaluation forces such a value first, and so where its side effects happen, depends on the order of evaluation, so a parallel checker must not reorder those evaluations.

Source

pub fn scope_has_effects(&self, scope: &Scope) -> bool

Whether retained lazy expressions or actual captured operators may print, draw randomness, perform I/O or read live checker state. Foreign scopes and unresolved callable targets conservatively return true. Pure captured operators remain usable; the caller-supplied argument level is not authority for a callable’s effects.

This inspects retained contexts without executing expressions, forcing callbacks or scanning arbitrary stored values. It complements static IR effects when public Rust callers supply a predicate’s scope themselves.

Source

pub fn with_sink( model: Model, opts: Options, sink: Arc<dyn PrintSink>, ) -> Result<Self, ContextError>

An evaluator with its own Print sink, admitted before any sink call.

§Errors

The same context admission failures as Self::new.

Source

pub fn try_simulation_lease(&self) -> Option<SimulationLease<'_>>

Claims exclusive simulation entry without waiting. Evaluator clones share the same core, so overlapping and reentrant claims return None. Hold this lease through host restoration. Independent cores remain free to simulate concurrently. No host-registration lock is held by the lease.

use dive_eval::Evaluator;
fn shared_core(ev: &Evaluator) {
    let lease = ev.try_simulation_lease();
    assert!(lease.is_some());
    assert!(ev.clone().try_simulation_lease().is_none());
    drop(lease);
    assert!(ev.try_simulation_lease().is_some());
}
Source

pub fn set_host(&self, host: Arc<dyn Host>)

Installs the run hosting the evaluator (see Host): the model checker’s live state, its random streams and TLCSet("exit"). Replaces any host installed before.

Source

pub fn replace_host(&self, host: Option<Arc<dyn Host>>) -> Option<Arc<dyn Host>>

Installs host (or none) and returns the host installed before.

Source

pub fn replace_host_binding(&self, binding: HostBinding) -> HostBinding

Replaces the complete operative host binding and returns its predecessor.

Unlike Self::replace_host, this deliberately selects callback policy. It grants no private-run authority, purity or permission to skip work.

Source

pub fn native_hook_scope(&self, hooks: NativeHooks) -> Option<HostBindingScope>

Temporarily selects native hook execution, preserving the current host.

Unrestricted returns None without changing the binding unless a host is installed in ordinary cache domain zero and a fresh generation is available. Independent nonzero domains keep callbacks and cannot be warmed while omitting their permission hook. Domain zero is shared ordinary authority: values warmed there can remain cached after callbacks are restored. It is not an isolated guard domain. Other host methods and cooperative control are unchanged. The caller must own host changes until scope drop; evaluator clones are not locked. Plain setters select callbacks. This grants no private-run certificate.

use dive_eval::NativeHooks;
if let Some(scope) = ev.native_hook_scope(NativeHooks::Unrestricted) {
    assert_eq!(ev.host_binding_stamp().native_hooks(), NativeHooks::Unrestricted);
    drop(scope); // Restore the complete previous binding, not its generation.
}
Source

pub fn host_binding_stamp(&self) -> HostBindingStamp

Snapshots operative policy and nonreused installation generation. This is not a private-owner certificate or a concurrent replacement lease.

Source

pub fn host_control( &self, control: Option<Arc<dyn HostControl>>, ) -> Result<HostControlScope, HostControlConflict>

Installs cooperative host control until the returned scope drops.

Only evaluator loop checkpoints invoke it; ordinary host operations and expression cache domains are unchanged. Replacing the specification-visible host does not discard this control. The driver must own the evaluator’s control scope exclusively and classify interruption using its own evidence. Nested scopes on the owning thread restore the remaining innermost control, including when guards are dropped out of order. Worker threads may evaluate under that control, but cannot install a competing scope. None suspends control only on this owning thread (for diagnostic replay of an earlier deciding failure); other workers retain the underlying control.

§Errors

HostControlConflict if another thread owns an active scope.

Source

pub fn host(&self) -> Option<Arc<dyn Host>>

The installed host, if any.

Source

pub fn intern_checker_names(&self)

Interns the names TLC interns when it creates its model checker (TLCGET_NAMES), in TLC’s order. A driver that reproduces TLC’s name order calls it after the binding stage and before checking the assumptions, where TLC creates its ModelChecker. They are start-up names (Self::startup_names) if every name interned before them was.

Source

pub fn intern_bfs_config(&self, config: &RunConfig)

Interns the actual configuration strings constructed eagerly by TLC’s AbstractChecker.createConfig, after Self::intern_checker_names and before assumptions. Even a spec that never reads the config can observe these tokens through runtime CHOOSE ordering. They are start-up names (Self::startup_names) if every name interned before them was.

Source

pub fn seal_startup_names(&self)

Records every name interned so far as a start-up name: one TLC interns, in the same order, before it evaluates an ASSUME or a state. The binding stage calls it when it finishes.

Source

pub fn startup_names(&self) -> usize

The number of start-up names (Self::seal_startup_names). A name with a higher token was created at run time: its position in TLC’s encounter order depends on what was evaluated before it.

Source

pub fn equal_values(&self, a: &Value, b: &Value) -> Result<bool>

Compares two given values with this evaluator’s comparison profile. This is the equality used by the interpreter, including TLC’s errors under Comparisons::Tlc and the approved TLA+ comparison semantics. It does not evaluate an expression or generate successor states.

§Errors

A comparison the profile cannot decide, or a value/resource error.

Source

pub fn constant_binding(&self, constant: ConstId) -> Option<ConstBinding>

The configured binding of a root constant. This exposes the actual value or definition for conservative scoped preflight; it evaluates nothing and does not resolve instance substitutions.

Source

pub fn options(&self) -> &Options

The options.

Source

pub fn external_input_refusal(&self) -> Option<String>

First actual external-input refusal, including one caught during startup precomputation. Drivers must not certify that binding after a refusal. Host callbacks are not invoked to record category denials.

Source

pub fn take_external_input_refusal(&self) -> Option<String>

Takes the recorded external-input refusal, leaving none. The binding stage uses it to attribute a refusal to one start-up evaluation, and puts it back with Evaluator::restore_external_input_refusal unless that evaluation provably cannot affect the model.

Source

pub fn restore_external_input_refusal(&self, refusal: Option<String>)

Records refusal as the external-input refusal unless one is already recorded (the first refusal wins).

Source

pub fn ir(&self) -> &Arc<Ir> ⓘ

The IR.

Source

pub fn eval_def(&self, def: DefId, st: &St) -> Result<Value>

Evaluates a zero-arity definition.

§Errors

Any evaluation error, refusal or resource limit.

Source

pub fn tlc_register(&self, op: StdOp, args: &[Value]) -> Result<Value>

TLCSet(key, value) or TLCGet(key) on evaluated arguments, against this evaluator’s registers, which start-up evaluation (constant definitions, ASSUMEs) wrote: integer registers, named "s:..." registers, "all" and "all:named", and the run’s "config" record, which the host provides. Errors are wrapped as TLC wraps them: TLCGet’s as its EvaluatingValue’s, TLCSet’s as a Java override’s. Another engine evaluating the specification calls it to share the run’s registers. TLCGet of any other string, and TLCSet of "exit", "pause" or a "-D" property, is refused by name: the caller knows the run’s level, counters and stop.

§Errors

TLC’s evaluation error, or a refusal.

Source

pub fn eval_in(&self, def: DefId, expr: ExprId, st: &St) -> Result<Value>

Evaluates the body of a top-level definition as a predicate or value in its own frame: expr must belong to def’s frame.

§Errors

Any evaluation error, refusal or resource limit.

Source

pub fn check_assumptions( &self, is_axiom: impl Fn(DefId) -> bool, ) -> AssumptionOutcome

TLC’s Tool.checkAssumptions: evaluates the root module’s assumptions in order (skipping those is_axiom selects), stopping at the first that is not TRUE.

Source

pub fn check_assumption(&self, a: DefId) -> AssumptionOutcome

Evaluates one assumption as TLC does (Tool.isValid(expr): states Empty, control Const).

Source

pub fn false_assumption(&self, a: DefId) -> AssumptionOutcome

The outcome Self::check_assumption reports for a when it evaluates to FALSE, for an evaluator that found it so (Core’s start-up evaluation of a pure ASSUME), without evaluating it again.

Source

pub fn redirected(&self, def: DefId) -> DefId

The definition the configuration makes def stand for, following Op <- Other overrides; def itself when it is not overridden.

Source

pub fn is_value_override(&self, def: DefId) -> bool

Whether the configuration assigns def a value (Op = v).

Source

pub fn value_override(&self, def: DefId) -> Option<Value>

The value the configuration assigns def (Op = v), if any. Core reads it at its binder boundary (dive-api’s core_engine).

Source

pub fn startup_error(&self) -> Option<EvalError>

The error TLC raises while processing the specification, before checking assumptions: a numeral too big for --int=tlc (TLC_INTEGER_TOO_BIG) or a decimal (TLC_CANT_HANDLE_REAL_NUMBERS). The binding stage reports it as TLC does, as a top-level error.

Source

pub fn location(&self, e: ExprId) -> String

TLC’s location string for an expression (SemanticNode.toString()).

Source

pub fn assumptions(&self) -> Vec<DefId>

The assumptions of the root module, in order, with whether each is a theorem-like definition kind TLC never evaluates.

Trait Implementations§

Source§

impl Clone for Evaluator

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Evaluator

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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.