dive-core 0.1.0

The dive execution core for TLA+: value store, plan compiler, interpreter and successor generation
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
//! Generator-side compilation helpers, kept apart from the value compiler: TLC's `elements()`
//! multiplicity for `x' \in S`, the decomposition of `UNCHANGED`, and the
//! resolution of a function applied as an action.

use dive_ir::{BuiltinOp, DefScope, Expr, ExprId, OpRef, StdOp};
use dive_value::{DeferredKind, SetKind, Value};

use super::{Compiler, ConstBinding, Mode, Sb};
use crate::Error;
use crate::plan::{Node, P, Raw, Unch};

/// How TLC represents the value of a set expression, as far as the
/// multiplicity of its `elements()` is concerned.
enum Class {
    /// `SetEnumValue` (`set` true) or `IntervalValue` (TLC's `Reducible`):
    /// `\cup` with another reducible set is computed eagerly, and `UNION`
    /// of set enumerations too.
    Reducible { set: bool },
    /// A set whose `elements()` lists each element once, of another class.
    Plain,
    /// A set whose `elements()` may repeat elements: its structure.
    Raw(Raw),
}

/// The deepest definition chain followed while classifying a set.
const MAX_DEPTH: u32 = 64;

fn value_class(v: &Value) -> Result<bool, Error> {
    // Whether a startup value is safe to enumerate as normalized.
    let Value::Set(s) = v else {
        return Ok(true);
    };
    match s.kind() {
        SetKind::Deferred => Ok(matches!(
            s.as_deferred().map(|d| d.kind()),
            Some(DeferredKind::Map)
        )),
        SetKind::FcnSet | SetKind::RcdSet | SetKind::Product => {
            for (_, c) in s.components() {
                if !value_class(&c)? {
                    return Ok(false);
                }
            }
            Ok(true)
        }
        _ => Ok(true),
    }
}

impl Compiler<'_> {
    /// The structure TLC's `elements()` of `e` has when it may repeat
    /// elements, or `None` when it cannot (the common case, compiled as a
    /// plain `x' \in S`).
    ///
    /// # Errors
    /// Unsupported when the multiplicity depends on a representation the
    /// core cannot see.
    pub(super) fn raw_plan(&mut self, e: ExprId, env: usize) -> Result<Option<Raw>, Error> {
        if !self.m.heap.store().semantics().tlc_comparisons {
            return Ok(None);
        }
        match self.class(e, env, 0)? {
            Class::Raw(r) => Ok(Some(r)),
            Class::Reducible { .. } | Class::Plain => Ok(None),
        }
    }

    fn leaf(&mut self, e: ExprId, env: usize) -> Result<Raw, Error> {
        Ok(Raw::Leaf(self.p(e, env, Mode::Plain)?))
    }

    fn as_raw(&mut self, c: Class, e: ExprId, env: usize) -> Result<Raw, Error> {
        match c {
            Class::Raw(r) => Ok(r),
            Class::Reducible { .. } | Class::Plain => self.leaf(e, env),
        }
    }

    #[allow(clippy::too_many_lines, reason = "one arm per set constructor")]
    fn class(&mut self, e: ExprId, env: usize, depth: u32) -> Result<Class, Error> {
        if depth > MAX_DEPTH {
            return Err(Error::unsupported(
                "x' \\in a set behind a definition chain deeper than the core follows",
            ));
        }
        let expr = self.ir.node(e).expr.clone();
        match expr {
            Expr::SetEnum(_) | Expr::SetMap { .. } => Ok(Class::Reducible { set: true }),
            Expr::Label { body: a, .. } | Expr::Selected(a) => self.class(a, env, depth + 1),
            Expr::Const(c) => match self.h.constants.get(c.index()).cloned().flatten() {
                Some(ConstBinding::Value(v)) => Ok(startup(&v)?),
                Some(ConstBinding::Def(d)) => self.def_class(d, e, env, depth),
                None => Ok(Class::Plain),
            },
            Expr::Def(d) => self.def_class(d, e, env, depth),
            Expr::Apply {
                callee: OpRef::Def(d),
                args,
            } => {
                let d = self.redirect(d);
                let def = self.ir.def(d);
                if matches!(def.std, Some(StdOp::NaturalsDotDot | StdOp::IntegersDotDot)) {
                    return Ok(Class::Reducible { set: false });
                }
                if args.is_empty() {
                    return self.def_class(d, e, env, depth);
                }
                if def.std.is_none() && risky(self.ir, def.body, 0) {
                    return Err(Error::unsupported(
                        "x' \\in an operator application whose body builds a lazily represented set (core)",
                    ));
                }
                Ok(Class::Plain)
            }
            Expr::Apply {
                callee: OpRef::Std(op),
                ..
            } => Ok(
                if matches!(op, StdOp::NaturalsDotDot | StdOp::IntegersDotDot) {
                    Class::Reducible { set: false }
                } else {
                    Class::Plain
                },
            ),
            Expr::Local(r) => {
                let fe = self.frame_env(env, r.up)?;
                match self.envs[fe].slots.get(r.slot.index()).cloned() {
                    Some(Sb::Arg {
                        expr, env: aenv, ..
                    }) => self.class(expr, aenv, depth + 1),
                    Some(Sb::LetVal { def, env: lenv, .. }) => {
                        let body = self.ir.def(def).body;
                        self.class(body, lenv, depth + 1)
                    }
                    _ => Ok(Class::Plain),
                }
            }
            Expr::Builtin { op, args } => match (op, args.as_ref()) {
                (BuiltinOp::Cup, &[a, b]) => {
                    let ca = self.class(a, env, depth + 1)?;
                    let cb = self.class(b, env, depth + 1)?;
                    if let (Class::Reducible { set: sa }, Class::Reducible { set: sb }) = (&ca, &cb)
                    {
                        // Computed eagerly (`SetEnumValue.cup`), or the
                        // other operand itself when one is empty.
                        return Ok(Class::Reducible { set: *sa && *sb });
                    }
                    let ra = self.as_raw(ca, a, env)?;
                    let rb = self.as_raw(cb, b, env)?;
                    Ok(Class::Raw(Raw::Cup(Box::new(ra), Box::new(rb))))
                }
                (BuiltinOp::Cap, &[a, b]) => {
                    let ca = self.class(a, env, depth + 1)?;
                    let cb = self.class(b, env, depth + 1)?;
                    if !matches!(ca, Class::Raw(_)) && !matches!(cb, Class::Raw(_)) {
                        return Ok(Class::Plain);
                    }
                    let ra = self.as_raw(ca, a, env)?;
                    let rb = self.as_raw(cb, b, env)?;
                    let pa = self.p(a, env, Mode::Plain)?;
                    let pb = self.p(b, env, Mode::Plain)?;
                    Ok(Class::Raw(Raw::Cap(Box::new(ra), Box::new(rb), pa, pb)))
                }
                (BuiltinOp::SetMinus, &[a, b]) => match self.class(a, env, depth + 1)? {
                    Class::Raw(ra) => {
                        let pb = self.p(b, env, Mode::Plain)?;
                        Ok(Class::Raw(Raw::Minus(Box::new(ra), pb)))
                    }
                    _ => Ok(Class::Plain),
                },
                (BuiltinOp::BigUnion, &[a]) => self.union_class(a, env, depth),
                (BuiltinOp::Times, items) => {
                    let items = items.to_vec();
                    self.odometer(e, &items, env, depth)
                }
                _ => Ok(Class::Plain),
            },
            Expr::Cartesian(items) => {
                let items = items.to_vec();
                self.odometer(e, &items, env, depth)
            }
            Expr::RecordSet(fields) => {
                let items: Vec<ExprId> = fields.iter().map(|f| f.value).collect();
                self.odometer(e, &items, env, depth)
            }
            Expr::FcnSet { range, .. } => self.odometer(e, &[range], env, depth),
            Expr::SetFilter { bound, .. } => {
                let Some(dom) = bound.domain else {
                    return Ok(Class::Plain);
                };
                match self.class(dom, env, depth + 1)? {
                    Class::Raw(inner) => {
                        let Expr::SetFilter { bound, pred } = self.ir.node(e).expr.clone() else {
                            return Err(Error::internal("a filter changed shape"));
                        };
                        let (mut binds, saved) =
                            self.binds(std::slice::from_ref(&bound), env, Mode::Plain)?;
                        let p = self.p(pred, env, Mode::Plain);
                        self.unbind(saved);
                        let pred = p?;
                        let bind = binds
                            .pop()
                            .ok_or_else(|| Error::internal("filter without a bound"))?;
                        Ok(Class::Raw(Raw::Filter {
                            bind,
                            pred,
                            inner: Box::new(inner),
                        }))
                    }
                    _ => Ok(Class::Plain),
                }
            }
            Expr::Let { body, .. } => {
                if risky(self.ir, body, 0) {
                    return Err(Error::unsupported(
                        "x' \\in a LET whose body builds a lazily represented set (core)",
                    ));
                }
                Ok(Class::Plain)
            }
            _ => Ok(Class::Plain),
        }
    }

    fn def_class(
        &mut self,
        d: dive_ir::DefId,
        e: ExprId,
        env: usize,
        depth: u32,
    ) -> Result<Class, Error> {
        let d = self.redirect(d);
        if let Some(v) = self.h.precomputed.get(&d) {
            return startup(v);
        }
        let def = self.ir.def(d);
        if matches!(def.std, Some(StdOp::NaturalsDotDot | StdOp::IntegersDotDot)) {
            return Ok(Class::Reducible { set: false });
        }
        if def.std.is_some() || !def.params.is_empty() {
            return Ok(Class::Plain);
        }
        if def.recursive || matches!(def.scope, DefScope::LetValue { .. }) {
            if risky(self.ir, def.body, 0) {
                return Err(Error::unsupported(
                    "x' \\in a definition whose body builds a lazily represented set (core)",
                ));
            }
            return Ok(Class::Plain);
        }
        let _ = e;
        let parent = self.lexical_parent(d, env)?;
        let inner = self.new_env(d, parent);
        self.class(def.body, inner, depth + 1)
    }

    fn union_class(&mut self, a: ExprId, env: usize, depth: u32) -> Result<Class, Error> {
        if let Expr::SetEnum(items) = self.ir.node(a).expr.clone() {
            let mut all_enum = true;
            let mut raws = Vec::with_capacity(items.len());
            for &i in &items {
                let c = self.class(i, env, depth + 1)?;
                all_enum &= matches!(c, Class::Reducible { set: true });
                raws.push(self.as_raw(c, i, env)?);
            }
            if all_enum {
                // `UnionValue.union` combines set enumerations eagerly.
                return Ok(Class::Reducible { set: true });
            }
            return Ok(Class::Raw(Raw::Union(raws.into())));
        }
        if risky(self.ir, a, 0) {
            return Err(Error::unsupported(
                "x' \\in UNION of a set whose members TLC may represent lazily (core)",
            ));
        }
        let p = self.p(a, env, Mode::Plain)?;
        Ok(Class::Raw(Raw::UnionOf(p)))
    }

    fn odometer(
        &mut self,
        e: ExprId,
        items: &[ExprId],
        env: usize,
        depth: u32,
    ) -> Result<Class, Error> {
        let mut any = false;
        let mut raws = Vec::with_capacity(items.len());
        for &i in items {
            let c = self.class(i, env, depth + 1)?;
            any |= matches!(c, Class::Raw(_));
            raws.push(self.as_raw(c, i, env)?);
        }
        if !any {
            return Ok(Class::Plain);
        }
        let p = self.p(e, env, Mode::Plain)?;
        Ok(Class::Raw(Raw::Odometer(raws.into(), p)))
    }

    /// Decomposes `UNCHANGED e` with TLC's `processUnchanged`:
    /// variables, tuples and
    /// zero-arity definitions are followed; anything else is verified.
    pub(super) fn unchanged_items(
        &mut self,
        e: ExprId,
        env: usize,
        out: &mut Vec<Unch>,
    ) -> Result<(), Error> {
        #[allow(clippy::cast_possible_truncation, reason = "at most 64 variables")]
        match self.ir.node(e).expr.clone() {
            Expr::Var { var, primed: false } => {
                out.push(Unch::Var {
                    var: var.index() as u16,
                    at: e.0,
                });
                Ok(())
            }
            Expr::Tuple(items) => {
                for &i in &items {
                    self.unchanged_items(i, env, out)?;
                }
                Ok(())
            }
            Expr::Label { body: a, .. } | Expr::Selected(a) => self.unchanged_items(a, env, out),
            Expr::Def(d) => {
                let d = self.redirect(d);
                let def = self.ir.def(d);
                if self.has_startup_value(d)
                    || def.std.is_some()
                    || !def.params.is_empty()
                    || def.recursive
                    || matches!(def.scope, DefScope::LetValue { .. })
                {
                    return self.verify_item(e, env, out);
                }
                let parent = self.lexical_parent(d, env)?;
                let inner = self.new_env(d, parent);
                self.unchanged_items(def.body, inner, out)
            }
            Expr::Apply {
                callee: OpRef::Def(d),
                args,
            } if args.is_empty() => {
                let d = self.redirect(d);
                let def = self.ir.def(d);
                if self.has_startup_value(d)
                    || def.std.is_some()
                    || def.recursive
                    || matches!(def.scope, DefScope::LetValue { .. })
                {
                    return self.verify_item(e, env, out);
                }
                let parent = self.lexical_parent(d, env)?;
                let inner = self.new_env(d, parent);
                self.unchanged_items(def.body, inner, out)
            }
            // An `INSTANCE` substitution (stream 2): a substituted name is
            // followed like an argument, an unsubstituted one is the root's
            // variable.
            Expr::SubstRef {
                decl,
                primed: false,
            } => match self.subst_expr(decl) {
                Some(r) => {
                    let (expr, aenv, depth) = r?;
                    self.outside(depth, |c| c.unchanged_items(expr, aenv, out))
                }
                None => match self.ir.decl(decl).var {
                    Some(v) => {
                        out.push(Unch::Var {
                            var: v.index() as u16,
                            at: e.0,
                        });
                        Ok(())
                    }
                    None => self.verify_item(e, env, out),
                },
            },
            Expr::Subst { bindings, body } => {
                let mut inner = Vec::new();
                let (r, _) = self.subst_scope(&bindings, env, Mode::Plain, |c| {
                    c.unchanged_items(body, env, &mut inner)
                })?;
                // A verified item would read the substitution's slots after
                // its scope ends.
                if inner.iter().any(|u| matches!(u, Unch::Verify(_))) {
                    return Err(Error::unsupported(
                        "UNCHANGED of a non-variable expression under an INSTANCE substitution (core)",
                    ));
                }
                out.extend(inner);
                Ok(r)
            }
            Expr::Local(r) => {
                let fe = self.frame_env(env, r.up)?;
                match self.envs[fe].slots.get(r.slot.index()).cloned() {
                    Some(Sb::Arg {
                        expr, env: aenv, ..
                    }) => self.unchanged_items(expr, aenv, out),
                    Some(Sb::LetVal { def, env: lenv, .. }) => {
                        let body = self.ir.def(def).body;
                        self.unchanged_items(body, lenv, out)
                    }
                    _ => self.verify_item(e, env, out),
                }
            }
            _ => self.verify_item(e, env, out),
        }
    }

    fn verify_item(&mut self, e: ExprId, env: usize, out: &mut Vec<Unch>) -> Result<(), Error> {
        let x = self.p(e, env, Mode::Plain)?;
        let y = self.p(e, env, Mode::Primed)?;
        let same = self.push(Node::Eq(x, y))?;
        out.push(Unch::Verify(same));
        Ok(())
    }

    /// `v = v'` for `<<A>>_v`'s `CHANGED v` item. A subscript compiled to a
    /// tuple, possibly nested and behind thunks, of state variables keeps
    /// its `Eq` inside a [`Node::SameVars`], which compares the variables
    /// without building either tuple when that cannot change the result.
    pub(super) fn changed_test(&mut self, e: ExprId, env: usize) -> Result<P, Error> {
        let x = self.p(e, env, Mode::Plain)?;
        let y = self.p(e, env, Mode::Primed)?;
        let eq = self.push(Node::Eq(x, y))?;
        let mut leaves = Vec::new();
        let mut thunks = Vec::new();
        if self.variable_tuple(x, y, 0, &mut leaves, &mut thunks) && !leaves.is_empty() {
            return self.push(Node::SameVars {
                eq,
                leaves: leaves.into(),
                thunks: thunks.into(),
            });
        }
        Ok(eq)
    }

    /// Whether `x` is a tuple whose elements are state variables or such
    /// tuples, each possibly behind thunks (`Node::Lazy`), and `y` is the
    /// same tree with each variable primed. Collects each variable with its
    /// depth below the outer tuple, and every thunk slot on the way.
    fn variable_tuple(
        &self,
        x: P,
        y: P,
        depth: u8,
        leaves: &mut Vec<(u16, u8)>,
        thunks: &mut Vec<u32>,
    ) -> bool {
        // A shallow tree keeps every leaf far from `compare::materialized`'s
        // depth limit.
        if depth >= 8 {
            return false;
        }
        let nodes = &self.code.nodes;
        match (nodes.get(x as usize), nodes.get(y as usize)) {
            (Some(Node::Lazy { slot, body }), _) => {
                thunks.push(*slot);
                self.variable_tuple(*body, y, depth, leaves, thunks)
            }
            (_, Some(Node::Lazy { slot, body })) => {
                thunks.push(*slot);
                self.variable_tuple(x, *body, depth, leaves, thunks)
            }
            (Some(Node::Tuple(xs)), Some(Node::Tuple(ys))) if xs.len() == ys.len() => {
                xs.iter().zip(ys.iter()).all(|(&a, &b)| {
                    match (nodes.get(a as usize), nodes.get(b as usize)) {
                        (Some(Node::Var(v)), Some(Node::Primed(w))) if v == w => {
                            leaves.push((*v, depth + 1));
                            true
                        }
                        _ => self.variable_tuple(a, b, depth + 1, leaves, thunks),
                    }
                })
            }
            _ => false,
        }
    }

    /// The function constructor `f` names, with its environment, when TLC
    /// evaluates `f` (with `KeepLazy`) to an unmaterialized
    /// `FcnLambdaValue`.
    pub(super) fn fcn_lambda(
        &mut self,
        f: ExprId,
        env: usize,
        depth: u32,
    ) -> Result<Option<(ExprId, usize)>, Error> {
        if depth > MAX_DEPTH {
            return Ok(None);
        }
        match self.ir.node(f).expr.clone() {
            Expr::FcnCons { .. } => Ok(Some((f, env))),
            Expr::Label { body: a, .. } | Expr::Selected(a) => self.fcn_lambda(a, env, depth + 1),
            Expr::Def(d)
            | Expr::Apply {
                callee: OpRef::Def(d),
                ..
            } => {
                if let Expr::Apply { args, .. } = &self.ir.node(f).expr
                    && !args.is_empty()
                {
                    return Ok(None);
                }
                let d = self.redirect(d);
                let def = self.ir.def(d);
                if self.has_startup_value(d)
                    || def.std.is_some()
                    || !def.params.is_empty()
                    || def.recursive
                    || matches!(def.scope, DefScope::LetValue { .. })
                {
                    return Ok(None);
                }
                let parent = self.lexical_parent(d, env)?;
                let inner = self.new_env(d, parent);
                self.fcn_lambda(def.body, inner, depth + 1)
            }
            _ => Ok(None),
        }
    }
}

fn startup(v: &Value) -> Result<Class, Error> {
    if let Value::Set(s) = v
        && matches!(s.kind(), SetKind::Enum | SetKind::Raw | SetKind::Interval)
    {
        return Ok(Class::Reducible {
            set: s.kind() != SetKind::Interval,
        });
    }
    if value_class(v)? {
        Ok(Class::Plain)
    } else {
        Err(Error::unsupported(
            "x' \\in a startup value TLC represents lazily, whose enumeration depends on its history (core)",
        ))
    }
}

/// Whether an expression builds a set TLC may keep lazy with repeated
/// elements (`\cup`, `UNION`), at any depth, through definitions.
fn risky(ir: &dive_ir::Ir, e: ExprId, _depth: u32) -> bool {
    let mut seen = std::collections::HashSet::new();
    risky_in(ir, e, &mut seen)
}

fn risky_in(
    ir: &dive_ir::Ir,
    e: ExprId,
    seen: &mut std::collections::HashSet<dive_ir::DefId>,
) -> bool {
    let node = &ir.node(e).expr;
    if matches!(
        node,
        Expr::Builtin {
            op: BuiltinOp::Cup | BuiltinOp::BigUnion,
            ..
        }
    ) {
        return true;
    }
    if let Expr::Def(d)
    | Expr::Apply {
        callee: OpRef::Def(d),
        ..
    } = node
        && seen.insert(*d)
        && risky_in(ir, ir.def(*d).body, seen)
    {
        return true;
    }
    let mut found = false;
    node.for_each_child(|c| {
        if !found && risky_in(ir, c, seen) {
            found = true;
        }
    });
    found
}