dive-eval 0.1.0

TLA+ expression and action evaluator with TLC's semantics
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! Action composition, `A \cdot B`: a port of TLC's `OPCODE_cdot`
//! rules in `Tool.getNextStates`, `Tool.eval` and `Tool.enabled`
//! (`tlc2/tool/impl/Tool.java` at tlaplus `94d0c50`, `:1488-1531`,
//! `:2772-2808`, `:3371-3393`), which TLC runs only with
//! `-Dtlc2.tool.impl.Tool.cdot=true`.
//!
//! `s -(A \cdot B)-> u` iff some `t` has `s -A-> t` and `t -B-> u`. All three
//! rules enumerate the intermediate states `t` with the successor generator
//! (`A` from `s`), then take `B` from each `t`:
//!
//! - **Next states.** The intermediate state starts as `s0.copyWith(s1)`:
//!   the variables the enclosing action already assigned, set to their
//!   *current* values. `A` is enumerated with the enclosing continuation, and
//!   so is `B` from each `t`, whose successors are the composition's.
//!   `nss.incrementStatesGenerated(|iss|)` counts the intermediate states as
//!   generated, so a state whose `A` steps have no `B` step is not a
//!   deadlock. A nested composition's intermediate states are not counted:
//!   its functor is a `StateVec` or an anonymous one, which ignore the count.
//! - **Evaluation.** `A` from `s` into an empty state, with no continuation;
//!   true iff `B` holds between some `t` and the given successor.
//! - **ENABLED.** As for next states, with `enabled` for `B`.
//!
//! Where the continuation is empty and nothing is assigned yet, these rules
//! compute the TLA+ meaning exactly. Elsewhere the continuation is evaluated
//! after `A` as well (against the intermediate state) and assigned variables
//! are pre-set in `t`, which is not what `A \cdot B` means: TLC's mode
//! ([`ActionComposition::Tlc`]) reproduces it, while the default
//! ([`ActionComposition::Tla`]) refuses those uses by name and counts only the
//! composed successors as generated.

use std::sync::Arc;

use dive_ir::ExprId;
use dive_ir::actions::ActionName;
use dive_value::Value;

use super::{Action, Acts, Enab, EnabledState, Flow, Gen, StateVals, Successor};
use crate::core::Core;
use crate::env::{Env, Ev, St, StateRef};
use crate::error::{EvalError, Result};
use crate::options::ActionComposition;

/// TLC's message when the switch is off (`Tool.java:1528`).
pub(crate) fn off_error(core: &Core, e: ExprId) -> EvalError {
    EvalError::general(format!(
        "The current version of TLC does not support action composition.  An incomplete implementation can be enabled via the tlc2.tool.impl.Tool.cdot=true java property.\n{}",
        core.loc(e)
    ))
}

/// The refusal of a composition whose meaning TLC's algorithm distorts, in
/// the default mode.
fn distorted(core: &Core, e: ExprId) -> EvalError {
    EvalError::unsupported(format!(
        "action composition `A \\cdot B` with conjuncts after it or variables assigned before it (TLC's algorithm evaluates them against the intermediate state; `--action-composition=tlc` reproduces that) ({})",
        core.loc(e)
    ))
}

/// `s0.copyWith(s1)`: `s0`'s values of the variables `s1` assigns.
fn copy_with(s0: &StateRef, s1: &StateVals) -> StateVals {
    let current = match s0 {
        StateRef::Vals(v) => Some(v),
        _ => None,
    };
    s1.iter()
        .enumerate()
        .map(|(i, v)| {
            v.as_ref()
                .and_then(|_| current.and_then(|c| c.get(i).cloned().flatten()))
        })
        .collect()
}

impl Core {
    fn bounded_composition(&self) -> bool {
        self.host
            .get()
            .is_some_and(|host| host.requires_bounded_action_composition())
    }

    fn unproved_composition<T>(&self) -> Result<T> {
        // Replay remembers this refusal even if an optional label swallows it.
        self.check_action_composition()?;
        Err(EvalError::unsupported(
            "unproved bounded action composition",
        ))
    }

    /// Reuse the existing callback-free closure inspection and generator,
    /// never a checker callback or a separately implemented relation search.
    /// All first-stage work finishes before any tail or outward observation.
    fn bounded_cdot_intermediates(
        self: &Arc<Self>,
        env: &Env,
        s0: &StateRef,
        a: ExprId,
        b: ExprId,
    ) -> Result<Vec<StateVals>> {
        if self.opts.action_composition != ActionComposition::Tla {
            return self.unproved_composition();
        }
        let evaluator = crate::Evaluator {
            core: self.clone(),
            collected: None,
        };
        let mut inspected = env.clone();
        // ENABLED's empty substitution cutoff changes no lookup. Inspect
        // that equivalent closure; retain every nonempty/unknown cutoff.
        if inspected.dynamic.cut == Some(0) && inspected.dynamic.subst.is_none() {
            inspected.dynamic.cut = None;
        }
        let scope = crate::Scope {
            env: inspected,
            owner: self.ir.clone(),
            names: self.names.clone(),
            context: Arc::downgrade(self),
            wrapper: None,
        };
        if evaluator
            .canonical_producer_stability_budgeted(&[(a, scope.clone()), (b, scope)], &[], None)?
            .is_none()
        {
            return self.unproved_composition();
        }
        let current = self.composition_current(s0)?;
        if !matches!(&current, StateRef::Vals(values) if values.len() == self.ir.vars().len() && values.iter().all(Option::is_some))
        {
            return self.unproved_composition();
        }
        if let Some(host) = self.host.get() {
            host.check_bounded_action_composition()
                .map_err(crate::host::host_error)?;
        }
        let empty = || vec![None; self.ir.vars().len()].into();
        let intermediates = self.cdot_steps(env, &current, empty(), a, false)?;
        if intermediates
            .iter()
            .any(|state| state.iter().any(Option::is_none))
        {
            return self.unproved_composition();
        }
        Ok(intermediates)
    }

    fn bounded_cdot_tail(
        self: &Arc<Self>,
        env: &Env,
        intermediate: StateVals,
        b: ExprId,
    ) -> Result<Vec<StateVals>> {
        self.loop_work()?;
        let empty = vec![None; self.ir.vars().len()].into();
        let final_states = self.cdot_steps(env, &StateRef::Vals(intermediate), empty, b, true)?;
        if final_states.len() > 1
            || final_states
                .iter()
                .any(|state| state.iter().any(Option::is_none))
        {
            return self.unproved_composition();
        }
        Ok(final_states)
    }

    fn composition_named(self: &Arc<Self>, state: &crate::NamedState) -> Result<StateVals> {
        if !std::ptr::eq(state.context.as_ptr(), Arc::as_ptr(self)) {
            return Err(EvalError::unsupported(
                "foreign named action-composition state",
            ));
        }
        if state
            .assignments()
            .any(|(name, _)| self.root_var_named(name).is_none())
        {
            return Err(EvalError::unsupported(
                "action composition with assigned hidden ENABLED variables",
            ));
        }
        Ok(self
            .ir
            .vars()
            .iter()
            .map(|decl| state.get(&self.ir.decl(*decl).name).cloned())
            .collect())
    }

    fn composition_current(self: &Arc<Self>, state: &StateRef) -> Result<StateRef> {
        match state {
            StateRef::Named(state) => Ok(StateRef::Vals(self.composition_named(state)?)),
            _ => Ok(state.clone()),
        }
    }

    /// The states `A` leads to from `s0`, with `t` as the partial successor
    /// and no continuation (`getNextStates(Action.UNKNOWN, A,
    /// ActionItemList.Empty, c, s0, t, iss)`), duplicates included.
    fn cdot_steps(
        self: &Arc<Self>,
        env: &Env,
        s0: &StateRef,
        t: StateVals,
        a: ExprId,
        bounded_tail: bool,
    ) -> Result<Vec<StateVals>> {
        if !self.bounded_composition() {
            self.check_action_composition()?;
        }
        let s0 = self.composition_current(s0)?;
        let action = Action {
            owner: self.ir.clone(),
            names: self.names.clone(),
            context: Arc::downgrade(self),
            expr: a,
            env: env.clone(),
            name: ActionName::Unnamed,
            params: Vec::new(),
            label: String::new(),
            id: usize::MAX,
        };
        let mut iss: Vec<StateVals> = Vec::new();
        let mut collect = |s: &Successor<'_>| {
            iss.push(StateVals::from(s.state));
            Flow::Continue
        };
        let mut g = Gen {
            core: self,
            init: false,
            diagnostic: false,
            s0,
            s1: t,
            action: &action,
            ordinal: 0,
            emitted: 0,
            intermediate: 0,
            sink: &mut collect,
            choices: None,
        };
        let result = g.step(a, &None, env);
        if let Err(error) = result {
            // A tail that emitted before failing is not a proved deterministic
            // operation. In particular its late error cannot certify a
            // before-first-successor endpoint after hiding the earlier row.
            if bounded_tail && !iss.is_empty() && error.class() == crate::ErrorClass::Eval {
                return self.unproved_composition();
            }
            return Err(error);
        }
        Ok(iss)
    }

    /// `Tool.eval` of `A \cdot B` (`:2772-2808`).
    pub(crate) fn eval_cdot(
        self: &Arc<Self>,
        env: &mut Env,
        st: &St,
        a: ExprId,
        b: ExprId,
        e: ExprId,
    ) -> Result<Ev> {
        if self.bounded_composition() {
            let intermediates = self.bounded_cdot_intermediates(env, &st.s0, a, b)?;
            let target = self.composition_current(&st.s1)?;
            let StateRef::Vals(target) = target else {
                return self.unproved_composition();
            };
            if target.len() != self.ir.vars().len() || target.iter().any(Option::is_none) {
                return self.unproved_composition();
            }
            for intermediate in intermediates {
                for successor in self.bounded_cdot_tail(env, intermediate, b)? {
                    self.loop_work()?;
                    let mut equal = true;
                    for (left, right) in successor.iter().zip(target.iter()) {
                        let (Some(left), Some(right)) = (left, right) else {
                            return self.unproved_composition();
                        };
                        if !self.equals(left, right)? {
                            equal = false;
                            break;
                        }
                    }
                    if equal {
                        return Ok(Ev::V(Value::TRUE));
                    }
                }
            }
            return Ok(Ev::V(Value::FALSE));
        }
        if self.opts.action_composition == ActionComposition::Off {
            return Err(off_error(self, e));
        }
        let empty: StateVals = vec![None; self.ir.vars().len()].into();
        for t in self.cdot_steps(env, &st.s0, empty, a, false)? {
            self.loop_work()?;
            let st2 = St {
                s0: StateRef::Vals(t),
                s1: st.s1.clone(),
                control: st.control,
            };
            match self.eval(&mut env.clone(), &st2, b)? {
                Ev::V(Value::Bool(true)) => return Ok(Ev::V(Value::Bool(true))),
                Ev::V(Value::Bool(false)) => {}
                other => {
                    // TLC casts to `BoolValue`; the cast fails.
                    return Err(EvalError::general(format!(
                        "Attempted to evaluate an expression of form A \\cdot B, but B was {}.\n{}",
                        self.ev_string(&other),
                        self.loc(e)
                    )));
                }
            }
        }
        Ok(Ev::V(Value::Bool(false)))
    }
}

impl Gen<'_, '_, '_> {
    /// `getNextStates` of `A \cdot B` (`:1488-1531`).
    pub(super) fn cdot(
        &mut self,
        a: ExprId,
        b: ExprId,
        acts: &Acts,
        env: &Env,
        e: ExprId,
    ) -> Result<Flow> {
        if self.core.bounded_composition() {
            if acts.is_some() || self.s1.iter().any(Option::is_some) {
                return self.core.unproved_composition();
            }
            let intermediates = self.core.bounded_cdot_intermediates(env, &self.s0, a, b)?;
            for intermediate in intermediates {
                for successor in self.core.bounded_cdot_tail(env, intermediate, b)? {
                    self.core.loop_work()?;
                    self.s1 = successor;
                    if self.emit() == Flow::Stop {
                        self.s1 = vec![None; self.core.ir.vars().len()].into();
                        return Ok(Flow::Stop);
                    }
                }
            }
            self.s1 = vec![None; self.core.ir.vars().len()].into();
            return Ok(Flow::Continue);
        }
        if self.choices.is_some() {
            return Err(EvalError::unsupported(
                "constructive generation of action composition",
            ));
        }
        let core = self.core;
        let mode = core.opts.action_composition;
        match mode {
            ActionComposition::Off => return Err(off_error(core, e)),
            ActionComposition::Tla if acts.is_some() || self.s1.iter().any(Option::is_some) => {
                return Err(distorted(core, e));
            }
            _ => {}
        }
        // The private A-side collection bypasses the caller's successor sink
        // in both modes. Ask the host before entering that intermediate search.
        core.check_action_composition()?;
        // s -A-> t
        let mut iss: Vec<StateVals> = Vec::new();
        {
            let mut collect = |s: &Successor<'_>| {
                iss.push(StateVals::from(s.state));
                Flow::Continue
            };
            let mut g = Gen {
                core,
                init: false,
                diagnostic: false,
                s0: self.s0.clone(),
                s1: copy_with(&core.composition_current(&self.s0)?, &self.s1),
                action: self.action,
                ordinal: 0,
                emitted: 0,
                intermediate: 0,
                sink: &mut collect,
                choices: None,
            };
            g.step(a, acts, env)?;
        }
        if mode == ActionComposition::Tlc {
            self.intermediate += iss.len() as u64;
        }
        // t -B-> u
        let action = self.action;
        for t in iss {
            core.loop_work()?;
            let mut g = Gen {
                core,
                init: false,
                diagnostic: false,
                s0: StateRef::Vals(t),
                s1: self.s1.clone(),
                action,
                ordinal: self.ordinal,
                emitted: 0,
                intermediate: 0,
                sink: &mut *self.sink,
                choices: None,
            };
            let r = g.step(b, acts, env);
            let n = g.emitted;
            self.emitted += n;
            self.ordinal += n;
            if r? == Flow::Stop {
                return Ok(Flow::Stop);
            }
        }
        Ok(Flow::Continue)
    }
}

impl Enab {
    /// `enabled` of `A \cdot B` (`:3371-3393`).
    pub(super) fn cdot(
        &self,
        a: ExprId,
        b: ExprId,
        acts: &Acts,
        env: &Env,
        s1: &EnabledState,
        e: ExprId,
    ) -> Result<Option<EnabledState>> {
        let core = &self.core;
        if core.bounded_composition() {
            // Only a nonstuttering subscript may follow the complete composed
            // edge. Test it against the original s0, never the intermediate t.
            let mut continuation = acts.as_ref();
            while let Some(item) = continuation {
                if !matches!(item.kind, super::Kind::Changed) {
                    return core.unproved_composition();
                }
                continuation = item.next.as_ref();
            }
            if !s1.is_empty() {
                return core.unproved_composition();
            }
            for intermediate in core.bounded_cdot_intermediates(env, &self.s0, a, b)? {
                for successor in core.bounded_cdot_tail(env, intermediate, b)? {
                    core.loop_work()?;
                    let mut named = crate::NamedState::empty(core);
                    for (declaration, value) in core.ir.vars().iter().zip(successor.iter()) {
                        let Some(value) = value else {
                            return core.unproved_composition();
                        };
                        named = named.with(&core.ir.decl(*declaration).name, value.clone());
                    }
                    if let Some(successor) = self.cont(acts, named)? {
                        return Ok(Some(successor));
                    }
                }
            }
            return Ok(None);
        }
        let root_s1 = core.composition_named(s1)?;
        match core.opts.action_composition {
            ActionComposition::Off => return Err(off_error(core, e)),
            ActionComposition::Tla if acts.is_some() || !s1.is_empty() => {
                return Err(distorted(core, e));
            }
            _ => {}
        }
        let t0 = copy_with(&core.composition_current(&self.s0)?, &root_s1);
        for t in core.cdot_steps(env, &self.s0, t0, a, false)? {
            core.loop_work()?;
            let en = Enab {
                core: core.clone(),
                s0: StateRef::Vals(t),
            };
            if let Some(s2) = en.enabled(b, acts, env, s1.clone())? {
                return Ok(Some(s2));
            }
        }
        Ok(None)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn copy_with_takes_current_values_of_assigned_variables() {
        let s0 = StateRef::Vals(vec![Some(Value::Int(1)), Some(Value::Int(2))].into());
        let s1: StateVals = vec![None, Some(Value::Int(9))].into();
        assert_eq!(&*copy_with(&s0, &s1), &[None, Some(Value::Int(2))]);
        assert_eq!(&*copy_with(&StateRef::Empty, &s1), &[None, None]);
    }
}