1use crate::sexpr::{Atom, SExpr};
4use alloc::boxed::Box;
5use alloc::collections::{BTreeMap, BTreeSet};
6use alloc::format;
7use alloc::string::String;
8use alloc::vec::Vec;
9
10#[derive(Debug, Clone, PartialEq, Eq)]
11#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
12pub struct Definition {
13 pub name: String,
14 pub elements: Vec<String>,
15 pub bottom: String,
16 pub top: String,
17 pub rows: Vec<(String, String, String)>,
18}
19
20#[derive(Debug, Clone, PartialEq, Eq)]
21#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
22pub struct Row {
23 pub key: String,
24 pub value: SExpr,
25 pub element: String,
26}
27
28#[derive(Debug, Clone, PartialEq, Eq)]
29#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
30pub struct Projection {
31 pub stable: bool,
32 pub rows: Vec<(String, SExpr)>,
33}
34
35#[derive(Debug, Clone, PartialEq, Eq)]
36#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
37pub struct Lift {
38 pub verb: String,
39 pub lattice: String,
40 pub rows: Vec<Row>,
41 pub projection: Option<Projection>,
42 pub table: Option<Box<Table>>,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq)]
47#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
48pub struct Table {
49 pub name: String,
50 pub elements: Vec<String>,
51 pub bottom: usize,
52 pub top: usize,
53 pub join: Vec<usize>,
54}
55
56impl Table {
57 pub fn merge(&self, a: usize, b: usize) -> usize {
58 self.join[a * self.elements.len() + b]
59 }
60 pub fn index(&self, name: &str) -> Option<usize> {
61 self.elements.iter().position(|x| x == name)
62 }
63 pub fn le(&self, a: usize, b: usize) -> bool {
64 self.merge(a, b) == b
65 }
66}
67
68impl Definition {
69 pub fn to_sexpr(&self) -> SExpr {
70 let sym = |s: &str| SExpr::Atom(Atom::Symbol(s.into()));
71 let mut elements = alloc::vec![sym("elements")];
72 elements.extend(self.elements.iter().map(|x| sym(x)));
73 let mut join = alloc::vec![sym("join")];
74 join.extend(
75 self.rows
76 .iter()
77 .map(|(a, b, c)| SExpr::List(alloc::vec![sym(a), sym(b), sym(c)])),
78 );
79 SExpr::List(alloc::vec![
80 sym("lattice"),
81 sym(&self.name),
82 SExpr::List(elements),
83 SExpr::List(alloc::vec![sym("bottom"), sym(&self.bottom)]),
84 SExpr::List(alloc::vec![sym("top"), sym(&self.top)]),
85 SExpr::List(join)
86 ])
87 }
88 pub fn compile(&self) -> Result<Table, String> {
91 let n = self.elements.len();
92 if n == 0 {
93 return Err("lattice elements cannot be empty".into());
94 }
95 let indices: BTreeMap<&str, usize> = self
96 .elements
97 .iter()
98 .enumerate()
99 .map(|(i, s)| (s.as_str(), i))
100 .collect();
101 if indices.len() != n {
102 return Err("duplicate lattice element".into());
103 }
104 let index = |name: &str| {
105 indices
106 .get(name)
107 .copied()
108 .ok_or_else(|| format!("undeclared element '{name}'"))
109 };
110 let bottom = index(&self.bottom)?;
111 let top = index(&self.top)?;
112 if bottom == top {
113 return Err("lattice bottom and conflict top must be distinct".into());
114 }
115 let mut rows = BTreeMap::new();
116 for (a, b, c) in &self.rows {
117 let (a, b, c) = (index(a)?, index(b)?, index(c)?);
118 if rows.insert((a, b), c).is_some() {
119 return Err(format!(
120 "duplicate join row: ({} {})",
121 self.elements[a], self.elements[b]
122 ));
123 }
124 }
125 let mut join = Vec::with_capacity(rows.len());
126 for a in 0..n {
127 for b in 0..n {
128 join.push(*rows.get(&(a, b)).ok_or_else(|| {
129 format!(
130 "join not total: missing ({} {})",
131 self.elements[a], self.elements[b]
132 )
133 })?);
134 }
135 }
136 Ok(Table {
137 name: self.name.clone(),
138 elements: self.elements.clone(),
139 bottom,
140 top,
141 join,
142 })
143 }
144
145 pub fn validate(&self, max_elements: usize) -> Result<Table, String> {
146 self.validate_counted(max_elements, || {})
147 }
148
149 fn validate_counted(
150 &self,
151 max_elements: usize,
152 mut triple: impl FnMut(),
153 ) -> Result<Table, String> {
154 if self.elements.len() > max_elements {
155 return Err(format!(
156 "lattice '{}' exceeds max-list ({max_elements})",
157 self.name
158 ));
159 }
160 let t = self.compile()?;
161 let n = t.elements.len();
162 for a in 0..n {
163 for b in 0..n {
164 if t.merge(a, b) != t.merge(b, a) {
165 return Err(format!(
166 "join not commutative: ({} {}) != ({} {})",
167 t.elements[a], t.elements[b], t.elements[b], t.elements[a]
168 ));
169 }
170 }
171 }
172 for a in 0..n {
173 for b in 0..n {
174 for c in 0..n {
175 triple();
176 if t.merge(t.merge(a, b), c) != t.merge(a, t.merge(b, c)) {
177 return Err(format!(
178 "join not associative: ({} {} {})",
179 t.elements[a], t.elements[b], t.elements[c]
180 ));
181 }
182 }
183 }
184 }
185 for a in 0..n {
186 if t.merge(a, a) != a {
187 return Err(format!("join not idempotent: ({})", t.elements[a]));
188 }
189 if t.merge(a, t.bottom) != a || t.merge(t.bottom, a) != a {
190 return Err(format!("bottom not identity: ({})", t.elements[a]));
191 }
192 if t.merge(a, t.top) != t.top || t.merge(t.top, a) != t.top {
193 return Err(format!("top not absorbing: ({})", t.elements[a]));
194 }
195 }
196 Ok(t)
197 }
198}
199
200fn scalar(value: &SExpr) -> bool {
201 matches!(
202 value,
203 SExpr::Atom(Atom::Str(_) | Atom::Num(_) | Atom::Bool(_))
204 )
205}
206
207impl Lift {
208 pub fn arguments(&self) -> Vec<SExpr> {
209 let sym = |s: &str| SExpr::Atom(Atom::Symbol(s.into()));
210 let mut rows = alloc::vec![sym("contribute")];
211 rows.extend(self.rows.iter().map(|row| {
212 SExpr::List(alloc::vec![
213 SExpr::Atom(Atom::Keyword(row.key.clone())),
214 row.value.clone(),
215 sym(&row.element)
216 ])
217 }));
218 let mut args = alloc::vec![
219 sym(&self.verb),
220 SExpr::List(alloc::vec![sym("into"), sym(&self.lattice)]),
221 SExpr::List(rows)
222 ];
223 if let Some(project) = &self.projection {
224 let mut p = alloc::vec![sym("project")];
225 if project.stable {
226 p.push(sym("stable"));
227 }
228 p.push(SExpr::List(
229 project
230 .rows
231 .iter()
232 .map(|(element, value)| SExpr::List(alloc::vec![sym(element), value.clone()]))
233 .collect(),
234 ));
235 args.push(SExpr::List(p));
236 }
237 args
238 }
239 pub fn evaluate<'a>(
240 &self,
241 acts: impl IntoIterator<Item = &'a crate::state::Act>,
242 ) -> crate::state::Value {
243 let Some(table) = &self.table else {
244 return crate::state::Value::Absent;
245 };
246 let mut index = table.bottom;
247 let mut evidence = BTreeSet::new();
248 for act in acts {
249 let value = self.contribution(table, &act.fields);
250 if value != table.bottom {
251 evidence.insert(act.address.clone());
252 }
253 index = table.merge(index, value);
254 }
255 if index == table.top {
256 return crate::state::conflict_top(
257 "finite lattice conflict",
258 evidence.into_iter().collect(),
259 );
260 }
261 self.project(table, index)
262 }
263
264 pub fn validate(&self, table: &Table) -> Result<(), String> {
265 for row in &self.rows {
266 if !scalar(&row.value) {
267 return Err(format!("contribution :{} must compare a scalar", row.key));
268 }
269 if table.index(&row.element).is_none() {
270 return Err(format!(
271 "contribution targets undeclared element '{}'",
272 row.element
273 ));
274 }
275 }
276 if let Some(project) = &self.projection {
277 let mut outputs = BTreeMap::new();
278 for (element, value) in &project.rows {
279 let Some(i) = table.index(element) else {
280 return Err(format!("projection names undeclared element '{element}'"));
281 };
282 if !scalar(value) || outputs.insert(i, value).is_some() {
283 return Err(format!("invalid or duplicate projection row '{element}'"));
284 }
285 }
286 for (i, element) in table.elements.iter().enumerate() {
287 if !outputs.contains_key(&i) {
288 return Err(format!("projection not total: missing '{element}'"));
289 }
290 }
291 if project.stable {
292 for a in 0..table.elements.len() {
293 for b in 0..table.elements.len() {
294 if table.le(a, b) {
295 let ordered = match (outputs[&a], outputs[&b]) {
296 (SExpr::Atom(Atom::Num(x)), SExpr::Atom(Atom::Num(y))) => x <= y,
297 (SExpr::Atom(Atom::Bool(x)), SExpr::Atom(Atom::Bool(y))) => {
298 !*x || *y
299 }
300 _ => false,
301 };
302 if !ordered {
303 return Err(format!(
304 "stable projection not monotone: ({} {})",
305 table.elements[a], table.elements[b]
306 ));
307 }
308 }
309 }
310 }
311 }
312 }
313 Ok(())
314 }
315
316 pub fn contribution(&self, table: &Table, fields: &BTreeMap<String, SExpr>) -> usize {
318 self.rows
319 .iter()
320 .filter(|row| fields.get(&row.key) == Some(&row.value))
321 .filter_map(|row| table.index(&row.element))
322 .fold(table.bottom, |a, b| table.merge(a, b))
323 }
324
325 pub fn project(&self, table: &Table, element: usize) -> crate::state::Value {
326 project(&self.projection, table, element)
327 }
328}
329
330pub fn project(
331 projection: &Option<Projection>,
332 table: &Table,
333 element: usize,
334) -> crate::state::Value {
335 projection
336 .as_ref()
337 .and_then(|p| {
338 p.rows
339 .iter()
340 .find(|(name, _)| *name == table.elements[element])
341 })
342 .map(|(_, value)| crate::state::Value::from_sexpr(value))
343 .unwrap_or_else(|| crate::state::Value::Str(table.elements[element].clone()))
344}
345
346#[cfg(test)]
347mod tests {
348 use super::*;
349 #[test]
350 fn verification_visits_exactly_n_cubed_associativity_triples() {
351 let n = 64;
352 let elements: Vec<String> = (0..n).map(|i| format!("e{i}")).collect();
353 let mut rows = Vec::new();
354 for a in 0..n {
355 for b in 0..n {
356 rows.push((
357 elements[a].clone(),
358 elements[b].clone(),
359 elements[a.max(b)].clone(),
360 ));
361 }
362 }
363 let d = Definition {
364 name: "chain".into(),
365 bottom: elements[0].clone(),
366 top: elements[n - 1].clone(),
367 elements,
368 rows,
369 };
370 let mut visited = 0;
371 d.validate_counted(n, || visited += 1).unwrap();
372 assert_eq!(visited, n * n * n);
373 }
374}