dive_eval/lib.rs
1//! `dive-eval`: the evaluator for expressions and actions over states.
2//!
3//! It evaluates the IR ([`dive_ir`]) over `dive-value` values with
4//! TLC's semantics: TLC's evaluation order, its laziness (operator arguments,
5//! zero-arity `LET` definitions and instance substitutions are thunks forced
6//! under TLC's caching rule), its lazy sets and functions, `CHOOSE` in the
7//! run's value order, and TLC's errors with TLC's messages. Anything it does
8//! not implement exactly is refused as [`ErrorClass::Unsupported`], naming
9//! the feature.
10//!
11//! # Using it
12//!
13//! A [`Model`] binds the IR's constants (normally built by `dive-model` from
14//! the configuration); an [`Evaluator`] evaluates definitions, expressions
15//! and assumptions under [`Options`]:
16//!
17//! ```
18//! use std::sync::Arc;
19//! use dive_eval::{Evaluator, Model, Options, St};
20//! use dive_sema::{Options as SemaOptions, analyze_source};
21//!
22//! let src = "---- MODULE M ----\nEXTENDS Naturals\nTwice(n) == n + n\nX == Twice(21)\n====\n";
23//! let ir = dive_ir::lower(&analyze_source("M.tla", src, &SemaOptions::default())).expect("lowers");
24//! let x = ir.root_def("X").expect("defined");
25//! let ev = Evaluator::new(Model::new(Arc::new(ir)), Options::tlc()).expect("valid context");
26//! assert_eq!(ev.eval_def(x, &St::constant()).expect("evaluates"), 42.into());
27//! ```
28//!
29//! # How the successor generator plugs in
30//!
31//! `dive_eval::next` ports TLC's `getInitStates`, `getNextStates`,
32//! `getActions` and `enabled`: it generates initial states and successors in
33//! TLC's order, duplicates included, evaluating the non-action parts of an
34//! action through this interpreter against the partial successor it is
35//! building, and uses [`EvalError`] for the error classes. `ENABLED` goes
36//! through it too, for the checker and the trace validator alike.
37#![forbid(unsafe_code)]
38
39mod host_io;
40pub mod inputs;
41
42mod bounded_domain;
43pub mod capture;
44mod community;
45mod context;
46mod core;
47pub use context::{ContextError, ContextErrorKind, validate_ir};
48mod env;
49mod error;
50mod eval;
51mod finite;
52mod generation;
53mod host;
54mod json;
55mod lazy;
56mod named_state;
57pub mod next;
58mod options;
59mod random_relation;
60mod recursive_leaf;
61mod scope;
62mod stability;
63mod startup_calls;
64mod startup_fixed;
65mod std;
66mod svg;
67mod tla_cmp;
68mod tlc_enum;
69mod tuple_names;
70
71#[path = "subset_mask.rs"]
72mod subset_mask;
73
74use ::std::collections::HashMap;
75use ::std::sync::Arc;
76
77use dive_ir::{DefId, DefKind, ExprId, Ir};
78use dive_value::{Interner, Value};
79
80use crate::core::Core;
81pub use crate::core::{CollectSink, PrintSink};
82use crate::env::{Dyn, Env, Ev};
83pub use crate::env::{St, StateRef};
84pub use crate::error::{
85 Ec, ErrorClass, EvalError, ExceptionKind, Result, ValueMethod, ValueMethodFailure,
86};
87pub use crate::host::{
88 Counter, Host, HostBinding, HostBindingScope, HostBindingStamp, HostControl,
89 HostControlConflict, HostControlScope, HostError, Interrupted, NativeHooks,
90 PRIMED_LEVEL_UNSUPPORTED, RunConfig, TLCGET_NAMES,
91};
92pub use crate::lazy::{LazyFcn, deferred_filter_normalization_operand};
93pub use crate::named_state::NamedState;
94pub use crate::options::{
95 ActionComposition, Comparisons, DEFAULT_MAX_DEPTH, ExplorationOrder, Options, Profile,
96 RECOMMENDED_STACK,
97};
98pub use crate::scope::{Scope, SlotView};
99pub use crate::stability::ProducerStability;
100pub use crate::tuple_names::TupleConcatSources;
101
102/// Exclusive simulation entry on a shared evaluator core. Dropping the lease
103/// permits the next simulation. The driver must restore its host before drop.
104/// Ordinary evaluator operations and host setters keep their existing behavior;
105/// callers must not mix foreign evaluator/host operations with an active simulation.
106#[derive(Debug)]
107pub struct SimulationLease<'a> {
108 active: &'a ::std::sync::atomic::AtomicBool,
109}
110
111impl Drop for SimulationLease<'_> {
112 fn drop(&mut self) {
113 self.active
114 .store(false, ::std::sync::atomic::Ordering::Release);
115 }
116}
117
118/// What the configuration binds a constant to.
119#[derive(Clone, Debug)]
120pub enum ConstBinding {
121 /// A value (`C = v` in the `.cfg`, including model values).
122 Value(Value),
123 /// A definition (`C <- D`), also for constant operators (`F(_)`).
124 Def(DefId),
125}
126
127/// The bindings evaluation needs beyond the IR: the run's names and the
128/// constants. `dive-model` builds it from the configuration.
129#[derive(Clone, Debug)]
130pub struct Model {
131 /// The lowered specification.
132 pub ir: Arc<Ir>,
133 /// The run's names. To reproduce TLC's order of strings and model values
134 /// under `--choose-order=tlc`, intern them in SANY/TLC's encounter order
135 /// before building the evaluator.
136 pub names: Arc<Interner>,
137 /// Constant bindings, by [`dive_ir::ConstId`].
138 pub constants: Vec<Option<ConstBinding>>,
139 /// Definition overrides from the configuration (`Op <- Other`).
140 pub redirects: HashMap<DefId, DefId>,
141 /// Definitions the configuration assigns a value (`Op = v`).
142 pub def_values: HashMap<DefId, Value>,
143}
144
145impl Model {
146 /// A model with no constants bound and a fresh name table.
147 #[must_use]
148 pub fn new(ir: Arc<Ir>) -> Self {
149 let n = ir.consts().len();
150 Self {
151 ir,
152 names: Arc::new(Interner::new()),
153 constants: vec![None; n],
154 redirects: HashMap::new(),
155 def_values: HashMap::new(),
156 }
157 }
158}
159
160/// The outcome of checking the assumptions, as TLC's
161/// `Tool.checkAssumptions` reports it.
162#[derive(Clone, Debug)]
163pub enum AssumptionOutcome {
164 /// Every assumption is `TRUE`.
165 AllTrue,
166 /// An assumption is `FALSE`: TLC's `TLC_ASSUMPTION_FALSE` (2104).
167 False {
168 /// The assumption.
169 def: DefId,
170 /// The evaluated assumption's source image, as TLC names it.
171 property: String,
172 /// TLC's message.
173 message: String,
174 },
175 /// Evaluating an assumption failed: TLC's
176 /// `TLC_ASSUMPTION_EVALUATION_ERROR` (2105), or a refusal or resource
177 /// limit.
178 Error {
179 /// The assumption.
180 def: DefId,
181 /// The error.
182 error: EvalError,
183 /// TLC's message (for an evaluation error).
184 message: String,
185 },
186}
187
188/// An evaluator for one specification and model.
189#[derive(Clone, Debug)]
190pub struct Evaluator {
191 core: Arc<Core>,
192 collected: Option<Arc<CollectSink>>,
193}
194
195impl Evaluator {
196 /// Whether both handles share the exact mutable evaluation core. This
197 /// callback-free identity check binds deferred execution receipts to their
198 /// original run; it is not semantic equality, graph or host authority.
199 #[must_use]
200 pub fn shares_run_state(&self, other: &Self) -> bool {
201 Arc::ptr_eq(&self.core, &other.core)
202 }
203 /// An evaluator that collects `Print` output (see [`Evaluator::take_output`]).
204 /// Admission checks IR references, override signatures/cycles and captured
205 /// values before interning literals or invoking caller code. Bare numeric IDs
206 /// are relative to `model.ir`; coincidentally equal foreign indices are not
207 /// provenance certificates.
208 ///
209 /// # Errors
210 /// A typed malformed context or bounded admission refusal.
211 pub fn new(model: Model, opts: Options) -> ::std::result::Result<Self, ContextError> {
212 let sink = Arc::new(CollectSink::default());
213 let mut ev = Self::with_sink(model, opts, sink.clone())?;
214 ev.collected = Some(sink);
215 Ok(ev)
216 }
217
218 /// Takes the `Print` output collected so far (empty with a custom sink).
219 #[must_use]
220 pub fn take_output(&self) -> Vec<String> {
221 self.collected
222 .as_ref()
223 .map(|s| s.take())
224 .unwrap_or_default()
225 }
226
227 /// Whether this evaluator has executed a `Print` or `PrintT` event.
228 ///
229 /// This monotonic execution fact includes empty text, custom sinks and
230 /// nested quiet captures. Warnings and unexecuted definitions do not set it;
231 /// draining output does not reset it. It carries no replay certificate.
232 #[must_use]
233 pub fn has_print_event(&self) -> bool {
234 self.core
235 .printed
236 .load(::std::sync::atomic::Ordering::Relaxed)
237 }
238
239 /// Releases captured output ([`capture::PrintCapture`]) through the
240 /// sink, in the order given. A captured warning is kept only if no
241 /// warning with its text was printed before in the run.
242 pub fn release(&self, lines: Vec<capture::Captured>) {
243 for line in lines {
244 if !line.warning || self.core.first_warning(&line.text) {
245 self.core.sink.print(line.text);
246 }
247 }
248 }
249
250 /// Applies the run's warning history to captured output without calling
251 /// any sink. Print events are retained even when their text repeats.
252 /// This is an alternative to [`Self::release`] for drivers that return
253 /// captured observations themselves; do not release the filtered warnings
254 /// a second time, since they are already recorded in the run's history.
255 ///
256 /// ```
257 /// use dive_eval::{Evaluator, capture::{Captured, PrintCapture}};
258 /// fn retained(ev: &Evaluator, cap: &PrintCapture) -> Vec<Captured> {
259 /// ev.filter_captured_warnings(cap.take())
260 /// }
261 /// ```
262 #[must_use]
263 pub fn filter_captured_warnings(
264 &self,
265 lines: Vec<capture::Captured>,
266 ) -> Vec<capture::Captured> {
267 lines
268 .into_iter()
269 .filter(|line| !line.warning || self.core.first_warning(&line.text))
270 .collect()
271 }
272
273 /// Whether evaluating in `scope` can run an expression with side effects
274 /// (`Print`, `TLCSet`, randomness, ...) through a lazily evaluated value
275 /// that every evaluation shares: a cached `LazyValue` or a lazy function
276 /// bound when the model was bound. Which evaluation forces such a value
277 /// first, and so where its side effects happen, depends on the order of
278 /// evaluation, so a parallel checker must not reorder those evaluations.
279 #[must_use]
280 pub fn scope_shares_side_effects(&self, scope: &Scope) -> bool {
281 self.validate_scope(scope).is_err() || env::shares_side_effects(&self.core.ir, &scope.env)
282 }
283
284 /// Whether retained lazy expressions or actual captured operators may print,
285 /// draw randomness, perform I/O or read live checker state. Foreign scopes
286 /// and unresolved callable targets conservatively return true. Pure captured
287 /// operators remain usable; the caller-supplied argument level is not authority
288 /// for a callable's effects.
289 ///
290 /// This inspects retained contexts without executing expressions, forcing
291 /// callbacks or scanning arbitrary stored values. It complements static IR
292 /// effects when public Rust callers supply a predicate's scope themselves.
293 #[must_use]
294 pub fn scope_has_effects(&self, scope: &Scope) -> bool {
295 use dive_ir::{Effects, StdSupport};
296 if self.validate_scope(scope).is_err() {
297 return true;
298 }
299 let native = |op: dive_ir::StdOp| {
300 op.impure() || matches!(op.support(), StdSupport::Io | StdSupport::Introspection)
301 };
302 let definition = |id: dive_ir::DefId| {
303 let Some(def) = self.core.ir.defs().get(self.core.redirect(id).index()) else {
304 return true;
305 };
306 def.std.map_or_else(
307 || {
308 self.core
309 .ir
310 .nodes()
311 .get(def.body.index())
312 .is_none_or(|node| {
313 node.effects
314 .intersects(Effects::IMPURE | Effects::LIVE_TLCGET)
315 })
316 },
317 native,
318 )
319 };
320 env::scope_has_effects(&self.core.ir, &scope.env, &|operator| match operator {
321 env::OpVal::Std(op) => native(*op),
322 env::OpVal::Def { def, .. } => definition(*def),
323 env::OpVal::Const(id) => {
324 match self.core.consts.get(id.index()).and_then(Option::as_ref) {
325 Some(ConstBinding::Def(def)) => definition(*def),
326 Some(ConstBinding::Value(_)) | None => true,
327 }
328 }
329 env::OpVal::Builtin(_) => false,
330 env::OpVal::Unbound(_) => true,
331 })
332 }
333
334 /// An evaluator with its own `Print` sink, admitted before any sink call.
335 ///
336 /// # Errors
337 /// The same context admission failures as [`Self::new`].
338 pub fn with_sink(
339 mut model: Model,
340 opts: Options,
341 sink: Arc<dyn PrintSink>,
342 ) -> ::std::result::Result<Self, ContextError> {
343 context::validate(&mut model)?;
344 Ok(Self {
345 core: Arc::new(Core::new(model, opts, sink)),
346 collected: None,
347 })
348 }
349
350 /// Claims exclusive simulation entry without waiting. Evaluator clones share
351 /// the same core, so overlapping and reentrant claims return `None`.
352 /// Hold this lease through host restoration. Independent cores remain free
353 /// to simulate concurrently. No host-registration lock is held by the lease.
354 ///
355 /// ```
356 /// use dive_eval::Evaluator;
357 /// fn shared_core(ev: &Evaluator) {
358 /// let lease = ev.try_simulation_lease();
359 /// assert!(lease.is_some());
360 /// assert!(ev.clone().try_simulation_lease().is_none());
361 /// drop(lease);
362 /// assert!(ev.try_simulation_lease().is_some());
363 /// }
364 /// ```
365 #[must_use]
366 pub fn try_simulation_lease(&self) -> Option<SimulationLease<'_>> {
367 self.core
368 .simulation_active
369 .compare_exchange(
370 false,
371 true,
372 ::std::sync::atomic::Ordering::AcqRel,
373 ::std::sync::atomic::Ordering::Acquire,
374 )
375 .ok()
376 .map(|_| SimulationLease {
377 active: &self.core.simulation_active,
378 })
379 }
380
381 /// Installs the run hosting the evaluator (see [`Host`]): the model
382 /// checker's live state, its random streams and `TLCSet("exit")`.
383 /// Replaces any host installed before.
384 pub fn set_host(&self, host: Arc<dyn Host>) {
385 let _ = self.replace_host(Some(host));
386 }
387
388 /// Installs `host` (or none) and returns the host installed before.
389 #[must_use = "the previous host must be restored or dropped deliberately"]
390 pub fn replace_host(&self, host: Option<Arc<dyn Host>>) -> Option<Arc<dyn Host>> {
391 self.core.host.replace(host)
392 }
393
394 /// Replaces the complete operative host binding and returns its predecessor.
395 ///
396 /// Unlike [`Self::replace_host`], this deliberately selects callback policy.
397 /// It grants no private-run authority, purity or permission to skip work.
398 #[must_use = "restore or drop the complete previous binding deliberately"]
399 pub fn replace_host_binding(&self, binding: HostBinding) -> HostBinding {
400 self.core.host.replace_binding(binding)
401 }
402
403 /// Temporarily selects native hook execution, preserving the current host.
404 ///
405 /// `Unrestricted` returns `None` without changing the binding unless a host
406 /// is installed in ordinary cache domain zero and a fresh generation is
407 /// available. Independent nonzero domains
408 /// keep callbacks and cannot be warmed while omitting their permission hook.
409 /// Domain zero is shared ordinary authority: values warmed there can remain
410 /// cached after callbacks are restored. It is not an isolated guard domain.
411 /// Other host methods and cooperative control are unchanged. The caller
412 /// must own host changes until scope drop; evaluator clones are not locked.
413 /// Plain setters select callbacks. This grants no private-run certificate.
414 ///
415 /// ```
416 /// # fn select(ev: &dive_eval::Evaluator) {
417 /// use dive_eval::NativeHooks;
418 /// if let Some(scope) = ev.native_hook_scope(NativeHooks::Unrestricted) {
419 /// assert_eq!(ev.host_binding_stamp().native_hooks(), NativeHooks::Unrestricted);
420 /// drop(scope); // Restore the complete previous binding, not its generation.
421 /// }
422 /// # }
423 /// ```
424 #[must_use]
425 pub fn native_hook_scope(&self, hooks: NativeHooks) -> Option<HostBindingScope> {
426 let previous = self.core.host.replace_hooks(hooks)?;
427 Some(HostBindingScope {
428 core: self.core.clone(),
429 previous: Some(previous),
430 _thread: ::std::marker::PhantomData,
431 })
432 }
433
434 /// Snapshots operative policy and nonreused installation generation.
435 /// This is not a private-owner certificate or a concurrent replacement lease.
436 #[must_use]
437 pub fn host_binding_stamp(&self) -> HostBindingStamp {
438 self.core.host.stamp()
439 }
440
441 /// Installs cooperative host control until the returned scope drops.
442 ///
443 /// Only evaluator loop checkpoints invoke it; ordinary host operations and
444 /// expression cache domains are unchanged. Replacing the specification-visible
445 /// host does not discard this control. The driver must own the evaluator's
446 /// control scope exclusively and classify interruption using its own evidence.
447 #[must_use = "the scope must live until evaluation finishes"]
448 /// Nested scopes on the owning thread restore the remaining innermost
449 /// control, including when guards are dropped out of order. Worker threads
450 /// may evaluate under that control, but cannot install a competing scope.
451 /// `None` suspends control only on this owning thread (for diagnostic replay
452 /// of an earlier deciding failure); other workers retain the underlying control.
453 ///
454 /// # Errors
455 /// [`HostControlConflict`] if another thread owns an active scope.
456 pub fn host_control(
457 &self,
458 control: Option<Arc<dyn HostControl>>,
459 ) -> Result<HostControlScope, HostControlConflict> {
460 Ok(HostControlScope {
461 core: self.core.clone(),
462 token: self.core.host.push_control(control)?,
463 _thread: ::std::marker::PhantomData,
464 })
465 }
466
467 /// The installed host, if any.
468 #[must_use]
469 pub fn host(&self) -> Option<Arc<dyn Host>> {
470 self.core.host.get()
471 }
472
473 /// Interns the names TLC interns when it creates its model checker
474 /// ([`TLCGET_NAMES`]), in TLC's order. A driver that reproduces TLC's
475 /// name order calls it after the binding stage and before checking the
476 /// assumptions, where TLC creates its `ModelChecker`.
477 /// They are start-up names ([`Self::startup_names`]) if every name
478 /// interned before them was.
479 pub fn intern_checker_names(&self) {
480 self.extend_startup_names(|| {
481 for n in TLCGET_NAMES {
482 self.core.names.intern(n);
483 }
484 });
485 }
486
487 /// Interns the actual configuration strings constructed eagerly by
488 /// TLC's `AbstractChecker.createConfig`, after [`Self::intern_checker_names`]
489 /// and before assumptions. Even a spec that never reads the config can
490 /// observe these tokens through runtime `CHOOSE` ordering.
491 /// They are start-up names ([`Self::startup_names`]) if every name
492 /// interned before them was.
493 pub fn intern_bfs_config(&self, config: &RunConfig) {
494 self.extend_startup_names(|| {
495 self.core.names.intern("bfs");
496 self.core.names.intern(&config.seed.to_string());
497 self.core.names.intern(&config.fingerprint.to_string());
498 self.core.names.intern(&config.install);
499 });
500 }
501
502 /// Records every name interned so far as a start-up name: one TLC
503 /// interns, in the same order, before it evaluates an `ASSUME` or a
504 /// state. The binding stage calls it when it finishes.
505 pub fn seal_startup_names(&self) {
506 self.core
507 .startup_names
508 .store(self.core.names.len(), ::std::sync::atomic::Ordering::SeqCst);
509 }
510
511 /// The number of start-up names ([`Self::seal_startup_names`]). A name
512 /// with a higher token was created at run time: its position in TLC's
513 /// encounter order depends on what was evaluated before it.
514 #[must_use]
515 pub fn startup_names(&self) -> usize {
516 self.core
517 .startup_names
518 .load(::std::sync::atomic::Ordering::SeqCst)
519 }
520
521 /// Runs `f`, which interns start-up names, and counts them as start-up
522 /// names only if no run-time name was interned before them.
523 fn extend_startup_names(&self, f: impl FnOnce()) {
524 let contiguous = self.core.names.len() == self.startup_names();
525 f();
526 if contiguous {
527 self.seal_startup_names();
528 }
529 }
530
531 /// Compares two given values with this evaluator's comparison profile.
532 /// This is the equality used by the interpreter, including TLC's errors
533 /// under `Comparisons::Tlc` and the approved TLA+ comparison semantics.
534 /// It does not evaluate an expression or generate successor states.
535 ///
536 /// # Errors
537 /// A comparison the profile cannot decide, or a value/resource error.
538 pub fn equal_values(&self, a: &Value, b: &Value) -> Result<bool> {
539 self.core.equals(a, b)
540 }
541
542 /// The configured binding of a root constant. This exposes the actual
543 /// value or definition for conservative scoped preflight; it evaluates
544 /// nothing and does not resolve instance substitutions.
545 #[must_use]
546 pub fn constant_binding(&self, constant: dive_ir::ConstId) -> Option<ConstBinding> {
547 self.core.consts.get(constant.index()).cloned().flatten()
548 }
549
550 /// The options.
551 #[must_use]
552 pub fn options(&self) -> &Options {
553 &self.core.opts
554 }
555
556 /// First actual external-input refusal, including one caught during startup
557 /// precomputation. Drivers must not certify that binding after a refusal.
558 /// Host callbacks are not invoked to record category denials.
559 #[must_use]
560 pub fn external_input_refusal(&self) -> Option<String> {
561 self.core
562 .input_refusal
563 .lock()
564 .unwrap_or_else(::std::sync::PoisonError::into_inner)
565 .clone()
566 }
567
568 /// Takes the recorded external-input refusal, leaving none. The binding
569 /// stage uses it to attribute a refusal to one start-up evaluation, and
570 /// puts it back with [`Evaluator::restore_external_input_refusal`] unless
571 /// that evaluation provably cannot affect the model.
572 #[must_use]
573 pub fn take_external_input_refusal(&self) -> Option<String> {
574 self.core
575 .input_refusal
576 .lock()
577 .unwrap_or_else(::std::sync::PoisonError::into_inner)
578 .take()
579 }
580
581 /// Records `refusal` as the external-input refusal unless one is already
582 /// recorded (the first refusal wins).
583 pub fn restore_external_input_refusal(&self, refusal: Option<String>) {
584 if let Some(refusal) = refusal {
585 self.core
586 .input_refusal
587 .lock()
588 .unwrap_or_else(::std::sync::PoisonError::into_inner)
589 .get_or_insert(refusal);
590 }
591 }
592
593 /// The IR.
594 #[must_use]
595 pub fn ir(&self) -> &Arc<Ir> {
596 &self.core.ir
597 }
598
599 /// Evaluates a zero-arity definition.
600 ///
601 /// # Errors
602 /// Any evaluation error, refusal or resource limit.
603 pub fn eval_def(&self, def: DefId, st: &St) -> Result<Value> {
604 self.validate_state_context(st)?;
605 let d = self.admit_def(def)?;
606 if !d.params.is_empty() {
607 return Err(EvalError::bug(format!(
608 "{} takes {} arguments",
609 d.name,
610 d.params.len()
611 )));
612 }
613 let mut env = Env::new(def, d.depth, d.frame.len(), None, Dyn::default());
614 let ev = self.core.eval(&mut env, st, d.body)?;
615 self.core.force_fcn(ev)
616 }
617
618 /// `TLCSet(key, value)` or `TLCGet(key)` on evaluated arguments, against
619 /// this evaluator's registers, which start-up evaluation (constant
620 /// definitions, `ASSUME`s) wrote: integer registers, named `"s:..."`
621 /// registers, `"all"` and `"all:named"`, and the run's `"config"`
622 /// record, which the host provides. Errors are wrapped as TLC
623 /// wraps them: `TLCGet`'s as its `EvaluatingValue`'s, `TLCSet`'s as a
624 /// Java override's. Another engine evaluating the specification calls
625 /// it to share the run's registers. `TLCGet` of any other string, and
626 /// `TLCSet` of `"exit"`, `"pause"` or a `"-D"` property, is refused by
627 /// name: the caller knows the run's level, counters and stop.
628 ///
629 /// # Errors
630 /// TLC's evaluation error, or a refusal.
631 pub fn tlc_register(&self, op: dive_ir::StdOp, args: &[Value]) -> Result<Value> {
632 let refuse = |k: &str| {
633 EvalError::unsupported(format!(
634 "{}(\"{k}\") outside the evaluator",
635 op.qualified_name()
636 ))
637 };
638 let plain = |k: &Value| match k {
639 Value::Str(s) => {
640 let s = s.as_str();
641 let ok = if op == dive_ir::StdOp::TlcTLCGet {
642 // `"config"` is the run's, fixed before the ASSUMEs.
643 s.starts_with("s:") || s == "all" || s == "all:named" || s == "config"
644 } else {
645 // Any other string is TLC's argument error.
646 !(s == "exit" || s == "pause" || s.starts_with("-D"))
647 };
648 if ok { Ok(()) } else { Err(refuse(s)) }
649 }
650 _ => Ok(()),
651 };
652 match (op, args) {
653 (dive_ir::StdOp::TlcTLCGet, [k]) => {
654 plain(k)?;
655 self.core
656 .tlc_get_value(k, &St::constant())
657 .map_err(|e| self.core.wrap_evaluating(op, e))
658 }
659 (dive_ir::StdOp::TlcTLCSet, [k, v]) => {
660 plain(k)?;
661 self.core
662 .tlc_set(k, v)
663 .map_err(|e| self.core.wrap_override(op, e))
664 }
665 _ => Err(EvalError::bug(format!(
666 "{} is not a register operator",
667 op.qualified_name()
668 ))),
669 }
670 }
671
672 /// Evaluates the body of a top-level definition as a predicate or value
673 /// in its own frame: `expr` must belong to `def`'s frame.
674 ///
675 /// # Errors
676 /// Any evaluation error, refusal or resource limit.
677 pub fn eval_in(&self, def: DefId, expr: ExprId, st: &St) -> Result<Value> {
678 self.validate_state_context(st)?;
679 let scope = self.scope(def)?;
680 self.admit_scoped_expr(&scope, expr)?;
681 let d = self.admit_def(def)?;
682 let mut env = Env::new(def, d.depth, d.frame.len(), None, Dyn::default());
683 let ev = self.core.eval(&mut env, st, expr)?;
684 self.core.force_fcn(ev)
685 }
686
687 /// TLC's `Tool.checkAssumptions`: evaluates the root module's
688 /// assumptions in order (skipping those `is_axiom` selects), stopping at
689 /// the first that is not `TRUE`.
690 pub fn check_assumptions(&self, is_axiom: impl Fn(DefId) -> bool) -> AssumptionOutcome {
691 let ir = &self.core.ir;
692 let root = ir.module(ir.root());
693 for &a in &root.assumptions {
694 if is_axiom(a) {
695 continue;
696 }
697 match self.check_assumption(a) {
698 AssumptionOutcome::AllTrue => {}
699 other => return other,
700 }
701 }
702 AssumptionOutcome::AllTrue
703 }
704
705 /// Evaluates one assumption as TLC does (`Tool.isValid(expr)`: states
706 /// `Empty`, control `Const`).
707 #[must_use]
708 pub fn check_assumption(&self, a: DefId) -> AssumptionOutcome {
709 let def = match self.admit_def(a) {
710 Ok(def) => def,
711 Err(error) => {
712 return AssumptionOutcome::Error {
713 def: a,
714 message: error.to_string(),
715 error,
716 };
717 }
718 };
719 let loc = self.core.loc(def.body);
720 let mut env = Env::new(a, def.depth, def.frame.len(), None, Dyn::default());
721 match self.core.eval(&mut env, &St::constant(), def.body) {
722 Ok(Ev::V(Value::Bool(true))) => AssumptionOutcome::AllTrue,
723 Ok(Ev::V(Value::Bool(false))) => Self::assumption_false(a, loc),
724 Ok(_) => {
725 let error = EvalError::coded(
726 Ec::ExpectedValue,
727 format!("TLC expected a boolean value, but did not find one. {loc}"),
728 );
729 let message = format!("Evaluating assumption {loc} failed.\n{}", error.tool_text());
730 AssumptionOutcome::Error {
731 def: a,
732 error,
733 message,
734 }
735 }
736 Err(error) => {
737 let message = format!("Evaluating assumption {loc} failed.\n{}", error.tool_text());
738 AssumptionOutcome::Error {
739 def: a,
740 error,
741 message,
742 }
743 }
744 }
745 }
746
747 /// The outcome [`Self::check_assumption`] reports for `a` when it
748 /// evaluates to `FALSE`, for an evaluator that found it so (Core's
749 /// start-up evaluation of a pure `ASSUME`), without
750 /// evaluating it again.
751 #[must_use]
752 pub fn false_assumption(&self, a: DefId) -> AssumptionOutcome {
753 match self.admit_def(a) {
754 Ok(def) => Self::assumption_false(a, self.core.loc(def.body)),
755 Err(error) => AssumptionOutcome::Error {
756 def: a,
757 message: error.to_string(),
758 error,
759 },
760 }
761 }
762
763 fn assumption_false(a: DefId, loc: String) -> AssumptionOutcome {
764 AssumptionOutcome::False {
765 def: a,
766 message: format!("Assumption {loc} is false."),
767 property: loc,
768 }
769 }
770
771 /// The definition the configuration makes `def` stand for, following
772 /// `Op <- Other` overrides; `def` itself when it is not overridden.
773 #[must_use]
774 pub fn redirected(&self, def: DefId) -> DefId {
775 self.core.redirect(def)
776 }
777
778 /// Whether the configuration assigns `def` a value (`Op = v`).
779 #[must_use]
780 pub fn is_value_override(&self, def: DefId) -> bool {
781 self.core.def_values.contains_key(&def)
782 }
783
784 /// The value the configuration assigns `def` (`Op = v`), if any. Core
785 /// reads it at its binder boundary (`dive-api`'s
786 /// `core_engine`).
787 #[must_use]
788 pub fn value_override(&self, def: DefId) -> Option<Value> {
789 self.core.def_values.get(&def).cloned()
790 }
791
792 /// The error TLC raises while processing the specification, before
793 /// checking assumptions: a numeral too big for `--int=tlc`
794 /// (`TLC_INTEGER_TOO_BIG`) or a decimal (`TLC_CANT_HANDLE_REAL_NUMBERS`).
795 /// The binding stage reports it as TLC does, as a top-level error.
796 #[must_use]
797 pub fn startup_error(&self) -> Option<EvalError> {
798 self.core.startup_error()
799 }
800
801 /// TLC's location string for an expression (`SemanticNode.toString()`).
802 #[must_use]
803 pub fn location(&self, e: ExprId) -> String {
804 self.core.loc(e)
805 }
806
807 /// The assumptions of the root module, in order, with whether each is a
808 /// theorem-like definition kind TLC never evaluates.
809 #[must_use]
810 pub fn assumptions(&self) -> Vec<DefId> {
811 let ir = &self.core.ir;
812 ir.module(ir.root())
813 .assumptions
814 .iter()
815 .copied()
816 .filter(|&d| ir.def(d).kind == DefKind::Assumption)
817 .collect()
818 }
819}