dive_eval/host.rs
1//! What the evaluator needs from the run around it: the model checker's
2//! spec-visible state (`TLCGet`'s live keys, `TLCSet("exit")`), the random
3//! stream TLC reseeds per expanded state, and TLC's register file.
4//!
5//! TLC reads these from its own globals and threads
6//! (`tlc2/module/TLCGetSet.java`, `RandomEnumerableValues.java`,
7//! `IdThread.java` at tlaplus `94d0c50`). dive keeps them out of the
8//! evaluator's core: the engine that drives the evaluator implements
9//! [`Host`] and installs it with [`crate::Evaluator::set_host`]. Without a
10//! host, the operators that need one are refused by name, never guessed.
11//!
12//! **Registers** belong to the evaluator itself (one logical register file
13//! per run): TLC's main thread writes every worker's registers,
14//! and dive's search is TLC's single-worker search, so one file reproduces
15//! every value a TLC run with one worker reads.
16
17use std::collections::BTreeMap;
18use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
19use std::sync::{Arc, Mutex, PoisonError};
20
21use dive_ir::{Arg, ExprId, StdOp};
22use dive_value::{Ctx, Int, Value};
23
24use crate::core::Core;
25use crate::env::{Env, Ev, St, StateRef, control};
26use crate::error::{Ec, EvalError, Result};
27
28/// A live counter of the model checker, as `TLCGet` reads it.
29#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
30pub enum Counter {
31 /// `"generated"`: states generated so far (`getStatesGenerated`).
32 Generated,
33 /// `"distinct"`: distinct states found so far.
34 Distinct,
35 /// `"queue"`: states left on the queue.
36 Queue,
37 /// `"diameter"`: `getProgress()`, the deepest level reached so far.
38 Diameter,
39 /// `"stats".initial`: initial states generated.
40 Initial,
41 /// `"duration"`: whole seconds since the run started. Wall-clock time,
42 /// nondeterministic in TLC as in dive.
43 DurationSecs,
44}
45
46/// `TLCGet("config")`: the run's settings, as TLC's `AbstractChecker.createConfig`
47/// records them.
48#[derive(Clone, Debug, PartialEq, Eq)]
49pub struct RunConfig {
50 /// Whether deadlock is checked.
51 pub deadlock: bool,
52 /// The worker count TLC reports. dive reports the logical count, 1
53 /// by default: its search at any worker count is TLC's single-worker
54 /// search. Under `--compat=tlc` it reports the physical count, as TLC does.
55 pub workers: i64,
56 /// The run's seed (printed as a string, as TLC does).
57 pub seed: i64,
58 /// The fingerprint polynomial (`FP64.getIrredPoly()`, printed as a signed
59 /// long in a string).
60 pub fingerprint: i64,
61 /// TLC's install location; dive's is the running executable's.
62 pub install: String,
63}
64
65/// An error raised by a host operation, with TLC's code and message.
66#[derive(Clone, Debug, PartialEq, Eq)]
67pub struct HostError {
68 /// TLC's error code (`tlc2.output.EC`); 0 for a refusal.
69 pub code: u32,
70 /// TLC's message, or the refused feature.
71 pub message: String,
72}
73
74/// A cooperative interruption requested by the evaluator's host.
75///
76/// This is control flow, never a specification error, a Boolean result or a
77/// resource refusal. The driver retains the resource and progress evidence.
78#[derive(Clone, Copy, Debug, PartialEq, Eq)]
79pub struct Interrupted {
80 token: u64,
81}
82
83impl Interrupted {
84 /// Associates an interruption with the driver's opaque receipt identity.
85 /// The value is not a TLC code or a resource measurement.
86 #[must_use]
87 pub const fn new(token: u64) -> Self {
88 Self { token }
89 }
90
91 /// The opaque identity supplied by the driver.
92 #[must_use]
93 pub const fn token(self) -> u64 {
94 self.token
95 }
96}
97
98/// Optional run control, separate from specification-visible host operations.
99///
100/// Drivers install this around the evaluator-backed phases they can classify,
101/// including controlled fresh binding after structural construction. Calls are
102/// amortized across evaluator loop work; implementations should inspect an
103/// existing signal rather than sample the clock or resident memory.
104pub trait HostControl: Send + Sync + std::fmt::Debug {
105 /// Checks whether evaluation must return to its driver.
106 ///
107 /// # Errors
108 /// [`Interrupted`] when the driver has requested interruption.
109 fn check(&self) -> Result<(), Interrupted>;
110}
111
112/// Restores the evaluator's previous host control when dropped.
113///
114/// The installing driver owns this scope exclusively, just as it owns changes
115/// to the specification-visible host. Worker threads share the installed control.
116#[derive(Debug)]
117pub struct HostControlScope {
118 pub(crate) core: Arc<Core>,
119 pub(crate) token: u64,
120 pub(crate) _thread: std::marker::PhantomData<std::rc::Rc<()>>,
121}
122
123impl Drop for HostControlScope {
124 fn drop(&mut self) {
125 self.core.host.remove_control(self.token);
126 }
127}
128
129/// Another thread currently owns the evaluator's host control scope.
130#[derive(Clone, Copy, Debug, PartialEq, Eq)]
131pub struct HostControlConflict;
132
133impl std::fmt::Display for HostControlConflict {
134 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
135 f.write_str("another driver owns the evaluator host control")
136 }
137}
138impl std::error::Error for HostControlConflict {}
139
140#[derive(Debug)]
141struct ControlFrame {
142 token: u64,
143 owner: std::thread::ThreadId,
144 control: Option<Arc<dyn HostControl>>,
145}
146
147#[derive(Debug, Default)]
148struct Controls {
149 next: u64,
150 frames: Vec<ControlFrame>,
151}
152
153/// The run hosting the evaluator: the model checker (or another driver).
154///
155/// Every method has a default that provides nothing; an operator that needs
156/// what a host does not provide is refused by name.
157///
158/// **Parallel engines.** The methods take `&self` and are called from the
159/// thread that evaluates. A host whose answers differ per worker (the level
160/// of the state being expanded, the random stream) keeps them per thread.
161pub trait Host: Send + Sync + std::fmt::Debug {
162 /// Supplies raw external inputs after explicit evaluator category admission.
163 /// No implementation is supplied by default; independent replay hosts must
164 /// consume an explicit recorded context and never read the operating system.
165 fn input(
166 &self,
167 _request: &crate::inputs::InputRequest,
168 ) -> Option<Result<crate::inputs::InputResponse, HostError>> {
169 None
170 }
171 /// Checks a native operation at runtime, before its arguments or body run.
172 /// Ordinary evaluators permit it; an isolated driver may remember a refusal
173 /// even if startup binding later catches the evaluation error.
174 ///
175 /// # Errors
176 /// A named refusal or a host evaluation error.
177 fn check_native_access(&self, _op: StdOp) -> Result<(), HostError> {
178 Ok(())
179 }
180
181 /// Checks a rendered Print/PrintT event before any output sink is called.
182 /// Arguments and rendering have already been evaluated. `false` preserves
183 /// the operator's return value while discarding replay output; `true`
184 /// emits the event. Ordinary hosts keep the existing output behavior.
185 ///
186 /// # Errors
187 /// A named refusal or an output resource bound. Rendering's temporary
188 /// allocation is not bounded by this hook.
189 fn print_output(&self, _text: &str) -> Result<bool, HostError> {
190 Ok(true)
191 }
192
193 /// Checks a string TLCGet/TLCSet key before accessing host state.
194 ///
195 /// # Errors
196 /// A named refusal or a host evaluation error.
197 fn check_tlc_access(&self, _key: &str, _write: bool) -> Result<(), HostError> {
198 Ok(())
199 }
200
201 /// Applies a random operator (`RandomElement`, `RandomSubset`,
202 /// `RandomSetOfSubsets`) to its evaluated arguments, drawing from the
203 /// stream of the current evaluation: TLC's start-up stream during
204 /// constant definitions, `ASSUME`s and `Init`, and the stream reseeded
205 /// from the expanded state's fingerprint while expanding a state.
206 /// `None` when the host has no stream.
207 fn random(&self, _op: StdOp, _args: &[Value], _ctx: Ctx) -> Option<Result<Value, HostError>> {
208 None
209 }
210
211 /// Checks a random operation reached inside an `ENABLED` query, before
212 /// evaluating its arguments. Ordinary hosts retain TLC's behavior. Isolated
213 /// sampling/replay hosts may refuse until they can prove the query's full
214 /// random support, including a negative existential result.
215 ///
216 /// # Errors
217 /// A named refusal or a host evaluation error.
218 fn check_random_in_enabled(&self) -> Result<(), HostError> {
219 Ok(())
220 }
221
222 /// Checks whether this run permits access to the evaluator's register
223 /// file. Called before integer/named `TLCGet` reads, aggregate register
224 /// reads (`"all"`, `"all:named"`), and integer/named `TLCSet` writes.
225 /// Other introspection keys do not call this method. The default permits
226 /// access, preserving ordinary evaluator and checker behavior.
227 ///
228 /// # Errors
229 /// A host may refuse search-dependent register access (code 0) or provide
230 /// a TLC evaluation error. Refusal occurs before reading or writing.
231 fn check_register_access(&self) -> Result<(), HostError> {
232 Ok(())
233 }
234
235 /// Checks whether expression evaluation or successor generation may search
236 /// intermediate states to decide unrestricted action composition. Independent
237 /// replay refuses this; its explicit bounded capability is checked separately.
238 ///
239 /// # Errors
240 /// A refusal (code 0) or an evaluation error supplied by the driver.
241 fn check_action_composition(&self) -> Result<(), HostError> {
242 Ok(())
243 }
244
245 /// Selects the evaluator's bounded, pure TLA+ composition path.
246 ///
247 /// This grants no expression or cached-result authority. The evaluator
248 /// inspects both operand closures without callbacks, requires complete
249 /// intermediate states and at most one complete tail successor, and calls
250 /// [`Self::check_action_composition`] on every declined case. Independent
251 /// replay uses this path with its own host and expression-cache domain.
252 fn requires_bounded_action_composition(&self) -> bool {
253 false
254 }
255
256 /// Checks the host's permission for an inspected bounded composition.
257 /// Existing host refusals still apply unless the host explicitly admits
258 /// this slice. This is called before collecting any intermediate states.
259 ///
260 /// # Errors
261 /// The host's composition refusal or evaluation error.
262 fn check_bounded_action_composition(&self) -> Result<(), HostError> {
263 self.check_action_composition()
264 }
265
266 /// The cache domain that lazy expression results computed under this
267 /// host belong to. A cached result is reused only by evaluation under a
268 /// host of the same domain. Ordinary drivers share domain 0 (TLC's single
269 /// `LazyValue` cache). Independent replay gives each run its own domain, so
270 /// a value cached by another consumer never becomes replay's answer and a
271 /// replay verdict does not depend on how warm the caches were.
272 fn expression_cache_domain(&self) -> u64 {
273 0
274 }
275
276 /// `TLCGet("level")` outside `ASSUME` and `Init`: the level of TLC's
277 /// `s0`, the state being expanded in the next-state relation and action
278 /// checks, the successor in invariants and constraints (initial states
279 /// are level 1).
280 fn level(&self) -> Option<i64> {
281 None
282 }
283
284 /// `TLCGet("level")` under a prime. TLC evaluates a primed expression with
285 /// the successor as its current state, so it reads the successor's level,
286 /// which [`Self::level`] does not describe. No host tracks it, so the
287 /// default refuses by name; a host may remember the refusal so that a
288 /// verdict built around a swallowed error is refused too.
289 ///
290 /// # Errors
291 /// The named refusal.
292 fn successor_level(&self) -> Result<i64, HostError> {
293 Err(HostError {
294 code: 0,
295 message: PRIMED_LEVEL_UNSUPPORTED.to_owned(),
296 })
297 }
298
299 /// A live counter.
300 fn counter(&self, _counter: Counter) -> Option<i64> {
301 None
302 }
303
304 /// `TLCGet("config")`.
305 fn config(&self) -> Option<RunConfig> {
306 None
307 }
308
309 /// `TLCSet("exit", TRUE)`: ends the run as a success once the current
310 /// state is done (`ModelChecker.stop`). Returns whether the host acts on
311 /// it.
312 fn request_exit(&self) -> bool {
313 false
314 }
315}
316
317/// The refusal of a primed `TLCGet("level")` ([`Host::successor_level`]).
318pub const PRIMED_LEVEL_UNSUPPORTED: &str =
319 "TLCGet(\"level\") under a prime, which TLC evaluates at the successor's level";
320
321/// The names `TLCGetSet`'s static initializer interns, in declaration order
322/// (`tlc2/module/TLCGetSet.java:52-162`). TLC loads the class when it
323/// creates its model checker (`AbstractChecker.createConfig`), after
324/// processing constant definitions and before checking assumptions; a
325/// driver that reproduces TLC's name order interns them then
326/// ([`crate::Evaluator::intern_checker_names`]). They decide the order of the
327/// fields of `TLCGet("config")` and `TLCGet("stats")`.
328pub const TLCGET_NAMES: &[&str] = &[
329 "exit",
330 "pause",
331 "config",
332 "spec",
333 "coverage",
334 "action",
335 "install",
336 "id",
337 "behavior",
338 "all",
339 "all:named",
340 "mode",
341 "deadlock",
342 "seed",
343 "fingerprint",
344 "worker",
345 "traces",
346 "depth",
347 "aril",
348 "sched",
349 "revision",
350 "timestamp",
351 "date",
352 "count",
353 "tag",
354 "calver",
355 "impliedinits",
356 "impliedactions",
357 "invariants",
358 "impliedtemporals",
359 "temporals",
360 "actions",
361 "inits",
362 "variables",
363 "actionconstraints",
364 "constraints",
365 "level",
366 "stats",
367 "duration",
368 "generated",
369 "diameter",
370 "distinct",
371 "initial",
372 "queue",
373 "retries",
374 "distinctvalues",
375 "levelmean",
376 "levelvariance",
377];
378
379/// TLC's register file (`IdThread.localValues`, `namedRegisters`), one
380/// logical worker's.
381#[derive(Debug, Default)]
382pub(crate) struct Registers {
383 ints: BTreeMap<i64, Value>,
384 /// Named registers (`"s:..."`), in first-write order.
385 named: Vec<(String, Value)>,
386}
387
388/// Whether native permission hooks execute for an installed host.
389///
390/// This chooses execution semantics, not a host's claim of purity or a proof
391/// that checks may be omitted. The plain host setters always select `Callback`.
392#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
393pub enum NativeHooks {
394 /// Invoke the installed host's original permission callback.
395 #[default]
396 Callback,
397 /// Do not invoke native permission callbacks in shared ordinary domain zero.
398 /// Selection declines in independent nonzero cache domains.
399 Unrestricted,
400}
401
402/// A complete host installation, including its operative callback policy.
403///
404/// Choosing `Unrestricted` explicitly changes hook execution; it grants no
405/// private source ownership or permission to skip evaluator work. Unrestricted
406/// execution can only be selected in ordinary cache domain zero, never in an
407/// independent permission-bearing cache domain. No public constructor mints an
408/// unrestricted binding; a displaced snapshot can retain an admitted domain-zero
409/// policy. A displaced
410/// binding retains its installed cache domain for complete restoration; a fresh
411/// constructor queries the host at installation, like plain replacement.
412///
413/// ```
414/// # fn install(ev: &dive_eval::Evaluator, host: std::sync::Arc<dyn dive_eval::Host>) {
415/// use dive_eval::HostBinding;
416/// let previous = ev.replace_host_binding(HostBinding::callback(Some(host)));
417/// // The driver owns installation until the complete predecessor is restored.
418/// drop(ev.replace_host_binding(previous));
419/// # }
420/// ```
421#[derive(Debug)]
422pub struct HostBinding {
423 host: Option<Arc<dyn Host>>,
424 hooks: NativeHooks,
425 // Installed snapshots restore the cache domain without calling user code.
426 cache_domain: Option<u64>,
427}
428
429impl HostBinding {
430 /// Install normal callbacks, including the no-host case.
431 #[must_use]
432 pub fn callback(host: Option<Arc<dyn Host>>) -> Self {
433 Self {
434 host,
435 hooks: NativeHooks::Callback,
436 cache_domain: None,
437 }
438 }
439
440 /// The installed native callback policy.
441 #[must_use]
442 pub const fn native_hooks(&self) -> NativeHooks {
443 self.hooks
444 }
445}
446
447/// A read-only installation snapshot, not a semantic proof or concurrency lease.
448#[derive(Clone, Copy, Debug, PartialEq, Eq)]
449pub struct HostBindingStamp {
450 generation: u64,
451 hooks: NativeHooks,
452}
453
454impl HostBindingStamp {
455 /// A process-local installation generation, or `None` after exhaustion.
456 /// Generations are specific to this evaluator and are never restored/reused.
457 #[must_use]
458 pub const fn generation(self) -> Option<u64> {
459 if self.generation == 0 {
460 None
461 } else {
462 Some(self.generation)
463 }
464 }
465
466 /// The operative native callback policy at this snapshot.
467 #[must_use]
468 pub const fn native_hooks(self) -> NativeHooks {
469 self.hooks
470 }
471}
472
473/// Restores the complete preceding host installation on drop.
474///
475/// The caller must own host replacement for this scope's lifetime. This is not
476/// a lease on a publicly shared evaluator. Restoration creates a new generation.
477#[derive(Debug)]
478pub struct HostBindingScope {
479 pub(crate) core: Arc<Core>,
480 pub(crate) previous: Option<HostBinding>,
481 pub(crate) _thread: std::marker::PhantomData<std::rc::Rc<()>>,
482}
483
484impl Drop for HostBindingScope {
485 fn drop(&mut self) {
486 if let Some(previous) = self.previous.take() {
487 drop(self.core.host.replace_binding(previous));
488 }
489 }
490}
491
492#[derive(Debug)]
493struct BindingState {
494 binding: HostBinding,
495 generation: u64,
496}
497
498impl Default for BindingState {
499 fn default() -> Self {
500 Self {
501 binding: HostBinding {
502 host: None,
503 hooks: NativeHooks::Callback,
504 cache_domain: Some(0),
505 },
506 generation: 1,
507 }
508 }
509}
510
511/// The evaluator's handle on its host and registers.
512#[derive(Debug, Default)]
513pub(crate) struct HostSlot {
514 host: Mutex<BindingState>,
515 pub(crate) registers: Mutex<Registers>,
516 /// Independent of host replacement: graph capture installs a search host
517 /// while the same outer run control remains active.
518 control: Mutex<Controls>,
519 /// The installed host's [`Host::expression_cache_domain`], updated with
520 /// the host so cache lookups need not lock it.
521 pub(crate) cache_domain: AtomicU64,
522 /// Whether the installed binding's hooks are [`NativeHooks::Unrestricted`],
523 /// mirrored from `host` so the per-call native check need not lock it.
524 /// Written only by `install`, under the `host` lock; `false` matches the
525 /// default binding's `Callback`.
526 unrestricted: AtomicBool,
527}
528
529impl HostSlot {
530 // Depends on the separately merged operative binding foundation. This
531 // concrete token owns only references to validated integer cursor storage.
532 pub(crate) fn commit_subset_position(&self, position: dive_value::SubsetCommit<'_>) -> bool {
533 let slot = self.host.lock().unwrap_or_else(PoisonError::into_inner);
534 if slot.generation == 0
535 || slot.binding.host.is_none()
536 || slot.binding.hooks != NativeHooks::Unrestricted
537 || slot.binding.cache_domain != Some(0)
538 {
539 return false;
540 }
541 position.commit();
542 true
543 }
544
545 /// Plain replacements always select callbacks, even for the same Arc.
546 pub(crate) fn replace(&self, host: Option<Arc<dyn Host>>) -> Option<Arc<dyn Host>> {
547 self.replace_binding(HostBinding::callback(host)).host
548 }
549
550 pub(crate) fn replace_binding(&self, binding: HostBinding) -> HostBinding {
551 let mut slot = self.host.lock().unwrap_or_else(PoisonError::into_inner);
552 self.install(&mut slot, binding)
553 }
554
555 fn install(&self, slot: &mut BindingState, mut binding: HostBinding) -> HostBinding {
556 let domain = binding.cache_domain.unwrap_or_else(|| {
557 binding
558 .host
559 .as_ref()
560 .map_or(0, |host| host.expression_cache_domain())
561 });
562 binding.cache_domain = Some(domain);
563 self.cache_domain.store(domain, Ordering::Release);
564 if slot.generation != 0 {
565 slot.generation = slot.generation.checked_add(1).unwrap_or(0);
566 }
567 // Independent cache authority and exhausted identity space never
568 // admit omission of permission checks.
569 if domain != 0 || slot.generation == 0 {
570 binding.hooks = NativeHooks::Callback;
571 }
572 // Release pairs with the Acquire load in `check_native_access`: a
573 // thread whose use happens after this install (for example a worker
574 // started or signalled afterwards) observes this mode or a later one.
575 // The installing thread always observes its own store (coherence).
576 self.unrestricted.store(
577 binding.hooks == NativeHooks::Unrestricted,
578 Ordering::Release,
579 );
580 std::mem::replace(&mut slot.binding, binding)
581 }
582
583 pub(crate) fn replace_hooks(&self, hooks: NativeHooks) -> Option<HostBinding> {
584 let mut slot = self.host.lock().unwrap_or_else(PoisonError::into_inner);
585 if hooks == NativeHooks::Unrestricted
586 && (slot.generation == 0
587 || slot.generation == u64::MAX
588 || slot.binding.host.is_none()
589 || slot.binding.cache_domain != Some(0))
590 {
591 return None;
592 }
593 let binding = HostBinding {
594 host: slot.binding.host.clone(),
595 hooks: if slot.binding.host.is_some() {
596 hooks
597 } else {
598 NativeHooks::Callback
599 },
600 cache_domain: slot.binding.cache_domain,
601 };
602 Some(self.install(&mut slot, binding))
603 }
604
605 pub(crate) fn stamp(&self) -> HostBindingStamp {
606 let slot = self.host.lock().unwrap_or_else(PoisonError::into_inner);
607 HostBindingStamp {
608 generation: slot.generation,
609 hooks: slot.binding.hooks,
610 }
611 }
612
613 pub(crate) fn check_native_access(&self, op: StdOp) -> Result<()> {
614 // Lock-free fast path. The flag is stored under the `host` lock by every
615 // install, so it is the mode of an installation at least as recent as
616 // any that happens-before this call; a concurrent install may land
617 // either side, exactly as it could when this read took the lock.
618 if self.unrestricted.load(Ordering::Acquire) {
619 return Ok(());
620 }
621 // Callback: read the binding under the lock (it may have changed since
622 // the load) and call the host outside it, so the hook may reinstall.
623 let host = {
624 let slot = self.host.lock().unwrap_or_else(PoisonError::into_inner);
625 match slot.binding.hooks {
626 NativeHooks::Unrestricted => None,
627 NativeHooks::Callback => slot.binding.host.clone(),
628 }
629 };
630 match host {
631 Some(host) => host.check_native_access(op).map_err(host_error),
632 None => Ok(()),
633 }
634 }
635
636 pub(crate) fn push_control(
637 &self,
638 control: Option<Arc<dyn HostControl>>,
639 ) -> Result<u64, HostControlConflict> {
640 let owner = std::thread::current().id();
641 let mut controls = self.control.lock().unwrap_or_else(PoisonError::into_inner);
642 if controls
643 .frames
644 .last()
645 .is_some_and(|frame| frame.owner != owner)
646 {
647 return Err(HostControlConflict);
648 }
649 let token = controls.next.checked_add(1).ok_or(HostControlConflict)?;
650 controls.next = token;
651 controls.frames.push(ControlFrame {
652 token,
653 owner,
654 control,
655 });
656 Ok(token)
657 }
658
659 pub(crate) fn remove_control(&self, token: u64) {
660 let mut controls = self.control.lock().unwrap_or_else(PoisonError::into_inner);
661 if let Some(index) = controls
662 .frames
663 .iter()
664 .position(|frame| frame.token == token)
665 {
666 controls.frames.remove(index);
667 }
668 }
669
670 pub(crate) fn check_control(&self) -> crate::Result<()> {
671 let controls = self.control.lock().unwrap_or_else(PoisonError::into_inner);
672 let control = match controls.frames.last() {
673 Some(frame) if frame.control.is_some() => frame.control.clone(),
674 Some(frame) if frame.owner != std::thread::current().id() => controls
675 .frames
676 .iter()
677 .rev()
678 .find_map(|frame| frame.control.clone()),
679 _ => None,
680 };
681 drop(controls);
682 match control {
683 Some(control) => control.check().map_err(EvalError::interrupted),
684 None => Ok(()),
685 }
686 }
687
688 /// The cache domain of the installed host.
689 pub(crate) fn cache_domain(&self) -> u64 {
690 self.cache_domain.load(Ordering::Acquire)
691 }
692
693 pub(crate) fn get(&self) -> Option<Arc<dyn Host>> {
694 self.host
695 .lock()
696 .unwrap_or_else(PoisonError::into_inner)
697 .binding
698 .host
699 .clone()
700 }
701}
702
703pub(crate) fn host_error(e: HostError) -> EvalError {
704 if e.code == 0 {
705 EvalError::unsupported(e.message)
706 } else {
707 // Already in its final form: an `EvalException`, or the override's
708 // own `TLC_MODULE_VALUE_JAVA_METHOD_OVERRIDE` wrapping.
709 EvalError::eval_exception(Ec::from_tlc_code(e.code), e.message)
710 }
711}
712
713impl Core {
714 fn check_register_access(&self) -> Result<()> {
715 match self.host.get() {
716 Some(host) => host.check_register_access().map_err(host_error),
717 None => Ok(()),
718 }
719 }
720
721 pub(crate) fn check_action_composition(&self) -> Result<()> {
722 match self.host.get() {
723 Some(host) => host.check_action_composition().map_err(host_error),
724 None => Ok(()),
725 }
726 }
727
728 /// The cache domain lazy results are read from and written to.
729 pub(crate) fn expression_cache(&self) -> u64 {
730 self.host.cache_domain()
731 }
732
733 /// `RandomElement` and the `Randomization` operators, through the host.
734 pub(crate) fn call_random(&self, op: StdOp, args: &[Value]) -> Result<Value> {
735 let Some(host) = self.host.get() else {
736 return Err(EvalError::unsupported(format!(
737 "{} without a random stream (the evaluator runs outside a model checker that seeds one)",
738 op.qualified_name()
739 )));
740 };
741 match host.random(op, args, self.ctx) {
742 Some(r) => r.map_err(host_error),
743 None => Err(EvalError::unsupported(format!(
744 "{} (this run provides no random stream)",
745 op.qualified_name()
746 ))),
747 }
748 }
749
750 /// `TLCGetSet.TLCGetEval`.
751 pub(crate) fn tlc_get(
752 self: &Arc<Self>,
753 env: &mut Env,
754 st: &St,
755 args: &[Arg],
756 e: ExprId,
757 ) -> Result<Ev> {
758 let Some(Arg::Expr { expr, .. }) = args.first() else {
759 return Err(EvalError::bug("TLCGet arity"));
760 };
761 let vidx = self.eval_v(env, st, *expr)?;
762 let _g = self.enter(e)?;
763 self.tlc_get_value(&vidx, st).map(Ev::V)
764 }
765
766 /// `TLCGetSet.TLCGetEval` on its evaluated argument.
767 pub(crate) fn tlc_get_value(&self, vidx: &Value, st: &St) -> Result<Value> {
768 match vidx {
769 Value::Int(_) | Value::BigInt(_) => {
770 let idx = self.register_index(vidx)?;
771 if idx >= 0 {
772 self.check_register_access()?;
773 let regs = self
774 .host
775 .registers
776 .lock()
777 .unwrap_or_else(PoisonError::into_inner);
778 return match regs.ints.get(&idx) {
779 Some(v) => Ok(v.clone()),
780 None => Err(undefined(&idx.to_string())),
781 };
782 }
783 }
784 Value::Str(s) => return self.tlc_get_string(s.as_str(), st),
785 _ => {}
786 }
787 Err(EvalError::eval_exception(
788 Ec::OneArgumentError,
789 format!(
790 "The argument of TLCGet should be a nonnegative integer, but instead it is:\n{}",
791 self.ppr(vidx)
792 ),
793 ))
794 }
795
796 /// A register index: TLC's `IntValue.val`, an `int`.
797 fn register_index(&self, v: &Value) -> Result<i64> {
798 match v.as_int().and_then(|i| i.to_i64()) {
799 Some(i) if i32::try_from(i).is_ok() => Ok(i),
800 _ => Err(EvalError::unsupported(format!(
801 "a TLCGet/TLCSet register index outside TLC's 32-bit range: {}",
802 self.ppr(v)
803 ))),
804 }
805 }
806
807 fn host_for(&self, key: &str) -> Result<Arc<dyn Host>> {
808 self.host.get().ok_or_else(|| {
809 EvalError::unsupported(format!(
810 "TLCGet(\"{key}\") without a model checker (the evaluator runs outside one)"
811 ))
812 })
813 }
814
815 fn counter(&self, key: &str, c: Counter) -> Result<i64> {
816 self.host_for(key)?.counter(c).ok_or_else(|| {
817 EvalError::unsupported(format!("TLCGet(\"{key}\") (this run does not provide it)"))
818 })
819 }
820
821 /// `IntValue.gen(Math.toIntExact(n))`, or TLC's overflow error.
822 fn narrow(n: i64) -> Result<Value> {
823 if i32::try_from(n).is_ok() {
824 Ok(Value::Int(n))
825 } else {
826 Err(EvalError::eval_exception(
827 Ec::Overflow,
828 format!("Overflow when computing {n}"),
829 ))
830 }
831 }
832
833 fn record(&self, fields: Vec<(&str, Value)>) -> Result<Value> {
834 let fields = fields
835 .into_iter()
836 .map(|(n, v)| (self.names.intern(n), v))
837 .collect();
838 Ok(Value::record(fields, self.ctx)?)
839 }
840
841 #[allow(
842 clippy::too_many_lines,
843 reason = "one arm per key, as in TLCGetStringValue"
844 )]
845 fn tlc_get_string(&self, key: &str, st: &St) -> Result<Value> {
846 if let Some(host) = self.host.get() {
847 host.check_tlc_access(key, false).map_err(host_error)?;
848 }
849 match key {
850 "diameter" => Self::narrow(self.counter(key, Counter::Diameter)?),
851 "generated" => Self::narrow(self.counter(key, Counter::Generated)?),
852 "distinct" => Self::narrow(self.counter(key, Counter::Distinct)?),
853 "queue" => Self::narrow(self.counter(key, Counter::Queue)?),
854 "duration" => Self::narrow(self.counter(key, Counter::DurationSecs)?),
855 "stats" => {
856 // `AbstractChecker.getStatistics`; `narrowToIntValue` saturates.
857 let sat = |n: i64| Value::Int(n.clamp(i64::from(i32::MIN), i64::from(i32::MAX)));
858 let queue = self.counter(key, Counter::Queue)?;
859 let distinct = self.counter(key, Counter::Distinct)?;
860 let initial = self.counter(key, Counter::Initial)?;
861 let generated = self.counter(key, Counter::Generated)?;
862 let diameter = self.counter(key, Counter::Diameter)?;
863 let duration = self.counter(key, Counter::DurationSecs)?;
864 self.record(vec![
865 ("queue", sat(queue)),
866 ("distinct", sat(distinct)),
867 ("initial", sat(initial)),
868 ("generated", sat(generated)),
869 ("diameter", sat(diameter)),
870 ("duration", sat(duration)),
871 // The worker's `IdThread` id: 0 for the one logical worker.
872 ("worker", Value::Int(0)),
873 ])
874 }
875 "config" => {
876 let c = self.host_for(key)?.config().ok_or_else(|| {
877 EvalError::unsupported("TLCGet(\"config\") (this run does not provide it)")
878 })?;
879 self.record(vec![
880 ("mode", Value::string(&self.names, "bfs")),
881 ("deadlock", Value::Bool(c.deadlock)),
882 ("worker", Value::Int(c.workers)),
883 ("seed", Value::string(&self.names, &c.seed.to_string())),
884 (
885 "fingerprint",
886 Value::string(&self.names, &c.fingerprint.to_string()),
887 ),
888 ("install", Value::string(&self.names, &c.install)),
889 ])
890 }
891 "level" => {
892 if st.is(control::CONST) || st.is(control::INIT) {
893 // `TLCState.INIT_LEVEL - 1` in `ASSUME`s and `Init`.
894 return Ok(Value::Int(0));
895 }
896 // `s1` is `Null` exactly when evaluating under a prime (the
897 // successor moved into `s0`), and `Primed` marks it inside
898 // `ENABLED`: TLC then reads the successor's level.
899 if st.is(control::PRIMED) || matches!(st.s1, StateRef::Null) {
900 return self
901 .host_for(key)?
902 .successor_level()
903 .map(|level| Value::int(Int::Small(level)))
904 .map_err(host_error);
905 }
906 let level = self.host_for(key)?.level().ok_or_else(|| {
907 EvalError::unsupported(
908 "TLCGet(\"level\") (this run does not track the level of the state)",
909 )
910 })?;
911 Ok(Value::int(Int::Small(level)))
912 }
913 "all" => {
914 self.check_register_access()?;
915 let regs = self
916 .host
917 .registers
918 .lock()
919 .unwrap_or_else(PoisonError::into_inner);
920 // `getAllValues`: [i \in I |-> [w \in 1..workers |-> v]], one
921 // logical worker.
922 let pairs = regs
923 .ints
924 .iter()
925 .map(|(i, v)| (Value::Int(*i), Value::tuple(vec![v.clone()])))
926 .collect();
927 Ok(Value::fcn(pairs, self.ctx)?)
928 }
929 "all:named" => {
930 self.check_register_access()?;
931 let regs = self
932 .host
933 .registers
934 .lock()
935 .unwrap_or_else(PoisonError::into_inner);
936 let pairs = regs
937 .named
938 .iter()
939 .map(|(k, v)| (Value::string(&self.names, k), Value::tuple(vec![v.clone()])))
940 .collect();
941 Ok(Value::fcn(pairs, self.ctx)?)
942 }
943 "spec" | "action" | "revision" => Err(EvalError::unsupported(format!(
944 "TLCGet(\"{key}\") (reads TLC's internal description of the run)"
945 ))),
946 k if k.starts_with("s:") => {
947 self.check_register_access()?;
948 let regs = self
949 .host
950 .registers
951 .lock()
952 .unwrap_or_else(PoisonError::into_inner);
953 match regs.named.iter().find(|(n, _)| n == k) {
954 Some((_, v)) => Ok(v.clone()),
955 None => Err(undefined(k)),
956 }
957 }
958 // `System.getProperty(key, "-D" + key)`: the one property dive
959 // models is the action composition switch, set exactly
960 // when `\cdot` is enabled.
961 "-Dtlc2.tool.impl.Tool.cdot" => Ok(Value::string(
962 &self.names,
963 if self.opts.action_composition == crate::options::ActionComposition::Off {
964 key
965 } else {
966 "true"
967 },
968 )),
969 k if k.starts_with("-D") => Err(EvalError::unsupported(format!(
970 "TLCGet(\"{k}\") (reads a Java system property of TLC's JVM)"
971 ))),
972 k => Err(undefined(k)),
973 }
974 }
975
976 /// `TLCGetSet.TLCSet`.
977 ///
978 /// Startup pre-evaluation runs before a checker or simulator is installed.
979 /// Integer writes therefore fail softly and cannot produce a startup cache
980 /// value; named writes are no-ops there. Runtime and ASSUME writes use
981 /// `tlc_set` directly and retain their existing behavior.
982 pub(crate) fn startup_register_write(&self, key: &Value, value: &Value) -> Result<()> {
983 match key {
984 Value::Int(_) | Value::BigInt(_) if self.register_index(key)? >= 0 => {
985 self.check_register_access()?;
986 Err(EvalError::general(
987 "integer TLCSet registers are unavailable during startup pre-evaluation",
988 ))
989 }
990 Value::Str(name) if name.as_str().starts_with("s:") => {
991 if let Some(host) = self.host.get() {
992 host.check_tlc_access(name.as_str(), true)
993 .map_err(host_error)?;
994 }
995 self.check_register_access()
996 }
997 _ => self.tlc_set(key, value).map(|_| ()),
998 }
999 }
1000
1001 /// `TLCGetSet.TLCSet` with an active checker (including ASSUMEs).
1002 pub(crate) fn tlc_set(&self, vidx: &Value, val: &Value) -> Result<Value> {
1003 match vidx {
1004 Value::Int(_) | Value::BigInt(_) => {
1005 let idx = self.register_index(vidx)?;
1006 if idx >= 0 {
1007 self.check_register_access()?;
1008 self.host
1009 .registers
1010 .lock()
1011 .unwrap_or_else(PoisonError::into_inner)
1012 .ints
1013 .insert(idx, val.clone());
1014 return Ok(Value::TRUE);
1015 }
1016 }
1017 Value::Str(s) => {
1018 if let Some(host) = self.host.get() {
1019 host.check_tlc_access(s.as_str(), true)
1020 .map_err(host_error)?;
1021 }
1022 match s.as_str() {
1023 "exit" => {
1024 if matches!(val, Value::Bool(true)) {
1025 let handled = self.host.get().is_some_and(|h| h.request_exit());
1026 if !handled {
1027 return Err(EvalError::unsupported(
1028 "TLCSet(\"exit\", TRUE) without a model checker that stops on it",
1029 ));
1030 }
1031 }
1032 return Ok(Value::TRUE);
1033 }
1034 "pause" => {
1035 if matches!(val, Value::Bool(true)) {
1036 return Err(EvalError::unsupported(
1037 "TLCSet(\"pause\", TRUE) (waits for input on TLC's console)",
1038 ));
1039 }
1040 return Ok(Value::TRUE);
1041 }
1042 k if k.starts_with("s:") => {
1043 self.check_register_access()?;
1044 let mut regs = self
1045 .host
1046 .registers
1047 .lock()
1048 .unwrap_or_else(PoisonError::into_inner);
1049 match regs.named.iter_mut().find(|(n, _)| n == k) {
1050 Some(slot) => slot.1 = val.clone(),
1051 None => regs.named.push((k.to_owned(), val.clone())),
1052 }
1053 return Ok(Value::TRUE);
1054 }
1055 k if k.starts_with("-D") => {
1056 return Err(EvalError::unsupported(format!(
1057 "TLCSet(\"{k}\", ...) (sets a Java system property of TLC's JVM)"
1058 )));
1059 }
1060 _ => {}
1061 }
1062 }
1063 _ => {}
1064 }
1065 Err(EvalError::eval_exception(
1066 Ec::ArgumentError,
1067 format!(
1068 "The first argument of TLCSet should be a nonnegative integer, but instead it is:\n{}",
1069 self.ppr(vidx)
1070 ),
1071 ))
1072 }
1073}
1074
1075fn undefined(key: &str) -> EvalError {
1076 EvalError::eval_exception(Ec::TlcGetUndefined, format!("TLCGet({key}) was undefined."))
1077}
1078
1079#[cfg(test)]
1080#[path = "host_binding_tests.rs"]
1081mod binding_tests;