Skip to main content

dive_eval/
named_state.rs

1//! Query-local name-addressed states. Concrete graph states remain indexed.
2
3use std::collections::BTreeMap;
4use std::sync::{Arc, Weak};
5
6use dive_ir::DeclId;
7use dive_value::Value;
8
9use crate::core::Core;
10use crate::{ContextError, ContextErrorKind, EvalError, Evaluator, StateRef};
11
12/// A partial existential assignment keyed by canonical IR variable name.
13///
14/// Hidden declarations with the same name share one slot, including collisions
15/// with root names. These assignments belong to one evaluator and never add
16/// variables to an ordinary graph state, fingerprint or serialized trace.
17#[derive(Clone, Debug)]
18pub struct NamedState {
19    pub(crate) context: Weak<Core>,
20    pub(crate) values: BTreeMap<Arc<str>, Value>,
21}
22
23impl NamedState {
24    /// The assigned value of a canonical name; absence means unassigned.
25    #[must_use]
26    pub fn get(&self, name: &str) -> Option<&Value> {
27        self.values.get(name)
28    }
29
30    /// The actual assigned names and values, in name order.
31    pub fn assignments(&self) -> impl ExactSizeIterator<Item = (&str, &Value)> {
32        self.values
33            .iter()
34            .map(|(name, value)| (name.as_ref(), value))
35    }
36
37    /// Number of assigned names.
38    #[must_use]
39    pub fn len(&self) -> usize {
40        self.values.len()
41    }
42
43    /// Whether no name is assigned.
44    #[must_use]
45    pub fn is_empty(&self) -> bool {
46        self.values.is_empty()
47    }
48
49    pub(crate) fn empty(core: &Arc<Core>) -> Arc<Self> {
50        Arc::new(Self {
51            context: Arc::downgrade(core),
52            values: BTreeMap::new(),
53        })
54    }
55
56    pub(crate) fn with(self: &Arc<Self>, name: &str, value: Value) -> Arc<Self> {
57        self.clone().with_owned(name, value)
58    }
59
60    pub(crate) fn with_owned(mut self: Arc<Self>, name: &str, value: Value) -> Arc<Self> {
61        // Cache keys, captured states and retained alternatives hold strong
62        // Arcs, so only a genuinely unshared query state is changed in place.
63        Arc::make_mut(&mut self)
64            .values
65            .insert(Arc::from(name), value);
66        self
67    }
68}
69
70impl Evaluator {
71    pub(crate) fn validate_state_context(&self, st: &crate::St) -> crate::Result<()> {
72        for state in [&st.s0, &st.s1] {
73            if let StateRef::Named(state) = state
74                && !std::ptr::eq(state.context.as_ptr(), Arc::as_ptr(&self.core))
75            {
76                return Err(ContextError::new(
77                    ContextErrorKind::ForeignContext,
78                    "named state belongs to another evaluator",
79                )
80                .into());
81            }
82        }
83        Ok(())
84    }
85
86    /// Constructs a query-local partial assignment from real variable declarations.
87    ///
88    /// Duplicate declarations of the same canonical name must agree. This checks
89    /// stored value names without interning, enumeration or callbacks. Opaque
90    /// deferred values cannot be supplied through this checked public constructor.
91    /// The resulting state is not an ordinary Next transition or a graph state.
92    ///
93    /// ```
94    /// use std::sync::Arc;
95    /// use dive_eval::{Evaluator, Model, Options, St, StateRef};
96    /// use dive_value::Value;
97    /// let analysis = dive_sema::analyze_source("M.tla",
98    ///     "---- MODULE M ----\nVARIABLE x\nRead == x\n====\n", &Default::default());
99    /// let ir = Arc::new(dive_ir::lower(&analysis).expect("IR"));
100    /// let read = ir.root_def("Read").expect("Read");
101    /// let x = ir.vars()[0];
102    /// let evaluator = Evaluator::new(Model::new(ir), Options::tlc()).expect("evaluator");
103    /// let assignment = evaluator.named_state([(x, Value::TRUE)]).expect("assignment");
104    /// let mut state = St::empty();
105    /// state.s0 = StateRef::Named(assignment);
106    /// assert_eq!(evaluator.eval_def(read, &state).expect("read"), Value::TRUE);
107    /// ```
108    ///
109    /// # Errors
110    /// An unknown/nonvariable declaration, inconsistent duplicate assignment or
111    /// stored value whose name-table ownership cannot be checked.
112    pub fn named_state(
113        &self,
114        assignments: impl IntoIterator<Item = (DeclId, Value)>,
115    ) -> crate::Result<Arc<NamedState>> {
116        let mut values = BTreeMap::new();
117        for (decl, value) in assignments {
118            let declaration = self.core.ir.decls().get(decl.index()).ok_or_else(|| {
119                ContextError::new(
120                    ContextErrorKind::UnknownId,
121                    "named-state variable declaration",
122                )
123            })?;
124            if !declaration.variable {
125                return Err(ContextError::new(
126                    ContextErrorKind::Structure,
127                    "named-state key is not a variable",
128                )
129                .into());
130            }
131            value.validate_names(&self.core.names).map_err(|error| {
132                ContextError::new(ContextErrorKind::ForeignContext, error.to_string())
133            })?;
134            if values
135                .get(declaration.name.as_str())
136                .is_some_and(|old| old != &value)
137            {
138                return Err(EvalError::general(format!(
139                    "Conflicting assignments to query variable {}.",
140                    declaration.name,
141                )));
142            }
143            values.insert(Arc::<str>::from(declaration.name.as_str()), value);
144        }
145        Ok(Arc::new(NamedState {
146            context: Arc::downgrade(&self.core),
147            values,
148        }))
149    }
150}
151
152impl Core {
153    /// One variable-read rule for indexed graph states and named query states.
154    pub(crate) fn state_variable<'a>(
155        self: &Arc<Self>,
156        state: &'a StateRef,
157        name: &str,
158        root: Option<usize>,
159    ) -> crate::Result<Option<&'a Value>> {
160        match state {
161            StateRef::Vals(values) => Ok(root.and_then(|i| values.get(i)).and_then(Option::as_ref)),
162            StateRef::Named(state) => {
163                if !std::ptr::eq(state.context.as_ptr(), Arc::as_ptr(self)) {
164                    return Err(ContextError::new(
165                        ContextErrorKind::ForeignContext,
166                        "named state belongs to another evaluator",
167                    )
168                    .into());
169                }
170                Ok(state.get(name))
171            }
172            StateRef::Null | StateRef::Empty => Ok(None),
173        }
174    }
175}
176
177#[cfg(test)]
178#[path = "named_state_tests.rs"]
179mod tests;