Skip to main content

dive_model/
bind.rs

1//! Binding the configuration's constants and overrides
2//! (`SpecProcessor.processSpec`) and evaluating constant definitions at
3//! start-up (`processConstantDefns`), in TLC's order.
4
5use std::collections::{HashMap, HashSet};
6use std::io::Read;
7use std::path::Path;
8use std::sync::Arc;
9
10use sha2::{Digest, Sha256};
11
12use dive_config::{ConfigValue, ConstantEntry, ModelConfig, Spanned};
13use dive_eval::{ConstBinding, ErrorClass, Evaluator, Options};
14use dive_ir::{DeclId, DefId, Ir, ModuleId, StdOp, Symbol};
15use dive_value::{Ctx, Interner, Value};
16
17use crate::error::{BindError, Ec, ErrorKind, Message};
18use crate::level::LevelCx;
19use crate::model::{Init, Named, Pred};
20use crate::tables::{Look, Tables};
21use crate::walk::{file_modules, inner_modules};
22
23pub(crate) type R<T> = Result<T, crate::control::StepError>;
24
25/// How the binding stage runs.
26#[derive(Clone, Debug)]
27pub struct BindOptions {
28    /// Whole-run policy for genuine temporal obligations and configured symmetry.
29    pub symmetry_liveness: crate::SymmetryLiveness,
30    /// The evaluator's options (the profile).
31    pub eval: Options,
32    /// TLC's `-deadlock` command-line flag: do not check for deadlock,
33    /// whatever `CHECK_DEADLOCK` says.
34    pub no_deadlock: bool,
35    /// The run hosting the evaluator ([`dive_eval::Host`]), installed before
36    /// TLC's start-up evaluation, so that constant definitions and `ASSUME`s
37    /// draw from the run's random stream and see its registers. `None`: no
38    /// host; operators that need one are refused by name.
39    pub host: Option<std::sync::Arc<dyn dive_eval::Host>>,
40}
41
42impl BindOptions {
43    /// `--compat=tlc`: TLC as users run it.
44    #[must_use]
45    pub fn tlc() -> Self {
46        Self {
47            eval: Options::tlc(),
48            symmetry_liveness: crate::SymmetryLiveness::Tlc,
49            no_deadlock: false,
50            host: None,
51        }
52    }
53
54    /// dive's default profile.
55    #[must_use]
56    pub fn dive() -> Self {
57        Self {
58            eval: Options::dive(),
59            symmetry_liveness: crate::SymmetryLiveness::Unreduced,
60            no_deadlock: false,
61            host: None,
62        }
63    }
64}
65
66impl Default for BindOptions {
67    fn default() -> Self {
68        Self::dive()
69    }
70}
71
72/// A constant's entry in TLC's constant table (`makeConstantTable`).
73enum CfgConst<'a> {
74    Plain(&'a Spanned<ConfigValue>),
75    /// A constant operator given values for some arguments (`OpRcdValue`).
76    Op,
77}
78
79/// The binder's state.
80pub(crate) struct Binder<'a> {
81    pub(crate) control: Option<Arc<dyn dive_eval::HostControl>>,
82    pub(crate) t: Tables,
83    pub(crate) cfg: &'a ModelConfig,
84    pub(crate) opts: &'a BindOptions,
85    pub(crate) names: Arc<Interner>,
86    /// TLC's `defns`: the names the configuration is looked up in.
87    pub(crate) defns: HashMap<String, Look>,
88    pub(crate) output: Vec<Message>,
89    pub(crate) init: Vec<Init>,
90    pub(crate) next: Option<Pred>,
91    /// The definition `NEXT` names, which TLC names the next-state relation
92    /// after.
93    pub(crate) next_def: Option<DefId>,
94    pub(crate) invariants: Vec<Named>,
95    pub(crate) implied_inits: Vec<Named>,
96    pub(crate) implied_actions: Vec<Named>,
97    pub(crate) temporals: Vec<Named>,
98    pub(crate) implied_temporals: Vec<Named>,
99    pub(crate) implied_temporal_action_names: Vec<String>,
100    pub(crate) configured_properties: Vec<Named>,
101    pub(crate) constraints: Vec<Named>,
102    pub(crate) action_constraints: Vec<Named>,
103    pub(crate) unsupported: Vec<String>,
104    /// Definitions whose start-up evaluation dive refused (an unsupported
105    /// feature or a resource limit): TLC may have given them a value, so
106    /// whatever depends on that value is refused too.
107    pub(crate) refused: HashMap<DefId, String>,
108    /// Impure definitions whose start-up evaluation dive refused. Each is
109    /// refused only if the checking path reaches it or its evaluation may
110    /// have had a lasting effect in TLC (`reach::unsupported`).
111    pub(crate) startup_refusals: Vec<StartupRefusal>,
112    /// The constant definitions the start-up evaluation leaves to the core
113    /// engine (`crate::defer`); `None` unless the core route asked.
114    pub(crate) defer: Option<crate::defer::Deferral>,
115    /// The left definitions a configured role uses, which the core
116    /// evaluates.
117    pub(crate) deferred: std::collections::BTreeSet<DefId>,
118}
119
120/// A refused start-up evaluation of an impure definition.
121pub(crate) struct StartupRefusal {
122    /// The definition.
123    pub def: DefId,
124    /// The refusal, naming the definition.
125    pub what: String,
126    /// The external-input refusal that evaluation recorded, if any; restored
127    /// when the refusal is kept.
128    pub input_refusal: Option<String>,
129}
130
131impl<'a> Binder<'a> {
132    pub(crate) fn new(
133        ir: Arc<Ir>,
134        cfg: &'a ModelConfig,
135        opts: &'a BindOptions,
136        names: Arc<Interner>,
137        control: Option<Arc<dyn dive_eval::HostControl>>,
138        fallible_errors: bool,
139    ) -> R<Self> {
140        let mut tables = Tables::new(ir)?;
141        tables.fallible_errors = fallible_errors;
142        Ok(Self {
143            control,
144            t: tables,
145            cfg,
146            opts,
147            names,
148            defns: HashMap::new(),
149            output: Vec::new(),
150            init: Vec::new(),
151            next: None,
152            next_def: None,
153            invariants: Vec::new(),
154            implied_inits: Vec::new(),
155            implied_actions: Vec::new(),
156            temporals: Vec::new(),
157            implied_temporals: Vec::new(),
158            implied_temporal_action_names: Vec::new(),
159            configured_properties: Vec::new(),
160            constraints: Vec::new(),
161            action_constraints: Vec::new(),
162            unsupported: Vec::new(),
163            refused: HashMap::new(),
164            startup_refusals: Vec::new(),
165            defer: None,
166            deferred: std::collections::BTreeSet::new(),
167        })
168    }
169
170    pub(crate) fn eval_error(
171        &self,
172        error: dive_eval::EvalError,
173        to_binding: impl FnOnce(dive_eval::EvalError) -> BindError,
174    ) -> crate::control::StepError {
175        self.t.eval_error(error, to_binding)
176    }
177
178    pub(crate) fn propagate_interruption(&self, error: &dive_eval::EvalError) -> R<()> {
179        if (self.control.is_some() || self.t.fallible_errors)
180            && error.class() == ErrorClass::Interrupted
181        {
182            return Err(crate::control::StepError::Interrupted(error.clone()));
183        }
184        if self.t.fallible_errors
185            && matches!(error.class(), ErrorClass::ResourceLimit | ErrorClass::Bug)
186        {
187            return Err(crate::control::StepError::EvaluationFailure(error.clone()));
188        }
189        Ok(())
190    }
191
192    pub(crate) fn ir(&self) -> &Ir {
193        &self.t.ir
194    }
195
196    pub(crate) fn ctx(&self) -> Ctx {
197        self.opts.eval.ctx
198    }
199
200    pub(crate) fn ev(&self) -> &Evaluator {
201        self.t.ev()
202    }
203
204    /// Moves `Print` output collected by the evaluator into the output.
205    pub(crate) fn drain_prints(&mut self) {
206        for line in self.t.ev().take_output() {
207            self.output.push(Message::Print(line));
208        }
209    }
210
211    /// `Value.toString()`.
212    pub(crate) fn show(&self, v: &Value) -> String {
213        dive_value::print::to_tlc_string_lenient(v, self.ctx())
214    }
215
216    /// A configuration value as a value (`ModelConfig.parseValue`, then
217    /// `initialize`, which normalizes sets).
218    fn cfg_value(&self, v: &ConfigValue) -> R<Value> {
219        Ok(match v {
220            ConfigValue::Int(i) => Value::Int(i64::from(*i)),
221            ConfigValue::String(s) => Value::string(&self.names, s),
222            ConfigValue::Bool(b) => Value::Bool(*b),
223            ConfigValue::ModelValue(m) => Value::model(&self.names, m),
224            ConfigValue::Set(items) => {
225                let mut out = Vec::with_capacity(items.len());
226                for i in items {
227                    out.push(self.cfg_value(&i.value)?);
228                }
229                Value::set(out, self.ctx()).map_err(|e| BindError {
230                    kind: ErrorKind::Eval { code: 1000 },
231                    message: e.message().to_owned(),
232                })?
233            }
234        })
235    }
236
237    // -------------------------------------------------------------------
238    // processSpec: constants and overrides
239    // -------------------------------------------------------------------
240
241    /// `SpecProcessor.processSpec` from `initializeConstants` on.
242    #[allow(clippy::too_many_lines, reason = "TLC's sequence, step by step")]
243    pub(crate) fn process_spec(&mut self) -> R<()> {
244        let ir = self.t.ir.clone();
245        let root = ir.root();
246        // Built-in names (`processSpec`: TRUE, FALSE, BOOLEAN, the Strings
247        // class's methods).
248        self.defns
249            .insert("TRUE".into(), Look::Value(Value::Bool(true)));
250        self.defns
251            .insert("FALSE".into(), Look::Value(Value::Bool(false)));
252        self.defns.insert(
253            "BOOLEAN".into(),
254            Look::Value(Value::boolean_set(self.ctx())),
255        );
256        self.defns
257            .insert("STRING".into(), Look::Value(Value::string_set(self.ctx())));
258
259        // `initializeConstants` / `makeConstantTable`.
260        let mut table: HashMap<&str, CfgConst<'_>> = HashMap::new();
261        let mut arities: HashMap<&str, usize> = HashMap::new();
262        for a in self.cfg.assignments() {
263            let name = a.name.text.as_str();
264            if a.args.is_empty() {
265                table.insert(name, CfgConst::Plain(a.value));
266            } else {
267                if let Some(&n) = arities.get(name)
268                    && n != a.args.len()
269                {
270                    return Err(BindError::tlc(Ec::TlcConfigOpArityInconsistent, &[name]).into());
271                }
272                arities.insert(name, a.args.len());
273                table.insert(name, CfgConst::Op);
274            }
275        }
276        let overrides = self.cfg.substitutions();
277
278        // Root constants, in `getConstantDecls` order.
279        let root_consts: Vec<DeclId> = ir.module(root).tlc_constants.clone();
280        for &decl in &root_consts {
281            let d = ir.decl(decl);
282            let Some(c) = d.constant else { continue };
283            match table.get(d.name.as_str()) {
284                None => {
285                    if !overrides.contains_key(d.name.as_str()) {
286                        return Err(BindError::tlc(
287                            Ec::TlcConfigValueNotAssignedToConstantParam,
288                            &[&d.name],
289                        )
290                        .into());
291                    }
292                }
293                Some(CfgConst::Plain(v)) => {
294                    let v = self.cfg_value(&v.value)?;
295                    self.t.consts[c.index()] = Some(Look::Value(v.clone()));
296                    self.defns.insert(d.name.clone(), Look::Value(v));
297                }
298                Some(CfgConst::Op) => {
299                    return Err(BindError::unsupported(format!(
300                        "values for the constant operator {} given in the configuration (TLC's OpRcdValue)",
301                        d.name
302                    )).into());
303                }
304            }
305        }
306
307        // Root definitions, with configuration values (`Op = v`).
308        let root_defs = self.t.op_defs(root);
309        for (name, d) in &root_defs {
310            match table.get(name.as_str()) {
311                None => {
312                    self.defns.insert(name.clone(), Look::Def(*d));
313                }
314                Some(CfgConst::Plain(v)) => {
315                    if !ir.def(*d).params.is_empty() {
316                        return Err(BindError::unsupported(format!(
317                            "a value given in the configuration for the operator {name}, which takes arguments"
318                        )).into());
319                    }
320                    let v = self.cfg_value(&v.value)?;
321                    self.t.tool_obj.insert(*d, Look::Value(v.clone()));
322                    self.defns.insert(name.clone(), Look::Value(v));
323                }
324                Some(CfgConst::Op) => {
325                    return Err(BindError::unsupported(format!(
326                        "values for the operator {name} given in the configuration (TLC's OpRcdValue)"
327                    )).into());
328                }
329            }
330        }
331
332        // Module-scoped values (`C = [M] v`), on definitions' bodies.
333        let mod_assign = self.cfg.module_assignments();
334        for m in file_modules(&ir) {
335            let mname = ir.module(m).name.clone();
336            let Some(entries) = mod_assign.get(mname.as_str()) else {
337                continue;
338            };
339            let mut mtable: HashMap<&str, &Spanned<ConfigValue>> = HashMap::new();
340            let mut marity: HashMap<&str, usize> = HashMap::new();
341            for a in entries {
342                if !a.args.is_empty() {
343                    if let Some(&n) = marity.get(a.name.text.as_str())
344                        && n != a.args.len()
345                    {
346                        return Err(BindError::tlc(
347                            Ec::TlcConfigOpArityInconsistent,
348                            &[&a.name.text],
349                        )
350                        .into());
351                    }
352                    marity.insert(a.name.text.as_str(), a.args.len());
353                    return Err(BindError::unsupported(format!(
354                        "module-scoped values for the operator {} given in the configuration",
355                        a.name.text
356                    ))
357                    .into());
358                }
359                mtable.insert(a.name.text.as_str(), a.value);
360            }
361            for (name, d) in self.t.op_defs(m) {
362                if let Some(v) = mtable.get(name.as_str()) {
363                    let v = self.cfg_value(&v.value)?;
364                    self.set_body_obj(d, &Look::Value(v));
365                }
366            }
367        }
368
369        // Java overrides (`processModuleOverrides`) enter `defns` by name.
370        for (i, def) in ir.defs().iter().enumerate() {
371            if let Some(op) = def.std
372                && def.source.is_none()
373            {
374                self.defns.insert(
375                    def.name.clone(),
376                    Look::Java(op, DefId(u32::try_from(i).unwrap_or(u32::MAX))),
377                );
378            }
379        }
380        self.install_user_java_overrides();
381
382        // Overrides of root constants.
383        let mut overridden: HashSet<String> = HashSet::new();
384        for &decl in &root_consts {
385            let d = ir.decl(decl);
386            let Some(c) = d.constant else { continue };
387            let Some(rhs) = overrides.get(d.name.as_str()) else {
388                continue;
389            };
390            let rhs = rhs.text.as_str();
391            if overrides.contains_key(rhs) {
392                return Err(BindError::tlc(Ec::TlcConfigRhsIdAppearedAfterLhsId, &[rhs]).into());
393            }
394            let Some(val) = self.defns.get(rhs).cloned() else {
395                return Err(BindError::tlc(Ec::TlcConfigWrongSubstitution, &[&d.name, rhs]).into());
396            };
397            self.t.consts[c.index()] = Some(val.clone());
398            self.defns.insert(d.name.clone(), val);
399            overridden.insert(d.name.clone());
400        }
401        // Overrides of root definitions.
402        for (name, d) in &root_defs {
403            let Some(rhs) = overrides.get(name.as_str()) else {
404                continue;
405            };
406            let rhs = rhs.text.as_str();
407            if overrides.contains_key(rhs) {
408                return Err(BindError::tlc(Ec::TlcConfigRhsIdAppearedAfterLhsId, &[rhs]).into());
409            }
410            let Some(val) = self.defns.get(rhs).cloned() else {
411                return Err(BindError::tlc(Ec::TlcConfigWrongSubstitution, &[name, rhs]).into());
412            };
413            if let Look::Def(r) = &val
414                && ir.def(*d).params.len() != ir.def(*r).params.len()
415            {
416                return Err(BindError::tlc(
417                    Ec::TlcConfigWrongSubstitutionNumberOfArgs,
418                    &[name, rhs],
419                )
420                .into());
421            }
422            self.t.tool_obj.insert(*d, val.clone());
423            self.defns.insert(name.clone(), val);
424            overridden.insert(name.clone());
425        }
426        // Overrides naming nothing, in the `Hashtable`'s order.
427        let keys = override_keys(self.cfg, None);
428        for k in hashtable_order(&keys) {
429            if !overridden.contains(k.as_str()) {
430                return Err(BindError::tlc(Ec::TlcConfigIdDoesNotAppearInSpec, &[&k]).into());
431            }
432        }
433
434        // Module-scoped overrides (`C <- [M] D`), on definitions' bodies.
435        let mod_over = self.cfg.module_substitutions();
436        let module_names: Vec<String> = file_modules(&ir)
437            .iter()
438            .map(|&m| ir.module(m).name.clone())
439            .collect();
440        for m in file_modules(&ir) {
441            let mname = ir.module(m).name.clone();
442            let Some(mdefs) = mod_over.get(mname.as_str()) else {
443                continue;
444            };
445            let mut done: HashSet<String> = HashSet::new();
446            for (name, d) in self.t.op_defs(m) {
447                let Some(rhs) = mdefs.get(name.as_str()) else {
448                    continue;
449                };
450                let rhs = rhs.text.as_str();
451                if mdefs.contains_key(rhs) {
452                    return Err(BindError::tlc(Ec::TlcConfigRhsIdAppearedAfterLhsId, &[rhs]).into());
453                }
454                let Some(val) = self.defns.get(rhs).cloned() else {
455                    return Err(
456                        BindError::tlc(Ec::TlcConfigWrongSubstitution, &[&name, rhs]).into(),
457                    );
458                };
459                if let Look::Def(r) = &val
460                    && ir.def(d).params.len() != ir.def(*r).params.len()
461                {
462                    return Err(BindError::tlc(
463                        Ec::TlcConfigWrongSubstitutionNumberOfArgs,
464                        &[&name, rhs],
465                    )
466                    .into());
467                }
468                self.set_body_obj(d, &val);
469                done.insert(name);
470            }
471            let keys = override_keys(self.cfg, Some(&mname));
472            for k in hashtable_order(&keys) {
473                if !done.contains(k.as_str()) {
474                    return Err(BindError::tlc(Ec::TlcConfigIdDoesNotAppearInSpec, &[&k]).into());
475                }
476            }
477        }
478        let mut mkeys: Vec<String> = Vec::new();
479        for e in &self.cfg.constants {
480            if let ConstantEntry::Substitution {
481                module: Some(m), ..
482            } = e
483                && !mkeys.contains(&m.text)
484            {
485                mkeys.push(m.text.clone());
486            }
487        }
488        for k in hashtable_order(&mkeys) {
489            if !module_names.contains(&k) {
490                return Err(BindError::tlc(Ec::TlcNoModules, &[&k]).into());
491            }
492        }
493        Ok(())
494    }
495
496    /// Sets the tool object of `d`'s body. TLC's lookup of an instantiated
497    /// copy (`I!Op`, whose body is `d`'s under the instance's substitutions)
498    /// looks through the substitutions and finds it too.
499    fn set_body_obj(&mut self, d: DefId, l: &Look) {
500        let ir = self.t.ir.clone();
501        for (i, def) in ir.defs().iter().enumerate() {
502            let mut cur = def.source;
503            let mut hops = 0;
504            let mut hit = i == d.index();
505            while let Some(s) = cur {
506                if s == d {
507                    hit = true;
508                    break;
509                }
510                hops += 1;
511                if hops > 64 {
512                    break;
513                }
514                cur = ir.def(s).source;
515            }
516            if hit {
517                self.t
518                    .body_obj
519                    .insert(DefId(u32::try_from(i).unwrap_or(u32::MAX)), l.clone());
520            }
521        }
522    }
523
524    /// TLC loads a Java class named after a loaded module from the module's
525    /// directory and uses its methods instead of the module's definitions
526    /// (`TLAClass.loadClass`, the first phase of `processModuleOverrides`).
527    /// Only the pinned Hanoi Bits class has a native port; others are refused.
528    fn install_user_java_overrides(&mut self) {
529        let ir = self.t.ir.clone();
530        for m in file_modules(&ir) {
531            let module = ir.module(m);
532            if module.standard {
533                continue;
534            }
535            let Some(f) = module.file else { continue };
536            let Some(info) = ir.files().get(f.index()) else {
537                continue;
538            };
539            let Some(dir) = Path::new(&info.display).parent() else {
540                continue;
541            };
542            let class = dir.join(format!("{}.class", module.name));
543            if class.is_file() {
544                if module.name == "Bits" && known_bits_class(&class) {
545                    let defs: Vec<_> = ir
546                        .defs()
547                        .iter()
548                        .enumerate()
549                        .filter_map(|(i, def)| {
550                            (def.module == m && def.name == "And" && def.source.is_none())
551                                .then_some(DefId(u32::try_from(i).unwrap_or(u32::MAX)))
552                        })
553                        .collect();
554                    for d in defs {
555                        let native = Arc::make_mut(&mut self.t.ir);
556                        if native.set_native_override(d, StdOp::BitsAnd) {
557                            // TLC installs the same body override on instantiated copies.
558                            for i in 0..native.defs().len() {
559                                let id = DefId(u32::try_from(i).unwrap_or(u32::MAX));
560                                let mut source = id;
561                                for _ in 0..=native.defs().len() {
562                                    if source == d {
563                                        native.set_native_override(id, StdOp::BitsAnd);
564                                        break;
565                                    }
566                                    let Some(next) = native.def(source).source else {
567                                        break;
568                                    };
569                                    source = next;
570                                }
571                            }
572                            self.defns
573                                .insert("And".into(), Look::Java(StdOp::BitsAnd, d));
574                        } else {
575                            self.unsupported.push("Bits!And (local class signature does not match four value parameters)".into());
576                        }
577                    }
578                    continue;
579                }
580                self.unsupported.push(format!(
581                    "a Java class overriding module {} ({}.class)",
582                    module.name, module.name
583                ));
584            }
585        }
586    }
587
588    /// Builds the evaluator once the constants and overrides are bound.
589    pub(crate) fn build_evaluator(&mut self) -> R<()> {
590        let ir = self.t.ir.clone();
591        let mut model = dive_eval::Model::new(ir.clone());
592        model.names = self.names.clone();
593        for (i, slot) in self.t.consts.iter().enumerate() {
594            model.constants[i] = match slot {
595                Some(Look::Value(v)) => Some(ConstBinding::Value(v.clone())),
596                Some(Look::Def(d) | Look::Java(_, d)) => {
597                    let constant = ir.decl(ir.consts()[i]);
598                    if ir.def(*d).params.len() != constant.arity as usize {
599                        return Err(BindError::tlc(
600                            Ec::TlcConfigWrongSubstitutionNumberOfArgs,
601                            &[&constant.name, &ir.def(*d).name],
602                        )
603                        .into());
604                    }
605                    Some(ConstBinding::Def(*d))
606                }
607                Some(Look::Literal(_)) | None => None,
608            };
609        }
610        for map in [&self.t.tool_obj, &self.t.body_obj] {
611            for (d, l) in map {
612                match l {
613                    Look::Value(v) => {
614                        model.def_values.entry(*d).or_insert_with(|| v.clone());
615                    }
616                    Look::Def(r) | Look::Java(_, r) => {
617                        model.redirects.entry(*d).or_insert(*r);
618                    }
619                    Look::Literal(_) => {}
620                }
621            }
622        }
623        // Construction returns ContextError, not an intrinsic EvalError.
624        let ev = Evaluator::new(model, self.opts.eval)
625            .map_err(|e| BindError::unsupported(e.to_string()))?;
626        if let Some(h) = &self.opts.host {
627            ev.set_host(h.clone());
628        }
629        self.t.set_evaluator(ev, self.control.is_some());
630        Ok(())
631    }
632
633    // -------------------------------------------------------------------
634    // processConstantDefns
635    // -------------------------------------------------------------------
636
637    /// `SpecProcessor.processConstantDefns`: for every module of the module
638    /// table (and its inner modules), the constants the configuration binds
639    /// to definitions, then every constant-level zero-arity definition, are
640    /// evaluated, and the values kept. Failures are swallowed.
641    pub(crate) fn process_constant_defns(&mut self) -> R<()> {
642        if self.defer.is_some() {
643            self.defer = Some(crate::defer::candidates(self));
644        }
645        let ir = self.t.ir.clone();
646        for m in file_modules(&ir) {
647            if self.processes_constant_defns(m) {
648                self.constant_defns_of(m)?;
649            }
650        }
651        self.drain_prints();
652        Ok(())
653    }
654
655    /// `ModuleNode.processConstantDefns`: not for a module that is
656    /// instantiated and has parameters.
657    pub(crate) fn processes_constant_defns(&self, m: ModuleId) -> bool {
658        let ir = &*self.t.ir;
659        let module = ir.module(m);
660        if !module.instantiated {
661            return true;
662        }
663        let has_params = module.context.iter().any(|(_, s)| {
664            matches!(s, Symbol::Decl(d) if {
665                let decl = ir.decl(*d);
666                decl.variable || decl.constant.is_some()
667            })
668        });
669        !has_params
670    }
671
672    fn constant_defns_of(&mut self, m: ModuleId) -> R<()> {
673        let ir = self.t.ir.clone();
674        // Constants bound to definitions (`C <- D`).
675        for &decl in &ir.module(m).tlc_constants.clone() {
676            let d = ir.decl(decl);
677            let Some(c) = d.constant else { continue };
678            let Some(Look::Def(def)) = self.t.const_look(c) else {
679                continue;
680            };
681            if ir.def(def).params.len() != d.arity as usize {
682                return Err(BindError::tlc(
683                    Ec::TlcConfigWrongSubstitutionNumberOfArgs,
684                    &[&d.name, &ir.def(def).name],
685                )
686                .into());
687            }
688            if !ir.def(def).params.is_empty() {
689                continue;
690            }
691            let (result, input_refusal) = self.startup_precompute(def);
692            match result {
693                Ok(Some(v)) => {
694                    // `opDef.setToolObject(toolId, defVal)`.
695                    self.t.tool_obj.insert(def, Look::Value(v));
696                }
697                Ok(None) => {}
698                Err(e) => {
699                    self.propagate_interruption(&e)?;
700                    let scope = self.ev().scope(def).map_err(|e| {
701                        self.eval_error(e, |e| BindError::unsupported(e.to_string()))
702                    })?;
703                    let level = LevelCx::new(&self.t).try_level(ir.def(def).body, &scope)?;
704                    if level > 0 {
705                        self.drain_prints();
706                        // `(e instanceof EvalException) ? "" : " - specifically: " + e.getMessage()`.
707                        let addendum = if e.class() != ErrorClass::Eval {
708                            return Err(BindError::unsupported(format!(
709                                "the message TLC prints when the definition {} that the configuration substitutes for {} fails at start-up ({e})",
710                                ir.def(def).name,
711                                d.name
712                            )).into());
713                        } else if e.is_eval_exception() {
714                            String::new()
715                        } else {
716                            format!(" - specifically: {}", e.tool_text())
717                        };
718                        return Err(BindError::tlc(
719                            Ec::TlcConfigSubstitutionNonConstant,
720                            &[&d.name, &ir.def(def).name, &addendum],
721                        )
722                        .into());
723                    }
724                    self.note_startup_failure(def, &e, input_refusal)?;
725                }
726            }
727        }
728        // Constant-level definitions.
729        for (name, d) in self.t.op_defs(m) {
730            let def = ir.def(d);
731            if !def.params.is_empty() {
732                continue;
733            }
734            let origin = def.module;
735            if !self.processes_constant_defns(origin) {
736                continue;
737            }
738            let real = match self.t.tool_obj.get(&d) {
739                Some(Look::Def(r)) => *r,
740                Some(_) => continue,
741                None => match self.t.lookup_def(d) {
742                    Look::Def(r) => r,
743                    Look::Value(_) | Look::Java(..) | Look::Literal(_) => continue,
744                },
745            };
746            let scope = self
747                .ev()
748                .scope(real)
749                .map_err(|e| self.eval_error(e, |e| BindError::unsupported(e.to_string())))?;
750            let level = LevelCx::new(&self.t).try_level(ir.def(real).body, &scope)?;
751            if level != 0 {
752                continue;
753            }
754            if self.left_to_core(real) {
755                continue;
756            }
757            let _ = name;
758            self.keep_startup_value(real)?;
759        }
760        for inner in inner_modules(&ir, m) {
761            self.constant_defns_of(inner)?;
762        }
763        Ok(())
764    }
765
766    /// Evaluates `real` at start-up and keeps its value, as
767    /// `processConstantDefns` does; a failure is swallowed as TLC swallows it
768    /// ([`Binder::note_startup_failure`]).
769    fn keep_startup_value(&mut self, real: DefId) -> R<()> {
770        let (result, input_refusal) = self.startup_precompute(real);
771        match result {
772            Ok(Some(v)) => {
773                self.t.tool_obj.insert(real, Look::Value(v.clone()));
774                let real_name = self.t.ir.def(real).name.clone();
775                if matches!(self.defns.get(&real_name), Some(Look::Def(x)) if *x == real) {
776                    self.defns.insert(real_name, Look::Value(v));
777                }
778                Ok(())
779            }
780            Ok(None) => Ok(()),
781            Err(e) => self.note_startup_failure(real, &e, input_refusal),
782        }
783    }
784
785    /// Evaluates, as `processConstantDefns` would have, the definitions left
786    /// to the core that the dive-eval evaluator may evaluate after binding
787    /// on the temporal route (`crate::defer::evaluator_temporal`), and
788    /// returns them: they are no longer left to the core.
789    pub(crate) fn keep_temporal_startup_values(
790        &mut self,
791        model: &crate::Model,
792    ) -> R<std::collections::BTreeSet<DefId>> {
793        let Some(defer) = &self.defer else {
794            return Ok(std::collections::BTreeSet::new());
795        };
796        if model.implied_temporals.is_empty() || defer.skip.is_empty() {
797            return Ok(std::collections::BTreeSet::new());
798        }
799        let reached = crate::defer::evaluator_temporal(self, model);
800        let settled: std::collections::BTreeSet<DefId> = defer
801            .skip
802            .iter()
803            .copied()
804            .filter(|d| reached.contains(d))
805            .collect();
806        for &d in &settled {
807            self.keep_startup_value(d)?;
808        }
809        if let Some(defer) = &mut self.defer {
810            for d in &settled {
811                defer.skip.remove(d);
812                defer.evaluate.remove(d);
813            }
814        }
815        for d in &settled {
816            self.deferred.remove(d);
817        }
818        Ok(settled)
819    }
820
821    /// Whether the start-up evaluation of `def` is left to the core
822    /// (`crate::defer`), which evaluates it when it compiles its plan if a
823    /// role uses it.
824    fn left_to_core(&mut self, def: DefId) -> bool {
825        let Some(defer) = &self.defer else {
826            return false;
827        };
828        if !defer.skip.contains(&def) {
829            return false;
830        }
831        if defer.evaluate.contains(&def) {
832            self.deferred.insert(def);
833        }
834        true
835    }
836
837    /// Precomputes `def` at start-up, returning the external-input refusal
838    /// this evaluation recorded separately. A successful evaluation's refusal
839    /// is restored at once; a failed one's goes to
840    /// [`Binder::note_startup_failure`].
841    fn startup_precompute(
842        &self,
843        def: DefId,
844    ) -> (Result<Option<Value>, dive_eval::EvalError>, Option<String>) {
845        let ev = self.ev();
846        let prior = ev.take_external_input_refusal();
847        let result = ev.precompute(def);
848        let mine = ev.take_external_input_refusal();
849        ev.restore_external_input_refusal(prior);
850        if result.is_ok() {
851            ev.restore_external_input_refusal(mine);
852            return (result, None);
853        }
854        (result, mine)
855    }
856
857    /// A start-up evaluation failed. TLC swallows the error; dive does too,
858    /// unless dive refused something TLC may have evaluated, in which case
859    /// the outcome may differ if the definition is impure (it prints or
860    /// draws, or the checking path reaches it) and the model is refused.
861    /// That decision waits for the checking path (`reach::unsupported`).
862    fn note_startup_failure(
863        &mut self,
864        def: DefId,
865        e: &dive_eval::EvalError,
866        input_refusal: Option<String>,
867    ) -> R<()> {
868        self.propagate_interruption(e)?;
869        if e.class() == ErrorClass::Eval {
870            self.ev().restore_external_input_refusal(input_refusal);
871            return Ok(());
872        }
873        let ir = &*self.t.ir;
874        let what = format!(
875            "the start-up evaluation of {}: {}",
876            ir.def(def).name,
877            e.message()
878        );
879        if ir.def(def).effects.intersects(dive_ir::Effects::IMPURE) {
880            self.startup_refusals.push(StartupRefusal {
881                def,
882                what: what.clone(),
883                input_refusal,
884            });
885        } else {
886            self.ev().restore_external_input_refusal(input_refusal);
887        }
888        self.refused.entry(def).or_insert(what);
889        Ok(())
890    }
891
892    /// Refuses a configuration name that names a definition whose start-up
893    /// evaluation dive refused: TLC may have replaced it by a value, which
894    /// changes how the name is treated.
895    pub(crate) fn check_refused(&self, name: &str) -> R<()> {
896        if let Some(Look::Def(d)) = self.defns.get(name)
897            && let Some(why) = self.refused.get(d)
898        {
899            return Err(BindError::unsupported(why.clone()).into());
900        }
901        Ok(())
902    }
903
904    /// A configuration name looked up as TLC does (`defns.get(name)`).
905    pub(crate) fn defn(&self, name: &str) -> Option<Look> {
906        self.defns.get(name).cloned()
907    }
908}
909
910/// The keys of the configuration's `<-` table for the root module (`None`)
911/// or a module, in first-insertion order.
912fn override_keys(cfg: &ModelConfig, module: Option<&str>) -> Vec<String> {
913    let mut keys: Vec<String> = Vec::new();
914    for e in &cfg.constants {
915        if let ConstantEntry::Substitution {
916            name, module: m, ..
917        } = e
918            && m.as_ref().map(|n| n.text.as_str()) == module
919            && !keys.contains(&name.text)
920        {
921            keys.push(name.text.clone());
922        }
923    }
924    keys
925}
926
927/// The keys of a `java.util.Hashtable<String, _>` built by putting `keys` in
928/// order, in its enumeration order (`Hashtable.keys()`).
929fn hashtable_order(keys: &[String]) -> Vec<String> {
930    let hashes: Vec<i32> = keys
931        .iter()
932        .map(|k| dive_ir::hashtable::java_string_hash(k))
933        .collect();
934    dive_ir::hashtable::enumeration_order(&hashes)
935        .into_iter()
936        .filter_map(|i| keys.get(i).cloned())
937        .collect()
938}
939
940/// SHA-256 of the supported local `Bits.class` from the pinned Examples Hanoi model.
941///
942/// Class presence and this exact digest establish the local input identity;
943/// installation separately validates `And`'s four value parameters.
944pub const HANOI_BITS_CLASS_SHA256: [u8; 32] = [
945    0x22, 0x5d, 0x2d, 0x3d, 0x16, 0x3b, 0x5a, 0x2c, 0x29, 0x23, 0x54, 0x4d, 0xe6, 0x19, 0xfb, 0x6f,
946    0x23, 0xcb, 0x86, 0x80, 0x4e, 0xd0, 0x6b, 0xd2, 0x84, 0x2c, 0xa2, 0x7a, 0x24, 0x2b, 0x84, 0x6b,
947];
948
949/// Hash local classes with bounded memory; unreadable bytes remain unsupported.
950fn known_bits_class(path: &Path) -> bool {
951    class_digest(path).is_ok_and(|digest| digest == HANOI_BITS_CLASS_SHA256)
952}
953
954fn class_digest(path: &Path) -> std::io::Result<[u8; 32]> {
955    let mut file = std::fs::File::open(path)?;
956    let mut hash = Sha256::new();
957    let mut buffer = [0; 8192];
958    loop {
959        let n = file.read(&mut buffer)?;
960        if n == 0 {
961            return Ok(hash.finalize().into());
962        }
963        hash.update(&buffer[..n]);
964    }
965}
966
967/// SHA-256 identities of adjacent local Java classes, sorted by module name.
968///
969/// Only file-level nonstandard modules participate. Class bytes are streamed
970/// through a fixed-size buffer; no Java code or TLA+ expression is evaluated.
971/// An empty result preserves the identity of sources with no local classes.
972///
973/// # Errors
974///
975/// Returns a named refusal if an existing class cannot be read completely.
976/// This does not establish whether a class has a supported native port.
977pub fn local_java_class_digests(ir: &Ir) -> Result<Vec<(String, [u8; 32])>, String> {
978    let mut digests = Vec::new();
979    for m in file_modules(ir) {
980        let module = ir.module(m);
981        if module.standard {
982            continue;
983        }
984        let Some(file) = module.file.and_then(|f| ir.files().get(f.index())) else {
985            continue;
986        };
987        let Some(dir) = Path::new(&file.display).parent() else {
988            continue;
989        };
990        let path = dir.join(format!("{}.class", module.name));
991        if path.is_file() {
992            let digest = class_digest(&path).map_err(|error| {
993                format!(
994                    "a Java class overriding module {} ({}.class): {error}",
995                    module.name, module.name
996                )
997            })?;
998            digests.push((module.name.clone(), digest));
999        }
1000    }
1001    digests.sort_unstable_by(|a, b| a.0.cmp(&b.0));
1002    Ok(digests)
1003}