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
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
//! Constructor-grounded result facts, separate from expression effects.

use std::collections::HashSet;
use std::sync::{Arc, Weak};

use dive_ir::{Arg, DefId, Expr, ExprId, OpRef, StdKind, StdOp, StdSupport};
use dive_value::{Fcn, Set, SetKind, Value};

use crate::core::Core;
use crate::env::{Env, Ev, Frame, OpVal, StateRef, SubstLink, Sv, Thunk};
use crate::{ConstBinding, EvalError, Evaluator, HostControl, Result, Scope};

mod scalar_callbacks;
#[cfg(test)]
mod tests;

/// A checked own-call fact for the supplied source roots of one evaluator.
///
/// Every reachable concatenation in these roots has a tuple operand. This
/// says nothing about other native name creators, effects, model truth or
/// roots the caller omitted. There is no public constructor; a model driver
/// must supply its complete checking path before removing a sequential reason.
#[derive(Clone)]
pub struct TupleConcatSources {
    owner: Weak<Core>,
}

impl std::fmt::Debug for TupleConcatSources {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TupleConcatSources").finish_non_exhaustive()
    }
}

impl TupleConcatSources {
    /// Whether the inspected roots belong to this actual evaluator.
    #[must_use]
    pub fn belongs_to(&self, evaluator: &Evaluator) -> bool {
        self.owner.ptr_eq(&Arc::downgrade(&evaluator.core))
    }
}

fn reserve<T>(values: &mut Vec<T>, count: usize) -> Result<()> {
    values
        .try_reserve(count)
        .map_err(|_| EvalError::resource_limit("tuple name analysis allocation"))
}

fn push<T>(values: &mut Vec<T>, value: T) -> Result<()> {
    reserve(values, 1)?;
    values.push(value);
    Ok(())
}

impl Evaluator {
    /// Inspects complete source roots for constructor-grounded tuple concatenation.
    ///
    /// Literal tuples and the unchanged native `Append` ground a finite monotone
    /// result analysis. All actuals remain unknown; recursion is never assumed
    /// tuple-valued. Every child is still inspected for its own calls. Opaque
    /// captures, native roots and unknown higher-order calls decline without forcing a
    /// value, calling a provider, or changing permissions or evaluation.
    ///
    /// `definitions` are bare configuration/assumption roots, not merely native
    /// definitions seen as fully applied callees. This fact covers only the
    /// supplied roots; it does not grant model-wide name or parallel authority.
    /// The walk has no count or depth ceiling and polls the supplied control,
    /// or the installed evaluator control when it is absent.
    ///
    /// ```no_run
    /// # fn inspect(ev: &dive_eval::Evaluator, root: (dive_ir::ExprId, dive_eval::Scope))
    /// # -> dive_eval::Result<()> {
    /// let fact = ev.tuple_concat_sources(&[root], &[], None)?;
    /// # let _ = fact; Ok(()) }
    /// ```
    ///
    /// # Errors
    /// Actual control interruption or a failed analysis allocation.
    pub fn tuple_concat_sources(
        &self,
        roots: &[(ExprId, Scope)],
        definitions: &[DefId],
        control: Option<&dyn HostControl>,
    ) -> Result<Option<TupleConcatSources>> {
        let mut analysis = Analysis {
            ev: self,
            control,
            blocked: Vec::new(),
        };
        analysis.poll()?;
        // A direct standard reference has lost any configured-constant origin.
        // Keep these origins unknown, including a same-target override.
        for binding in self.core.consts.iter().flatten() {
            analysis.poll()?;
            if let ConstBinding::Def(def) = binding
                && let Some(op) = self.core.ir.def(self.redirected(*def)).std
            {
                push(&mut analysis.blocked, op)?;
            }
        }
        for (index, def) in self.core.ir.defs().iter().enumerate() {
            analysis.poll()?;
            let id = DefId(
                u32::try_from(index)
                    .map_err(|_| EvalError::resource_limit("tuple name definition index"))?,
            );
            if let Some(op) = def.std
                && (self.redirected(id) != id || self.is_value_override(id))
            {
                push(&mut analysis.blocked, op)?;
            }
        }
        let Some(mut sources) = analysis.captures(roots)? else {
            return Ok(None);
        };
        for &def in definitions {
            analysis.poll()?;
            let Some(body) = analysis.user_body(def, 0) else {
                return Ok(None);
            };
            push(&mut sources.exprs, body)?;
        }
        let Some(callbacks) = analysis.closed_scalar_callbacks(&sources)? else {
            return Ok(None);
        };
        let tuples = analysis.results()?;
        if !analysis.calls(&sources.exprs, &tuples, callbacks)? {
            return Ok(None);
        }
        analysis.poll()?;
        Ok(Some(TupleConcatSources {
            owner: Arc::downgrade(&self.core),
        }))
    }
}

struct Analysis<'a> {
    ev: &'a Evaluator,
    control: Option<&'a dyn HostControl>,
    blocked: Vec<StdOp>,
}

impl Analysis<'_> {
    fn poll(&self) -> Result<()> {
        if let Some(control) = self.control {
            control.check().map_err(EvalError::interrupted)
        } else {
            self.ev.core.host.check_control()
        }
    }

    fn native(&self, op: &OpRef, arity: usize) -> Option<StdOp> {
        let op = match op {
            OpRef::Std(op) => *op,
            OpRef::Def(def) => {
                let target = self.ev.ir().defs().get(def.index())?;
                if self.ev.redirected(*def) != *def
                    || self.ev.is_value_override(*def)
                    || target.params.len() != arity
                    || target.params.iter().any(|p| p.arity != 0)
                {
                    return None;
                }
                target.std?
            }
            _ => return None,
        };
        (op.kind() == StdKind::Value
            && op.support() == StdSupport::Core
            && usize::try_from(op.java_arity()).ok() == Some(arity)
            && !self.blocked.contains(&op)
            && !self.ev.core.std_redirects.contains_key(&op))
        .then_some(op)
    }

    fn user_body(&self, def: DefId, arity: usize) -> Option<ExprId> {
        let target = self.ev.ir().defs().get(def.index())?;
        (target.std.is_none()
            && self.ev.redirected(def) == def
            && !self.ev.is_value_override(def)
            && target.params.len() == arity
            && target.params.iter().all(|p| p.arity == 0))
        .then_some(target.body)
    }

    // Result dependencies exclude children whose values do not determine the
    // outer result kind. The independent call walk below still visits them.
    fn result_edges(&self, expr: &Expr, edges: &mut Vec<ExprId>) -> Result<()> {
        match expr {
            Expr::If { then, other, .. } => {
                push(edges, *then)?;
                push(edges, *other)?;
            }
            Expr::Case { arms, other } => {
                for arm in arms {
                    push(edges, arm.value)?;
                }
                if let Some(other) = other {
                    push(edges, *other)?;
                }
            }
            Expr::Label { body, .. }
            | Expr::Selected(body)
            | Expr::Let { body, .. }
            | Expr::Subst { body, .. } => push(edges, *body)?,
            Expr::Def(def) => {
                if let Some(body) = self.user_body(*def, 0) {
                    push(edges, body)?;
                }
            }
            Expr::Apply { callee, args } if args.iter().all(|a| matches!(a, Arg::Expr { .. })) => {
                match self.native(callee, args.len()) {
                    Some(StdOp::SequencesConcat) => {
                        for arg in args {
                            if let Arg::Expr { expr, .. } = arg {
                                push(edges, *expr)?;
                            }
                        }
                    }
                    Some(_) => {}
                    None => {
                        if let OpRef::Def(def) = callee
                            && let Some(body) = self.user_body(*def, args.len())
                        {
                            push(edges, body)?;
                        }
                    }
                }
            }
            _ => {}
        }
        Ok(())
    }

    fn results(&self) -> Result<Vec<bool>> {
        let count = self.ev.ir().nodes().len();
        let mut users = Vec::new();
        reserve(&mut users, count)?;
        users.resize_with(count, Vec::new);
        let mut tuples = Vec::new();
        reserve(&mut tuples, count)?;
        tuples.resize(count, false);
        let mut work = Vec::new();
        for (index, node) in self.ev.ir().nodes().iter().enumerate() {
            self.poll()?;
            let id = ExprId(
                u32::try_from(index)
                    .map_err(|_| EvalError::resource_limit("tuple name expression index"))?,
            );
            let mut edges = Vec::new();
            self.result_edges(&node.expr, &mut edges)?;
            for edge in edges {
                let Some(dependents) = users.get_mut(edge.index()) else {
                    return Err(EvalError::bug("tuple name result dependency"));
                };
                push(dependents, id)?;
            }
            push(&mut work, id)?;
        }
        while let Some(id) = work.pop() {
            self.poll()?;
            if tuples[id.index()] {
                continue;
            }
            let expr = self.ev.ir().expr(id);
            let mut edges = Vec::new();
            self.result_edges(expr, &mut edges)?;
            let grounded = matches!(expr, Expr::Tuple(_))
                || matches!(expr, Expr::Apply { callee, args }
                    if args.iter().all(|a| matches!(a, Arg::Expr { .. }))
                    && self.native(callee, args.len()) == Some(StdOp::SequencesAppend));
            let proved = if matches!(expr, Expr::Apply { callee, args }
                if self.native(callee, args.len()) == Some(StdOp::SequencesConcat))
            {
                edges.iter().any(|e| tuples[e.index()])
            } else {
                !edges.is_empty() && edges.iter().all(|e| tuples[e.index()])
            };
            if grounded || proved {
                tuples[id.index()] = true;
                for &user in &users[id.index()] {
                    push(&mut work, user)?;
                }
            }
        }
        Ok(tuples)
    }

    fn calls(&self, sources: &[ExprId], tuples: &[bool], callbacks: bool) -> Result<bool> {
        let mut contexts = Vec::new();
        push(&mut contexts, Lexical::default())?;
        let mut seen = HashSet::new();
        let mut work = Vec::new();
        for &source in sources {
            push(&mut work, (source, 0))?;
        }
        while let Some((id, context)) = work.pop() {
            self.poll()?;
            if seen.contains(&(id, context)) {
                continue;
            }
            seen.try_reserve(1)
                .map_err(|_| EvalError::resource_limit("tuple name call contexts allocation"))?;
            seen.insert((id, context));
            let Some(node) = self.ev.ir().nodes().get(id.index()) else {
                return Ok(false);
            };
            match &node.expr {
                Expr::Apply { callee, args } => {
                    if !self.call(
                        callee,
                        args,
                        tuples,
                        &contexts[context],
                        &mut work,
                        callbacks,
                    )? {
                        return Ok(false);
                    }
                }
                Expr::Def(def) if self.stored_value_leaf(*def) => {
                    // eval_def_use returns this already inspected stored value.
                    // Its overridden body is not evaluated and grants no tuple fact.
                }
                Expr::Def(def) => {
                    if let Some(op) = self.native(&OpRef::Def(*def), 0) {
                        if op.creates_runtime_names() {
                            return Ok(false);
                        }
                    } else if let Some(body) = self.user_body(*def, 0) {
                        push(&mut work, (body, 0))?;
                    } else {
                        return Ok(false);
                    }
                }
                Expr::Let { defs, body } => {
                    let context = self.enter_let(defs, &contexts[context], tuples)?;
                    let next = if let Some(index) = contexts.iter().position(|old| *old == context)
                    {
                        index
                    } else {
                        let index = contexts.len();
                        push(&mut contexts, context)?;
                        index
                    };
                    push(&mut work, (*body, next))?;
                    for def in defs {
                        push(&mut work, (self.ev.ir().def(*def).body, 0))?;
                    }
                    continue;
                }
                _ => {}
            }
            // These constructs can rebind slots, retain a closure or replace
            // dynamic context. Never carry a dominated LET fact through them.
            let context = if matches!(
                node.expr,
                Expr::Quant { .. }
                    | Expr::SetFilter { .. }
                    | Expr::SetMap { .. }
                    | Expr::FcnCons { .. }
                    | Expr::RecFcn { .. }
                    | Expr::TemporalQuant { .. }
                    | Expr::Subst { .. }
                    | Expr::Except { .. }
                    | Expr::Prime(_)
                    | Expr::Enabled(_)
            ) {
                0
            } else {
                context
            };
            node.expr
                .try_for_each_child(|child| push(&mut work, (child, context)))?;
        }
        Ok(true)
    }

    fn stored_value_leaf(&self, def: DefId) -> bool {
        let Some(target) = self.ev.ir().defs().get(def.index()) else {
            return false;
        };
        target.params.is_empty()
            && target.std.is_none()
            && self.ev.redirected(def) == def
            && self.ev.core.def_values.contains_key(&def)
    }

    fn call(
        &self,
        callee: &OpRef,
        args: &[Arg],
        tuples: &[bool],
        context: &Lexical,
        work: &mut Vec<(ExprId, usize)>,
        callbacks: bool,
    ) -> Result<bool> {
        if !callbacks && args.iter().any(|a| matches!(a, Arg::Op { .. })) {
            return Ok(false);
        }
        if let Some(op) = self.native(callee, args.len()) {
            if op.creates_runtime_names() && op != StdOp::SequencesConcat {
                return Ok(false);
            }
            if op == StdOp::SequencesConcat
                && !args.iter().any(|a| {
                    matches!(a, Arg::Expr { expr, .. }
                    if tuples[expr.index()] || self.local_tuple(*expr, context))
                })
            {
                return Ok(false);
            }
        } else if callbacks
            && args.len() == 2
            && matches!(callee, OpRef::Param(_) | OpRef::Subst(_))
        {
            // The separate closed-origin walk proved every possible operator
            // value is a name-free scalar comparison. No tuple fact follows.
        } else if let OpRef::Def(def) = callee
            && let Some(body) = self.call_body(*def, args)
        {
            // A callee's own frame and captured parent are not this callsite's
            // lexical proof context, even for a zero-arity local operator.
            push(work, (body, 0))?;
        } else {
            return Ok(false);
        }
        Ok(true)
    }

    fn enter_let(&self, defs: &[DefId], old: &Lexical, tuples: &[bool]) -> Result<Lexical> {
        let mut context = Lexical {
            frame: old.frame,
            slots: Vec::new(),
        };
        reserve(&mut context.slots, old.slots.len())?;
        context.slots.extend_from_slice(&old.slots);
        for &def in defs {
            self.poll()?;
            let definition = self.ev.ir().def(def);
            let dive_ir::DefScope::LetValue { parent, slot, .. } = definition.scope else {
                continue;
            };
            // Mint only for a real LET-owned slot of this immutable IR. A root
            // Local, formal, capture or similarly numbered foreign frame cannot
            // acquire this fact merely by having a tuple stored in it.
            if context.frame != Some(parent) {
                context.slots.clear();
                context.frame = Some(parent);
            }
            context.slots.retain(|(bound, _)| *bound != slot);
            let valid = self
                .ev
                .ir()
                .def(parent)
                .frame
                .get(slot.index())
                .is_some_and(|info| info.kind == dive_ir::SlotKind::LetValue(def));
            if valid
                && self.user_body(def, 0) == Some(definition.body)
                && tuples[definition.body.index()]
            {
                push(&mut context.slots, (slot, def))?;
            }
        }
        context.slots.sort_unstable();
        Ok(context)
    }

    fn local_tuple(&self, expr: ExprId, context: &Lexical) -> bool {
        let Expr::Local(local) = self.ev.ir().expr(expr) else {
            return false;
        };
        local.up == 0
            && context.slots.iter().any(|(slot, def)| {
                *slot == local.slot
                    && matches!(self.ev.ir().def(*def).scope,
                dive_ir::DefScope::LetValue { parent, slot: bound, .. }
                    if Some(parent) == context.frame && bound == local.slot)
            })
    }
}

// Facts arise only from an actually entered LET. They never populate the global
// expression result vector, and roots/user-definition bodies start empty.
#[derive(Default, PartialEq, Eq)]
struct Lexical {
    frame: Option<DefId>,
    slots: Vec<(dive_ir::Slot, DefId)>,
}

struct Sources {
    exprs: Vec<ExprId>,
    scalar_callbacks: bool,
}

enum Capture {
    Environment(Env),
    Slot(Sv),
    Value(Value),
    State(StateRef),
}

#[derive(Default)]
struct Retained {
    frames: Vec<Arc<Frame>>,
    links: Vec<Arc<SubstLink>>,
    functions: Vec<Fcn>,
    sets: Vec<Set>,
    thunks: Vec<Arc<Thunk>>,
    states: Vec<Arc<[Option<Value>]>>,
    scalar_callbacks: bool,
}

impl Analysis<'_> {
    fn captures(&self, roots: &[(ExprId, Scope)]) -> Result<Option<Sources>> {
        let mut work = Vec::new();
        let mut sources = Vec::new();
        let mut retained = Retained::default();
        for (expr, scope) in roots {
            self.poll()?;
            if !Arc::ptr_eq(&scope.owner, &self.ev.core.ir)
                || !Arc::ptr_eq(&scope.names, &self.ev.core.names)
                || !scope.context.ptr_eq(&Arc::downgrade(&self.ev.core))
            {
                return Ok(None);
            }
            push(&mut sources, *expr)?;
            if let Some(wrapper) = scope.wrapper {
                push(&mut sources, wrapper)?;
            }
            push(&mut work, Capture::Environment(scope.env.clone()))?;
        }
        for value in self.ev.core.def_values.values() {
            push(&mut work, Capture::Value(value.clone()))?;
        }
        for value in self.ev.core.startup.iter().chain(&self.ev.core.def_cache) {
            if let Some(value) = value.get() {
                push(&mut work, Capture::Value(value.clone()))?;
            }
        }
        for binding in self.ev.core.consts.iter().flatten() {
            if let ConstBinding::Value(value) = binding {
                push(&mut work, Capture::Value(value.clone()))?;
            }
        }
        while let Some(task) = work.pop() {
            self.poll()?;
            let known = match task {
                Capture::Environment(env) => {
                    self.capture_environment(env, &mut work, &mut retained)?
                }
                Capture::Slot(slot) => {
                    self.capture_slot(slot, &mut work, &mut sources, &mut retained)?
                }
                Capture::Value(value) => self.capture_value(value, &mut work, &mut retained)?,
                Capture::State(StateRef::Null | StateRef::Empty) => true,
                Capture::State(StateRef::Vals(values)) => {
                    if !retained
                        .states
                        .iter()
                        .any(|prior| Arc::ptr_eq(prior, &values))
                    {
                        push(&mut retained.states, values.clone())?;
                        for value in values.iter().flatten() {
                            push(&mut work, Capture::Value(value.clone()))?;
                        }
                    }
                    true
                }
                Capture::State(StateRef::Named(_)) => false,
            };
            if !known {
                return Ok(None);
            }
        }
        Ok(Some(Sources {
            exprs: sources,
            scalar_callbacks: retained.scalar_callbacks,
        }))
    }

    fn capture_environment(
        &self,
        env: Env,
        work: &mut Vec<Capture>,
        retained: &mut Retained,
    ) -> Result<bool> {
        if env.dynamic.at.is_some() || env.dynamic.cut.is_some() {
            return Ok(false);
        }
        let mut link = env.dynamic.subst.clone();
        while let Some(current) = link.take() {
            self.poll()?;
            if retained
                .links
                .iter()
                .any(|prior| Arc::ptr_eq(prior, &current))
            {
                break;
            }
            push(&mut retained.links, current.clone())?;
            push(work, Capture::Slot(current.val.clone()))?;
            link.clone_from(&current.next);
        }
        let mut frame = Some(env.frame);
        while let Some(current) = frame.take() {
            self.poll()?;
            if retained
                .frames
                .iter()
                .any(|prior| Arc::ptr_eq(prior, &current))
            {
                break;
            }
            push(&mut retained.frames, current.clone())?;
            let Some(definition) = self.ev.ir().defs().get(current.def.index()) else {
                return Ok(false);
            };
            for (index, slot) in current.slots.iter().enumerate() {
                if definition.params.get(index).is_some_and(|p| p.arity != 0)
                    && !matches!(slot, Sv::Op(_))
                {
                    return Ok(false); // An opaque operator root is not forwarding.
                }
                push(work, Capture::Slot(slot.clone()))?;
            }
            frame.clone_from(&current.parent);
        }
        Ok(true)
    }

    fn capture_slot(
        &self,
        slot: Sv,
        work: &mut Vec<Capture>,
        sources: &mut Vec<ExprId>,
        retained: &mut Retained,
    ) -> Result<bool> {
        self.poll()?;
        match slot {
            Sv::Thunk(thunk) => {
                if retained
                    .thunks
                    .iter()
                    .any(|prior| Arc::ptr_eq(prior, &thunk))
                {
                    return Ok(true);
                }
                push(&mut retained.thunks, thunk.clone())?;
                push(sources, thunk.expr)?;
                push(work, Capture::Environment(thunk.env.clone()))?;
                for cache in thunk.stored_caches().into_iter().flatten() {
                    let (Ev::V(value), before, after) = cache else {
                        return Ok(false);
                    };
                    push(work, Capture::Value(value))?;
                    push(work, Capture::State(before))?;
                    push(work, Capture::State(after))?;
                }
            }
            Sv::Val(value) => push(work, Capture::Value(value))?,
            Sv::Unset | Sv::AnalysisBound | Sv::AnalysisConstant => {}
            Sv::Op(op) if self.scalar_operator(&op) => retained.scalar_callbacks = true,
            Sv::Fcn(_) | Sv::Op(_) => return Ok(false),
        }
        Ok(true)
    }

    fn capture_value(
        &self,
        value: Value,
        work: &mut Vec<Capture>,
        retained: &mut Retained,
    ) -> Result<bool> {
        match value {
            Value::Fcn(function) => {
                if retained
                    .functions
                    .iter()
                    .any(|prior| prior.ptr_eq(&function))
                {
                    return Ok(true);
                }
                push(&mut retained.functions, function.clone())?;
                for (key, value) in function.iter() {
                    self.poll()?;
                    push(work, Capture::Value(key))?;
                    push(work, Capture::Value(value.clone()))?;
                }
            }
            Value::Set(set) => {
                // A warm provider is still opaque. Inspect representation before
                // any cached payload, without asking the provider about itself.
                if !matches!(
                    set.kind(),
                    SetKind::Raw
                        | SetKind::Enum
                        | SetKind::Interval
                        | SetKind::Nat
                        | SetKind::Int
                        | SetKind::Strings
                ) {
                    return Ok(false);
                }
                if retained.sets.iter().any(|prior| prior.ptr_eq(&set)) {
                    return Ok(true);
                }
                push(&mut retained.sets, set.clone())?;
                if matches!(set.kind(), SetKind::Raw | SetKind::Enum) {
                    let Some(values) = set.stored_elements() else {
                        return Ok(false);
                    };
                    for value in values {
                        self.poll()?;
                        push(work, Capture::Value(value.clone()))?;
                    }
                }
            }
            _ => {}
        }
        Ok(true)
    }
}