Skip to main content

dive_eval/
random_relation.rs

1//! A direct native choice relation, separate from ordinary random evaluation.
2
3use dive_ir::{Arg, Expr, OpRef, StdOp};
4use dive_value::{SetKind, Value};
5
6use crate::env::control;
7use crate::{
8    ContextError, ContextErrorKind, Ec, EvalError, Evaluator, Result, Scope, St, StateRef,
9};
10
11const STORED_ENTRY_LIMIT: usize = 65_536;
12
13impl Evaluator {
14    /// Tests the support of one direct native `RandomElement(S)` application.
15    ///
16    /// This evaluates the actual argument in `scope` and `st`, then checks
17    /// `candidate` against an interval or a stored finite scalar set. It never
18    /// invokes a random host or returns a candidate to ordinary evaluation.
19    /// `None` means the expression is outside this relation operation (including
20    /// aliases, configured native redirects and surrounding expressions).
21    /// Callers must separately enforce single-occurrence, startup and complete
22    /// predicate contracts. This operation is not a purity certificate.
23    ///
24    /// The state must be constant context, or Init context with the correct number
25    /// of entirely unassigned slots and no successor. Candidates are scalar:
26    /// strings/model values must have tokens resolving to the same exact text
27    /// in this evaluator. Compound candidates refuse before domain evaluation.
28    ///
29    /// `limit` bounds stored-set entries before normalization, capped at 65,536;
30    /// intervals use exact bounds without enumeration. Stored entries obey the
31    /// same flat scalar/token check. Compound/deferred sets remain unsupported.
32    /// Normal argument evaluation can execute effects under the installed host;
33    /// this operation itself supplies no host authority or purity certificate.
34    ///
35    /// ```
36    /// use std::sync::Arc;
37    /// use dive_eval::{Evaluator, Model, Options, St};
38    /// let source = "---- MODULE M ----\nEXTENDS TLC\nChoice == RandomElement({7})\n====\n";
39    /// let analysis = dive_sema::analyze_source("M.tla", source, &Default::default());
40    /// let ir = Arc::new(dive_ir::lower(&analysis).unwrap());
41    /// let choice = ir.root_def("Choice").unwrap();
42    /// let expr = ir.def(choice).body;
43    /// let ev = Evaluator::new(Model::new(ir), Options::tlc()).unwrap();
44    /// let scope = ev.scope(choice).unwrap();
45    /// assert_eq!(ev.random_element_member(&scope, expr, &St::constant(), &7.into(), 10).unwrap(), Some(true));
46    /// assert_eq!(ev.random_element_member(&scope, expr, &St::constant(), &8.into(), 10).unwrap(), Some(false));
47    /// ```
48    ///
49    /// # Errors
50    /// Foreign context/value, argument evaluation errors, native empty/non-set
51    /// domain errors, unsupported domains, comparison errors or entry limits.
52    pub fn random_element_member(
53        &self,
54        scope: &Scope,
55        expr: dive_ir::ExprId,
56        st: &St,
57        candidate: &Value,
58        limit: usize,
59    ) -> Result<Option<bool>> {
60        self.validate_scope(scope)?;
61        self.admit_scoped_expr(scope, expr)?;
62        self.validate_state_context(st)?;
63        self.random_relation_state(st)?;
64        let Expr::Apply { callee, args } = self.core.ir.expr(expr) else {
65            return Ok(None);
66        };
67        let direct = match callee {
68            OpRef::Std(op) => *op == StdOp::TlcRandomElement,
69            OpRef::Def(def) => {
70                self.core.redirect(*def) == *def
71                    && self.core.ir.def(*def).std == Some(StdOp::TlcRandomElement)
72                    && !self.is_value_override(*def)
73            }
74            _ => false,
75        };
76        if !direct
77            || self
78                .core
79                .std_redirects
80                .contains_key(&StdOp::TlcRandomElement)
81        {
82            return Ok(None);
83        }
84        // Non-direct expressions delegate without granting relation authority.
85        // In particular, a pure compound Init must keep its deterministic path.
86        self.random_relation_scalar(candidate, "RandomElement relation compound candidate")?;
87        let [Arg::Expr { expr: domain, .. }] = args.as_ref() else {
88            return Err(EvalError::unsupported(
89                "direct RandomElement relation arity",
90            ));
91        };
92        // Ordinary argument evaluation retains its errors and runtime effects.
93        let domain = self.eval_scoped(scope, *domain, st)?;
94        let wrong = || {
95            EvalError::eval_exception(
96                Ec::ApplyingToWrongValue,
97                format!(
98                    "Applying RandomElement to the following value,\nwhich is not a finite set:\n{}",
99                    self.core.ppr(&domain)
100                ),
101            )
102        };
103        let Value::Set(set) = &domain else {
104            // Formatting a function can force a deferred value nested within it.
105            // Keep the native wrong-domain class without visiting its contents.
106            if matches!(&domain, Value::Fcn(_)) {
107                return Err(EvalError::eval_exception(
108                    Ec::ApplyingToWrongValue,
109                    "Applying RandomElement to a function value, which is not a finite set.",
110                ));
111            }
112            return Err(wrong());
113        };
114        match set.kind() {
115            SetKind::Nat | SetKind::Int | SetKind::Strings => return Err(wrong()),
116            SetKind::Interval => {
117                let size = set
118                    .size(self.core.ctx)
119                    .map_err(|e| self.core.wrap_override(StdOp::TlcRandomElement, e.into()))?;
120                if size == 0 {
121                    return Err(self.core.wrap_override(StdOp::TlcRandomElement, EvalError::general(format!(
122                        "Attempted to retrieve out-of-bounds element from the interval value {}.", self.core.ppr(&domain)
123                    ))));
124                }
125            }
126            SetKind::Enum | SetKind::Raw => {
127                // Observe only the actual explicit storage, including Raw sets
128                // that already have a normalized cache. Never enumerate Deferred.
129                let Some(stored) = set.stored_elements() else {
130                    return Err(EvalError::unsupported(
131                        "RandomElement relation has no stored scalar entries",
132                    ));
133                };
134                if stored.len() > limit.min(STORED_ENTRY_LIMIT) {
135                    return Err(EvalError::resource_limit(
136                        "RandomElement relation stored-set entries",
137                    ));
138                }
139                for entry in stored {
140                    self.random_relation_scalar(
141                        entry,
142                        "RandomElement relation compound stored element",
143                    )?;
144                }
145                // Every immediate entry was checked before normalization or member.
146                // Keep the normal comparator, normalization order and error class.
147                let values = set
148                    .elements(self.core.ctx)
149                    .map_err(|e| self.core.wrap_override(StdOp::TlcRandomElement, e.into()))?;
150                if values.is_empty() {
151                    return Err(self.core.wrap_override(
152                        StdOp::TlcRandomElement,
153                        EvalError::general("Index 0 out of bounds for length 0"),
154                    ));
155                }
156            }
157            _ => {
158                return Err(EvalError::unsupported(
159                    "RandomElement relation requires an interval or stored finite scalar set",
160                ));
161            }
162        }
163        self.core.member(candidate, &domain).map(Some)
164    }
165
166    fn random_relation_state(&self, st: &St) -> Result<()> {
167        let allowed = match (&st.s0, &st.s1, st.control) {
168            (StateRef::Empty, StateRef::Empty, control::CONST) => true,
169            (StateRef::Vals(slots), StateRef::Empty, control::INIT) => {
170                slots.len() == self.core.ir.vars().len() && slots.iter().all(Option::is_none)
171            }
172            _ => false,
173        };
174        if allowed {
175            Ok(())
176        } else {
177            Err(ContextError::new(
178                ContextErrorKind::Structure,
179                "RandomElement relation requires Const or empty Init with correct slots and no successor",
180            )
181            .into())
182        }
183    }
184
185    fn random_relation_scalar(&self, value: &Value, compound: &'static str) -> Result<()> {
186        match value {
187            Value::Bool(_) | Value::Int(_) | Value::BigInt(_) => Ok(()),
188            Value::Str(atom) | Value::Model(atom) => {
189                if self
190                    .core
191                    .names
192                    .resolve(atom.tok())
193                    .is_some_and(|owned| owned.as_str() == atom.as_str())
194                {
195                    Ok(())
196                } else {
197                    Err(ContextError::new(
198                        ContextErrorKind::ForeignContext,
199                        "RandomElement relation scalar token does not resolve to its exact text",
200                    )
201                    .into())
202                }
203            }
204            Value::Set(_) | Value::Fcn(_) => Err(EvalError::unsupported(compound)),
205        }
206    }
207}
208
209#[cfg(test)]
210mod tests {
211    #![allow(clippy::expect_used, clippy::panic, reason = "test fixture assertions")]
212
213    use std::fmt;
214    use std::sync::Arc;
215    use std::sync::atomic::{AtomicUsize, Ordering};
216
217    use dive_ir::ExprId;
218    use dive_value::{Ctx, DeferredKind, DeferredSet, Int, IntMode, Interner, Value};
219
220    use crate::{
221        ConstBinding, Ec, ErrorClass, Evaluator, Host, HostError, Model, Options, PrintSink, Scope,
222        St, StateRef,
223    };
224
225    const SOURCE: &str = "---- MODULE Relation ----\nEXTENDS Naturals, TLC\nCONSTANT Domain\nVARIABLE x\nChoice == RandomElement(Domain)\nEffectChoice == RandomElement(IF PrintT(TRUE) THEN Domain ELSE Domain)\nParam(v) == RandomElement(v)\nUsesVar == RandomElement({x})\nPure == 7\n====\n";
226
227    #[derive(Default)]
228    struct Sink(AtomicUsize);
229    impl PrintSink for Sink {
230        fn print(&self, _: String) {
231            self.0.fetch_add(1, Ordering::SeqCst);
232        }
233    }
234
235    #[derive(Default)]
236    struct Callbacks(AtomicUsize);
237    impl fmt::Debug for Callbacks {
238        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
239            self.0.fetch_add(1, Ordering::SeqCst);
240            f.write_str("callback-counted deferred source")
241        }
242    }
243    impl DeferredSet for Callbacks {
244        fn kind(&self) -> DeferredKind {
245            self.0.fetch_add(1, Ordering::SeqCst);
246            DeferredKind::Filter
247        }
248        fn elements(&self, _: Ctx) -> dive_value::Result<Vec<Value>> {
249            self.0.fetch_add(1, Ordering::SeqCst);
250            Ok(vec![Value::Int(7)])
251        }
252        fn member(&self, _: &Value, _: Ctx) -> Option<dive_value::Result<bool>> {
253            self.0.fetch_add(1, Ordering::SeqCst);
254            Some(Ok(true))
255        }
256        fn key(&self) -> Vec<Value> {
257            self.0.fetch_add(1, Ordering::SeqCst);
258            vec![Value::Int(7)]
259        }
260    }
261
262    #[derive(Debug, Default)]
263    struct Draws(AtomicUsize);
264    impl Host for Draws {
265        fn random(
266            &self,
267            _: dive_ir::StdOp,
268            _: &[Value],
269            _: Ctx,
270        ) -> Option<Result<Value, HostError>> {
271            self.0.fetch_add(1, Ordering::SeqCst);
272            Some(Ok(Value::Int(7)))
273        }
274    }
275
276    struct Fixture {
277        ev: Evaluator,
278        names: Arc<Interner>,
279        sink: Arc<Sink>,
280        ctx: Ctx,
281    }
282    impl Fixture {
283        fn new(tlc: bool, domain: impl FnOnce(&Interner, Ctx) -> Value) -> Self {
284            let analysis =
285                dive_sema::analyze_source("Relation.tla", SOURCE, &dive_sema::Options::default());
286            assert!(analysis.accepted(), "{:?}", analysis.diagnostics());
287            let ir = Arc::new(dive_ir::lower(&analysis).expect("IR"));
288            let mut model = Model::new(ir);
289            let options = if tlc { Options::tlc() } else { Options::dive() };
290            let ctx = options.ctx;
291            model.constants[0] = Some(ConstBinding::Value(domain(&model.names, ctx)));
292            let names = model.names.clone();
293            let sink = Arc::new(Sink::default());
294            let ev = Evaluator::with_sink(model, options, sink.clone()).expect("evaluator");
295            Self {
296                ev,
297                names,
298                sink,
299                ctx,
300            }
301        }
302        fn predicate(&self, name: &str) -> (Scope, ExprId) {
303            let def = self.ev.ir().root_def(name).expect("definition");
304            (
305                self.ev.scope(def).expect("scope"),
306                self.ev.ir().def(def).body,
307            )
308        }
309        fn member(
310            &self,
311            name: &str,
312            st: &St,
313            candidate: &Value,
314            limit: usize,
315        ) -> crate::Result<Option<bool>> {
316            let (scope, expr) = self.predicate(name);
317            self.ev
318                .random_element_member(&scope, expr, st, candidate, limit)
319        }
320    }
321    fn empty_init() -> St {
322        St::initial(Arc::from([None]))
323    }
324    fn error_code(result: crate::Result<Option<bool>>, code: &str) {
325        let error = result.expect_err("relation must reject input");
326        assert!(error.message().contains(code), "{error}");
327    }
328    fn foreign(names: &Interner, mode: usize) -> Value {
329        let target = names.intern("owned scalar");
330        let source = Interner::new();
331        let token = match mode {
332            0 => usize::try_from(target.tok()).expect("token fits usize") + 1,
333            1 | 3 => usize::try_from(target.tok()).expect("token fits usize"),
334            _ => names.len() + 1,
335        };
336        for index in 0..token {
337            source.intern(&format!("foreign filler {index}"));
338        }
339        Value::string(
340            &source,
341            if mode == 1 {
342                "different scalar"
343            } else {
344                "owned scalar"
345            },
346        )
347    }
348
349    #[test]
350    fn foreign_scalar_candidate_checks_precede_effects_in_both_profiles() {
351        for tlc in [false, true] {
352            let fixture = Fixture::new(tlc, |names, ctx| {
353                Value::set_raw(vec![Value::string(names, "owned scalar")], ctx)
354            });
355            for mode in 0..3 {
356                for model_value in [false, true] {
357                    let candidate = foreign(&fixture.names, mode);
358                    let candidate = if model_value {
359                        let Value::Str(atom) = candidate else {
360                            panic!("scalar")
361                        };
362                        Value::Model(atom)
363                    } else {
364                        candidate
365                    };
366                    let before = fixture.names.len();
367                    error_code(
368                        fixture.member("EffectChoice", &empty_init(), &candidate, 10),
369                        "C004",
370                    );
371                    assert_eq!(fixture.names.len(), before);
372                    assert_eq!(fixture.sink.0.load(Ordering::SeqCst), 0);
373                }
374            }
375            // Different Arc ownership is harmless when both token and text agree.
376            let candidate = foreign(&fixture.names, 3);
377            assert_eq!(
378                fixture
379                    .member("Choice", &St::constant(), &candidate, 10)
380                    .expect("matching token/text"),
381                Some(true)
382            );
383            assert_eq!(
384                fixture
385                    .member("EffectChoice", &empty_init(), &candidate, 10)
386                    .expect("normal domain evaluation"),
387                Some(true)
388            );
389            assert_eq!(fixture.sink.0.load(Ordering::SeqCst), 1);
390        }
391    }
392
393    #[test]
394    fn compound_candidates_refuse_before_domain_or_deferred_callbacks() {
395        for tlc in [false, true] {
396            let fixture = Fixture::new(tlc, |_, ctx| Value::set_raw(vec![Value::Int(7)], ctx));
397            for cached in [false, true] {
398                let calls = Arc::new(Callbacks::default());
399                let deferred = Value::deferred(calls.clone(), fixture.ctx);
400                if cached {
401                    let Value::Set(set) = &deferred else {
402                        panic!("set")
403                    };
404                    set.elements(fixture.ctx).expect("prime cache explicitly");
405                }
406                let candidates = [
407                    deferred.clone(),
408                    Value::tuple(vec![deferred.clone()]),
409                    Value::set_raw(vec![deferred.clone()], fixture.ctx),
410                ];
411                // Tuple construction can inspect deferred keys. Only the
412                // relation operation must add no callbacks to this baseline.
413                let before = calls.0.load(Ordering::SeqCst);
414                for candidate in candidates {
415                    let count = fixture.names.len();
416                    let error = fixture
417                        .member("EffectChoice", &empty_init(), &candidate, 10)
418                        .expect_err("compound candidate");
419                    assert_eq!(error.class(), ErrorClass::Unsupported);
420                    assert!(error.message().contains("compound candidate"));
421                    assert_eq!(fixture.sink.0.load(Ordering::SeqCst), 0);
422                    assert_eq!(calls.0.load(Ordering::SeqCst), before);
423                    assert_eq!(fixture.names.len(), count);
424                }
425            }
426        }
427    }
428
429    #[test]
430    fn state_contract_refuses_assigned_foreign_deferred_and_invalid_contexts_before_effects() {
431        for tlc in [false, true] {
432            let fixture = Fixture::new(tlc, |_, ctx| Value::set_raw(vec![Value::Int(7)], ctx));
433            let calls = Arc::new(Callbacks::default());
434            let mut constant_with_assignment = St::constant();
435            constant_with_assignment.s0 = StateRef::Vals(Arc::from([Some(Value::Int(7))]));
436            let mut init_with_successor = empty_init();
437            init_with_successor.s1 = StateRef::Vals(Arc::from([None]));
438            let mut null_initial = empty_init();
439            null_initial.s0 = StateRef::Null;
440            let mut null_successor = empty_init();
441            null_successor.s1 = StateRef::Null;
442            for state in [
443                St::empty(),
444                St::default(),
445                St::state(Arc::from([None])),
446                St::state(Arc::from([Some(Value::Int(7))])),
447                St::initial(Arc::from([Some(foreign(&fixture.names, 0))])),
448                St::initial(Arc::from([Some(Value::deferred(
449                    calls.clone(),
450                    fixture.ctx,
451                ))])),
452                St::initial(Arc::from([])),
453                St::initial(Arc::from([None, None])),
454                St::action(Arc::from([None]), Arc::from([None])),
455                empty_init().keep_lazy(),
456                constant_with_assignment,
457                init_with_successor,
458                null_initial,
459                null_successor,
460            ] {
461                let count = fixture.names.len();
462                error_code(
463                    fixture.member("EffectChoice", &state, &Value::Int(7), 10),
464                    "C005",
465                );
466                assert_eq!(fixture.sink.0.load(Ordering::SeqCst), 0);
467                assert_eq!(calls.0.load(Ordering::SeqCst), 0);
468                assert_eq!(fixture.names.len(), count);
469            }
470            for state in [St::constant(), empty_init()] {
471                assert_eq!(
472                    fixture
473                        .member("Choice", &state, &Value::Int(7), 10)
474                        .expect("supported context"),
475                    Some(true)
476                );
477            }
478            let error = fixture
479                .member("UsesVar", &empty_init(), &Value::Int(7), 10)
480                .expect_err("missing variable stays unassigned");
481            assert_eq!(error.class(), ErrorClass::Eval);
482            assert_eq!(fixture.sink.0.load(Ordering::SeqCst), 0);
483            assert_eq!(calls.0.load(Ordering::SeqCst), 0);
484        }
485    }
486
487    #[test]
488    fn context_and_expression_guards_win_before_value_guards_and_domain_effects() {
489        for tlc in [false, true] {
490            let fixture = Fixture::new(tlc, |_, ctx| Value::set_raw(vec![Value::Int(7)], ctx));
491            let other = Fixture::new(tlc, |_, ctx| Value::set_raw(vec![Value::Int(7)], ctx));
492            let (scope, expression) = fixture.predicate("EffectChoice");
493            let (foreign_scope, _) = other.predicate("EffectChoice");
494            let compound = Value::tuple(vec![Value::Int(7)]);
495            error_code(
496                fixture.ev.random_element_member(
497                    &foreign_scope,
498                    expression,
499                    &St::empty(),
500                    &compound,
501                    10,
502                ),
503                "C004",
504            );
505            error_code(
506                fixture.ev.random_element_member(
507                    &scope,
508                    ExprId(u32::MAX),
509                    &St::empty(),
510                    &compound,
511                    10,
512                ),
513                "C001",
514            );
515            let (_, parameter_body) = fixture.predicate("Param");
516            error_code(
517                fixture.ev.random_element_member(
518                    &scope,
519                    parameter_body,
520                    &St::constant(),
521                    &compound,
522                    10,
523                ),
524                "C005",
525            );
526            assert_eq!(fixture.sink.0.load(Ordering::SeqCst), 0);
527            assert_eq!(other.sink.0.load(Ordering::SeqCst), 0);
528        }
529    }
530
531    #[test]
532    fn stored_foreign_entries_reject_raw_cached_raw_and_enum_before_member() {
533        for tlc in [false, true] {
534            for mode in 0..3 {
535                for representation in 0..3 {
536                    for model_value in [false, true] {
537                        let fixture = Fixture::new(tlc, |names, ctx| {
538                            let candidate = foreign(names, mode);
539                            let entry = if model_value {
540                                let Value::Str(atom) = candidate else {
541                                    panic!("scalar")
542                                };
543                                Value::Model(atom)
544                            } else {
545                                candidate
546                            };
547                            if representation == 2 {
548                                Value::set(vec![entry], ctx).expect("single stored entry")
549                            } else {
550                                let value = Value::set_raw(vec![entry], ctx);
551                                if representation == 1 {
552                                    let Value::Set(set) = &value else {
553                                        panic!("set")
554                                    };
555                                    set.elements(ctx).expect("prime normalization explicitly");
556                                }
557                                value
558                            }
559                        });
560                        let count = fixture.names.len();
561                        error_code(
562                            fixture.member("Choice", &St::constant(), &Value::Int(7), 10),
563                            "C004",
564                        );
565                        assert_eq!(fixture.names.len(), count);
566                        assert_eq!(fixture.sink.0.load(Ordering::SeqCst), 0);
567                    }
568                }
569            }
570        }
571    }
572
573    #[test]
574    fn deferred_domains_and_compound_stored_entries_refuse_without_callbacks_even_if_cached() {
575        for tlc in [false, true] {
576            for representation in 0..4 {
577                for cached in [false, true] {
578                    let calls = Arc::new(Callbacks::default());
579                    let fixture = Fixture::new(tlc, |_, ctx| {
580                        let deferred = Value::deferred(calls.clone(), ctx);
581                        if cached {
582                            let Value::Set(set) = &deferred else {
583                                panic!("set")
584                            };
585                            set.elements(ctx).expect("prime deferred cache explicitly");
586                        }
587                        match representation {
588                            0 => deferred,
589                            1 => Value::set_raw(vec![deferred], ctx),
590                            2 => Value::set_raw(vec![Value::tuple(vec![deferred])], ctx),
591                            _ => Value::set(vec![Value::tuple(vec![deferred])], ctx)
592                                .expect("single compound enum entry"),
593                        }
594                    });
595                    let before = calls.0.load(Ordering::SeqCst);
596                    let error = fixture
597                        .member("Choice", &St::constant(), &Value::Int(7), 10)
598                        .expect_err("unsupported domain");
599                    assert_eq!(error.class(), ErrorClass::Unsupported);
600                    assert_eq!(calls.0.load(Ordering::SeqCst), before);
601                    assert_eq!(fixture.sink.0.load(Ordering::SeqCst), 0);
602                }
603            }
604        }
605    }
606
607    #[test]
608    fn wrong_function_domain_preserves_native_class_without_formatting_nested_deferred_values() {
609        for tlc in [false, true] {
610            let calls = Arc::new(Callbacks::default());
611            let fixture = Fixture::new(tlc, |_, ctx| {
612                Value::tuple(vec![Value::deferred(calls.clone(), ctx)])
613            });
614            let before = calls.0.load(Ordering::SeqCst);
615            let error = fixture
616                .member("Choice", &St::constant(), &Value::Int(7), 10)
617                .expect_err("not a set");
618            assert_eq!(error.class(), ErrorClass::Eval);
619            assert_eq!(error.ec(), Ec::ApplyingToWrongValue);
620            assert_eq!(calls.0.load(Ordering::SeqCst), before);
621        }
622    }
623
624    #[test]
625    fn domain_budget_counts_storage_before_dedup_and_has_a_hard_ceiling() {
626        for tlc in [false, true] {
627            for cached in [false, true] {
628                let fixture = Fixture::new(tlc, |_, ctx| {
629                    let value = Value::set_raw(vec![Value::Int(7); 3], ctx);
630                    if cached {
631                        let Value::Set(set) = &value else {
632                            panic!("set")
633                        };
634                        set.elements(ctx).expect("prime deduplicated cache");
635                    }
636                    value
637                });
638                let error = fixture
639                    .member("Choice", &St::constant(), &Value::Int(7), 2)
640                    .expect_err("raw storage is three entries");
641                assert_eq!(error.class(), ErrorClass::ResourceLimit);
642            }
643            let fixture = Fixture::new(tlc, |_, ctx| {
644                Value::set_raw(vec![Value::Int(7); 65_537], ctx)
645            });
646            assert_eq!(
647                fixture
648                    .member("Choice", &St::constant(), &Value::Int(7), usize::MAX)
649                    .expect_err("hard entry bound")
650                    .class(),
651                ErrorClass::ResourceLimit
652            );
653            let bounded = Fixture::new(tlc, |_, ctx| {
654                Value::set_raw(vec![Value::Int(7); 65_536], ctx)
655            });
656            assert_eq!(
657                bounded
658                    .member("Choice", &St::constant(), &Value::Int(7), usize::MAX)
659                    .expect("exact bound"),
660                Some(true)
661            );
662        }
663    }
664
665    #[test]
666    fn owned_model_true_is_not_bool_true_and_member_keeps_profile_errors() {
667        for tlc in [false, true] {
668            let fixture = Fixture::new(tlc, |_, ctx| Value::interval(1.into(), 10.into(), ctx));
669            let owned_model = Value::model(&fixture.names, "TRUE");
670            assert_eq!(
671                fixture
672                    .member("Choice", &empty_init(), &owned_model, 10)
673                    .expect("owned untyped Model TRUE"),
674                Some(false)
675            );
676            let error = fixture
677                .member("Choice", &empty_init(), &Value::TRUE, 10)
678                .expect_err("Bool TRUE is a typed membership error");
679            assert_eq!(error.class(), ErrorClass::Eval);
680            assert_eq!(error.ec(), Ec::General);
681            let typed_model = Value::model(&fixture.names, "A_value");
682            assert_eq!(
683                fixture
684                    .member("Choice", &empty_init(), &typed_model, 10)
685                    .expect_err("typed model interval error")
686                    .ec(),
687                Ec::General
688            );
689            let raw = Fixture::new(tlc, |names, ctx| {
690                Value::set_raw(
691                    vec![Value::Int(7), Value::string(names, "owned scalar")],
692                    ctx,
693                )
694            });
695            let error = raw
696                .member("Choice", &St::constant(), &Value::Int(7), 10)
697                .expect_err("native normalization comparability error");
698            assert_eq!(error.class(), ErrorClass::Eval);
699            assert_eq!(error.ec(), Ec::JavaMethodOverride);
700        }
701    }
702
703    #[test]
704    fn scalar_support_never_calls_random_host_and_big_integer_is_not_a_compound_value() {
705        for tlc in [false, true] {
706            let fixture = Fixture::new(tlc, |_, ctx| Value::set_raw(vec![Value::Int(7)], ctx));
707            let calls = Arc::new(Draws::default());
708            fixture.ev.set_host(calls.clone());
709            assert_eq!(
710                fixture
711                    .member("Choice", &empty_init(), &Value::Int(7), 10)
712                    .expect("support membership"),
713                Some(true)
714            );
715            assert_eq!(
716                fixture
717                    .member("Choice", &empty_init(), &Value::Int(8), 10)
718                    .expect("support exclusion"),
719                Some(false)
720            );
721            assert_eq!(calls.0.load(Ordering::SeqCst), 0);
722        }
723        let large = Value::int(
724            Int::from_literal("9223372036854775808", IntMode::Big).expect("big integer"),
725        );
726        assert!(matches!(&large, Value::BigInt(_)));
727        let fixture = Fixture::new(false, |_, ctx| Value::set_raw(vec![large.clone()], ctx));
728        assert_eq!(
729            fixture
730                .member("Choice", &St::constant(), &large, 10)
731                .expect("big scalar"),
732            Some(true)
733        );
734    }
735
736    #[test]
737    fn non_direct_expression_delegates_without_inspecting_a_compound_candidate() {
738        let fixture = Fixture::new(true, |_, ctx| Value::set_raw(vec![Value::Int(7)], ctx));
739        let calls = Arc::new(Callbacks::default());
740        let candidate = Value::deferred(calls.clone(), fixture.ctx);
741        assert_eq!(
742            fixture
743                .member("Pure", &empty_init(), &candidate, 10)
744                .expect("not a direct native call"),
745            None
746        );
747        assert_eq!(calls.0.load(Ordering::SeqCst), 0);
748        assert_eq!(fixture.sink.0.load(Ordering::SeqCst), 0);
749    }
750}