1use 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#[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 #[must_use]
26 pub fn get(&self, name: &str) -> Option<&Value> {
27 self.values.get(name)
28 }
29
30 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 #[must_use]
39 pub fn len(&self) -> usize {
40 self.values.len()
41 }
42
43 #[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 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 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 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;