Skip to main content

conjure_cp_core/ast/
eval.rs

1#![allow(dead_code)]
2use crate::ast::{
3    AbstractLiteral, Atom, DeclarationKind, Expression as Expr, Literal as Lit, Metadata,
4    comprehension::{Comprehension, ComprehensionQualifier},
5    matrix,
6};
7use crate::into_matrix;
8use itertools::{Itertools as _, izip};
9use std::cmp::Ordering as CmpOrdering;
10use std::collections::HashSet;
11
12/// Simplify an expression to a constant if possible
13/// Returns:
14/// `None` if the expression cannot be simplified to a constant (e.g. if it contains a variable)
15/// `Some(Const)` if the expression can be simplified to a constant
16pub fn eval_constant(expr: &Expr) -> Option<Lit> {
17    match expr {
18        Expr::Supset(_, a, b) => match (a.as_ref(), b.as_ref()) {
19            (
20                Expr::Atomic(_, Atom::Literal(Lit::AbstractLiteral(AbstractLiteral::Set(a)))),
21                Expr::Atomic(_, Atom::Literal(Lit::AbstractLiteral(AbstractLiteral::Set(b)))),
22            ) => {
23                let a_set: HashSet<Lit> = a.iter().cloned().collect();
24                let b_set: HashSet<Lit> = b.iter().cloned().collect();
25
26                if a_set.difference(&b_set).count() > 0 {
27                    Some(Lit::Bool(a_set.is_superset(&b_set)))
28                } else {
29                    Some(Lit::Bool(false))
30                }
31            }
32            _ => None,
33        },
34        Expr::SupsetEq(_, a, b) => match (a.as_ref(), b.as_ref()) {
35            (
36                Expr::Atomic(_, Atom::Literal(Lit::AbstractLiteral(AbstractLiteral::Set(a)))),
37                Expr::Atomic(_, Atom::Literal(Lit::AbstractLiteral(AbstractLiteral::Set(b)))),
38            ) => Some(Lit::Bool(
39                a.iter()
40                    .cloned()
41                    .collect::<HashSet<Lit>>()
42                    .is_superset(&b.iter().cloned().collect::<HashSet<Lit>>()),
43            )),
44            _ => None,
45        },
46        Expr::Subset(_, a, b) => match (a.as_ref(), b.as_ref()) {
47            (
48                Expr::Atomic(_, Atom::Literal(Lit::AbstractLiteral(AbstractLiteral::Set(a)))),
49                Expr::Atomic(_, Atom::Literal(Lit::AbstractLiteral(AbstractLiteral::Set(b)))),
50            ) => {
51                let a_set: HashSet<Lit> = a.iter().cloned().collect();
52                let b_set: HashSet<Lit> = b.iter().cloned().collect();
53
54                if b_set.difference(&a_set).count() > 0 {
55                    Some(Lit::Bool(a_set.is_subset(&b_set)))
56                } else {
57                    Some(Lit::Bool(false))
58                }
59            }
60            _ => None,
61        },
62        Expr::SubsetEq(_, a, b) => match (a.as_ref(), b.as_ref()) {
63            (
64                Expr::Atomic(_, Atom::Literal(Lit::AbstractLiteral(AbstractLiteral::Set(a)))),
65                Expr::Atomic(_, Atom::Literal(Lit::AbstractLiteral(AbstractLiteral::Set(b)))),
66            ) => Some(Lit::Bool(
67                a.iter()
68                    .cloned()
69                    .collect::<HashSet<Lit>>()
70                    .is_subset(&b.iter().cloned().collect::<HashSet<Lit>>()),
71            )),
72            _ => None,
73        },
74        Expr::Intersect(_, a, b) => match (a.as_ref(), b.as_ref()) {
75            (
76                Expr::Atomic(_, Atom::Literal(Lit::AbstractLiteral(AbstractLiteral::Set(a)))),
77                Expr::Atomic(_, Atom::Literal(Lit::AbstractLiteral(AbstractLiteral::Set(b)))),
78            ) => {
79                let mut res: Vec<Lit> = Vec::new();
80                for lit in a.iter() {
81                    if b.contains(lit) && !res.contains(lit) {
82                        res.push(lit.clone());
83                    }
84                }
85                Some(Lit::AbstractLiteral(AbstractLiteral::Set(res)))
86            }
87            _ => None,
88        },
89        Expr::Union(_, a, b) => match (a.as_ref(), b.as_ref()) {
90            (
91                Expr::Atomic(_, Atom::Literal(Lit::AbstractLiteral(AbstractLiteral::Set(a)))),
92                Expr::Atomic(_, Atom::Literal(Lit::AbstractLiteral(AbstractLiteral::Set(b)))),
93            ) => {
94                let mut res: Vec<Lit> = Vec::new();
95                for lit in a.iter() {
96                    res.push(lit.clone());
97                }
98                for lit in b.iter() {
99                    if !res.contains(lit) {
100                        res.push(lit.clone());
101                    }
102                }
103                Some(Lit::AbstractLiteral(AbstractLiteral::Set(res)))
104            }
105            _ => None,
106        },
107        Expr::In(_, a, b) => {
108            if let (
109                Expr::Atomic(_, Atom::Literal(Lit::Int(c))),
110                Expr::Atomic(_, Atom::Literal(Lit::AbstractLiteral(AbstractLiteral::Set(d)))),
111            ) = (a.as_ref(), b.as_ref())
112            {
113                for lit in d.iter() {
114                    if let Lit::Int(x) = lit
115                        && c == x
116                    {
117                        return Some(Lit::Bool(true));
118                    }
119                }
120                Some(Lit::Bool(false))
121            } else {
122                None
123            }
124        }
125        Expr::FromSolution(_, _) => None,
126        Expr::DominanceRelation(_, _) => None,
127        Expr::InDomain(_, e, domain) => {
128            let Expr::Atomic(_, Atom::Literal(lit)) = e.as_ref() else {
129                return None;
130            };
131
132            domain.contains(lit).ok().map(Into::into)
133        }
134        Expr::Atomic(_, Atom::Literal(c)) => Some(c.clone()),
135        Expr::Atomic(_, Atom::Reference(reference)) => reference.resolve_constant(),
136        Expr::AbstractLiteral(_, a) => Some(Lit::AbstractLiteral(a.clone().into_literals()?)),
137        Expr::Comprehension(_, comprehension) => {
138            eval_constant_comprehension(comprehension.as_ref())
139        }
140        Expr::AbstractComprehension(_, _) => None,
141        Expr::UnsafeIndex(_, subject, indices) | Expr::SafeIndex(_, subject, indices) => {
142            let subject: Lit = eval_constant(subject.as_ref())?;
143            let indices: Vec<Lit> = indices
144                .iter()
145                .map(eval_constant)
146                .collect::<Option<Vec<Lit>>>()?;
147
148            match subject {
149                Lit::AbstractLiteral(subject @ AbstractLiteral::Matrix(_, _)) => {
150                    matrix::flatten_enumerate(subject)
151                        .find(|(i, _)| i == &indices)
152                        .map(|(_, x)| x)
153                }
154                Lit::AbstractLiteral(subject @ AbstractLiteral::Tuple(_)) => {
155                    let AbstractLiteral::Tuple(elems) = subject else {
156                        return None;
157                    };
158
159                    assert!(indices.len() == 1, "nested tuples not supported yet");
160
161                    let Lit::Int(index) = indices[0].clone() else {
162                        return None;
163                    };
164
165                    if elems.len() < index as usize || index < 1 {
166                        return None;
167                    }
168
169                    // -1 for 0-indexing vs 1-indexing
170                    let item = elems[index as usize - 1].clone();
171
172                    Some(item)
173                }
174                Lit::AbstractLiteral(subject @ AbstractLiteral::Record(_)) => {
175                    let AbstractLiteral::Record(elems) = subject else {
176                        return None;
177                    };
178
179                    assert!(indices.len() == 1, "nested record not supported yet");
180
181                    let Lit::Int(index) = indices[0].clone() else {
182                        return None;
183                    };
184
185                    if elems.len() < index as usize || index < 1 {
186                        return None;
187                    }
188
189                    // -1 for 0-indexing vs 1-indexing
190                    let item = elems[index as usize - 1].clone();
191                    Some(item.value)
192                }
193                _ => None,
194            }
195        }
196        Expr::UnsafeSlice(_, subject, indices) | Expr::SafeSlice(_, subject, indices) => {
197            let subject: Lit = eval_constant(subject.as_ref())?;
198            let Lit::AbstractLiteral(subject @ AbstractLiteral::Matrix(_, _)) = subject else {
199                return None;
200            };
201
202            let hole_dim = indices
203                .iter()
204                .cloned()
205                .position(|x| x.is_none())
206                .expect("slice expression should have a hole dimension");
207
208            let missing_domain = matrix::index_domains(subject.clone())[hole_dim].clone();
209
210            let indices: Vec<Option<Lit>> = indices
211                .iter()
212                .cloned()
213                .map(|x| {
214                    // the outer option represents success of this iterator, the inner the index
215                    // slice.
216                    match x {
217                        Some(x) => eval_constant(&x).map(Some),
218                        None => Some(None),
219                    }
220                })
221                .collect::<Option<Vec<Option<Lit>>>>()?;
222
223            let indices_in_slice: Vec<Vec<Lit>> = missing_domain
224                .values()
225                .ok()?
226                .map(|i| {
227                    let mut indices = indices.clone();
228                    indices[hole_dim] = Some(i);
229                    // These unwraps will only fail if we have multiple holes.
230                    // As this is invalid, panicking is fine.
231                    indices.into_iter().map(|x| x.unwrap()).collect_vec()
232                })
233                .collect_vec();
234
235            // Note: indices_in_slice is not necessarily sorted, so this is the best way.
236            let elems = matrix::flatten_enumerate(subject)
237                .filter(|(i, _)| indices_in_slice.contains(i))
238                .map(|(_, elem)| elem)
239                .collect();
240
241            Some(Lit::AbstractLiteral(into_matrix![elems]))
242        }
243        Expr::Abs(_, e) => un_op::<i32, i32>(|a| a.abs(), e).map(Lit::Int),
244        Expr::Eq(_, a, b) => bin_op::<i32, bool>(|a, b| a == b, a, b)
245            .or_else(|| bin_op::<bool, bool>(|a, b| a == b, a, b))
246            .map(Lit::Bool),
247        Expr::Neq(_, a, b) => bin_op::<i32, bool>(|a, b| a != b, a, b).map(Lit::Bool),
248        Expr::Lt(_, a, b) => bin_op::<i32, bool>(|a, b| a < b, a, b).map(Lit::Bool),
249        Expr::Gt(_, a, b) => bin_op::<i32, bool>(|a, b| a > b, a, b).map(Lit::Bool),
250        Expr::Leq(_, a, b) => bin_op::<i32, bool>(|a, b| a <= b, a, b).map(Lit::Bool),
251        Expr::Geq(_, a, b) => bin_op::<i32, bool>(|a, b| a >= b, a, b).map(Lit::Bool),
252        Expr::Not(_, expr) => un_op::<bool, bool>(|e| !e, expr).map(Lit::Bool),
253        Expr::And(_, e) => {
254            vec_lit_op::<bool, bool>(|e| e.iter().all(|&e| e), e.as_ref()).map(Lit::Bool)
255        }
256        Expr::Table(_, _, _) => None,
257        Expr::NegativeTable(_, _, _) => None,
258        Expr::Root(_, _) => None,
259        Expr::Or(_, es) => {
260            // possibly cheating; definitely should be in partial eval instead
261            for e in (**es).clone().unwrap_list()? {
262                if let Expr::Atomic(_, Atom::Literal(Lit::Bool(true))) = e {
263                    return Some(Lit::Bool(true));
264                };
265            }
266
267            vec_lit_op::<bool, bool>(|e| e.iter().any(|&e| e), es.as_ref()).map(Lit::Bool)
268        }
269        Expr::Imply(_, box1, box2) => {
270            let a: &Atom = (&**box1).try_into().ok()?;
271            let b: &Atom = (&**box2).try_into().ok()?;
272
273            let a: bool = a.try_into().ok()?;
274            let b: bool = b.try_into().ok()?;
275
276            if a {
277                // true -> b ~> b
278                Some(Lit::Bool(b))
279            } else {
280                // false -> b ~> true
281                Some(Lit::Bool(true))
282            }
283        }
284        Expr::Iff(_, box1, box2) => {
285            let a: &Atom = (&**box1).try_into().ok()?;
286            let b: &Atom = (&**box2).try_into().ok()?;
287
288            let a: bool = a.try_into().ok()?;
289            let b: bool = b.try_into().ok()?;
290
291            Some(Lit::Bool(a == b))
292        }
293        Expr::Sum(_, exprs) => vec_lit_op::<i32, i32>(|e| e.iter().sum(), exprs).map(Lit::Int),
294        Expr::Product(_, exprs) => {
295            vec_lit_op::<i32, i32>(|e| e.iter().product(), exprs).map(Lit::Int)
296        }
297        Expr::FlatIneq(_, a, b, c) => {
298            let a: i32 = a.try_into().ok()?;
299            let b: i32 = b.try_into().ok()?;
300            let c: i32 = c.try_into().ok()?;
301
302            Some(Lit::Bool(a <= b + c))
303        }
304        Expr::FlatSumGeq(_, exprs, a) => {
305            let sum = exprs.iter().try_fold(0, |acc, atom: &Atom| {
306                let n: i32 = atom.try_into().ok()?;
307                let acc = acc + n;
308                Some(acc)
309            })?;
310
311            Some(Lit::Bool(sum >= a.try_into().ok()?))
312        }
313        Expr::FlatSumLeq(_, exprs, a) => {
314            let sum = exprs.iter().try_fold(0, |acc, atom: &Atom| {
315                let n: i32 = atom.try_into().ok()?;
316                let acc = acc + n;
317                Some(acc)
318            })?;
319
320            Some(Lit::Bool(sum >= a.try_into().ok()?))
321        }
322        Expr::Min(_, e) => {
323            opt_vec_lit_op::<i32, i32>(|e| e.iter().min().copied(), e.as_ref()).map(Lit::Int)
324        }
325        Expr::Max(_, e) => {
326            opt_vec_lit_op::<i32, i32>(|e| e.iter().max().copied(), e.as_ref()).map(Lit::Int)
327        }
328        Expr::UnsafeDiv(_, a, b) | Expr::SafeDiv(_, a, b) => {
329            if unwrap_expr::<i32>(b)? == 0 {
330                return None;
331            }
332            bin_op::<i32, i32>(|a, b| ((a as f32) / (b as f32)).floor() as i32, a, b).map(Lit::Int)
333        }
334        Expr::UnsafeMod(_, a, b) | Expr::SafeMod(_, a, b) => {
335            if unwrap_expr::<i32>(b)? == 0 {
336                return None;
337            }
338            bin_op::<i32, i32>(|a, b| a - b * (a as f32 / b as f32).floor() as i32, a, b)
339                .map(Lit::Int)
340        }
341        Expr::MinionDivEqUndefZero(_, a, b, c) => {
342            // div always rounds down
343            let a: i32 = a.try_into().ok()?;
344            let b: i32 = b.try_into().ok()?;
345            let c: i32 = c.try_into().ok()?;
346
347            if b == 0 {
348                return None;
349            }
350
351            let a = a as f32;
352            let b = b as f32;
353            let div: i32 = (a / b).floor() as i32;
354            Some(Lit::Bool(div == c))
355        }
356        Expr::Bubble(_, a, b) => bin_op::<bool, bool>(|a, b| a && b, a, b).map(Lit::Bool),
357        Expr::MinionReify(_, a, b) => {
358            let result = eval_constant(a)?;
359
360            let result: bool = result.try_into().ok()?;
361            let b: bool = b.try_into().ok()?;
362
363            Some(Lit::Bool(b == result))
364        }
365        Expr::MinionReifyImply(_, a, b) => {
366            let result = eval_constant(a)?;
367
368            let result: bool = result.try_into().ok()?;
369            let b: bool = b.try_into().ok()?;
370
371            if b {
372                Some(Lit::Bool(result))
373            } else {
374                Some(Lit::Bool(true))
375            }
376        }
377        Expr::MinionModuloEqUndefZero(_, a, b, c) => {
378            // From Savile Row. Same semantics as division.
379            //
380            //   a - (b * floor(a/b))
381            //
382            // We don't use % as it has the same semantics as /. We don't use / as we want to round
383            // down instead, not towards zero.
384
385            let a: i32 = a.try_into().ok()?;
386            let b: i32 = b.try_into().ok()?;
387            let c: i32 = c.try_into().ok()?;
388
389            if b == 0 {
390                return None;
391            }
392
393            let modulo = a - b * (a as f32 / b as f32).floor() as i32;
394            Some(Lit::Bool(modulo == c))
395        }
396        Expr::MinionPow(_, a, b, c) => {
397            // only available for positive a b c
398
399            let a: i32 = a.try_into().ok()?;
400            let b: i32 = b.try_into().ok()?;
401            let c: i32 = c.try_into().ok()?;
402
403            if a <= 0 {
404                return None;
405            }
406
407            if b <= 0 {
408                return None;
409            }
410
411            if c <= 0 {
412                return None;
413            }
414
415            Some(Lit::Bool(a ^ b == c))
416        }
417        Expr::MinionWInSet(_, _, _) => None,
418        Expr::MinionWInIntervalSet(_, x, intervals) => {
419            let x_lit: &Lit = x.try_into().ok()?;
420
421            let x_lit = match x_lit.clone() {
422                Lit::Int(i) => Some(i),
423                Lit::Bool(true) => Some(1),
424                Lit::Bool(false) => Some(0),
425                _ => None,
426            }?;
427
428            let mut intervals = intervals.iter();
429            loop {
430                let Some(lower) = intervals.next() else {
431                    break;
432                };
433
434                let Some(upper) = intervals.next() else {
435                    break;
436                };
437                if &x_lit >= lower && &x_lit <= upper {
438                    return Some(Lit::Bool(true));
439                }
440            }
441
442            Some(Lit::Bool(false))
443        }
444        Expr::Flatten(_, _, _) => {
445            // TODO
446            None
447        }
448        Expr::AllDiff(_, e) => {
449            let es = (**e).clone().unwrap_list()?;
450            let mut lits: HashSet<Lit> = HashSet::new();
451            for expr in es {
452                let Expr::Atomic(_, Atom::Literal(x)) = expr else {
453                    return None;
454                };
455                match x {
456                    Lit::Int(_) | Lit::Bool(_) => {
457                        if lits.contains(&x) {
458                            return Some(Lit::Bool(false));
459                        } else {
460                            lits.insert(x.clone());
461                        }
462                    }
463                    Lit::AbstractLiteral(_) => return None, // Reject AbstractLiteral cases
464                }
465            }
466            Some(Lit::Bool(true))
467        }
468        Expr::FlatAllDiff(_, es) => {
469            let mut lits: HashSet<Lit> = HashSet::new();
470            for atom in es {
471                let Atom::Literal(x) = atom else {
472                    return None;
473                };
474
475                match x {
476                    Lit::Int(_) | Lit::Bool(_) => {
477                        if lits.contains(x) {
478                            return Some(Lit::Bool(false));
479                        } else {
480                            lits.insert(x.clone());
481                        }
482                    }
483                    Lit::AbstractLiteral(_) => return None, // Reject AbstractLiteral cases
484                }
485            }
486            Some(Lit::Bool(true))
487        }
488        Expr::FlatWatchedLiteral(_, _, _) => None,
489        Expr::AuxDeclaration(_, _, _) => None,
490        Expr::Neg(_, a) => match eval_constant(a.as_ref())? {
491            Lit::Int(a) => Some(Lit::Int(-a)),
492            _ => None,
493        },
494        Expr::Factorial(_, _) => None,
495        Expr::Minus(_, a, b) => bin_op::<i32, i32>(|a, b| a - b, a, b).map(Lit::Int),
496        Expr::FlatMinusEq(_, a, b) => {
497            let a: i32 = a.try_into().ok()?;
498            let b: i32 = b.try_into().ok()?;
499            Some(Lit::Bool(a == -b))
500        }
501        Expr::FlatProductEq(_, a, b, c) => {
502            let a: i32 = a.try_into().ok()?;
503            let b: i32 = b.try_into().ok()?;
504            let c: i32 = c.try_into().ok()?;
505            Some(Lit::Bool(a * b == c))
506        }
507        Expr::FlatWeightedSumLeq(_, cs, vs, total) => {
508            let cs: Vec<i32> = cs
509                .iter()
510                .map(|x| TryInto::<i32>::try_into(x).ok())
511                .collect::<Option<Vec<i32>>>()?;
512            let vs: Vec<i32> = vs
513                .iter()
514                .map(|x| TryInto::<i32>::try_into(x).ok())
515                .collect::<Option<Vec<i32>>>()?;
516            let total: i32 = total.try_into().ok()?;
517
518            let sum: i32 = izip!(cs, vs).fold(0, |acc, (c, v)| acc + (c * v));
519
520            Some(Lit::Bool(sum <= total))
521        }
522        Expr::FlatWeightedSumGeq(_, cs, vs, total) => {
523            let cs: Vec<i32> = cs
524                .iter()
525                .map(|x| TryInto::<i32>::try_into(x).ok())
526                .collect::<Option<Vec<i32>>>()?;
527            let vs: Vec<i32> = vs
528                .iter()
529                .map(|x| TryInto::<i32>::try_into(x).ok())
530                .collect::<Option<Vec<i32>>>()?;
531            let total: i32 = total.try_into().ok()?;
532
533            let sum: i32 = izip!(cs, vs).fold(0, |acc, (c, v)| acc + (c * v));
534
535            Some(Lit::Bool(sum >= total))
536        }
537        Expr::FlatAbsEq(_, x, y) => {
538            let x: i32 = x.try_into().ok()?;
539            let y: i32 = y.try_into().ok()?;
540
541            Some(Lit::Bool(x == y.abs()))
542        }
543        Expr::UnsafePow(_, a, b) | Expr::SafePow(_, a, b) => {
544            let a: &Atom = a.try_into().ok()?;
545            let a: i32 = a.try_into().ok()?;
546
547            let b: &Atom = b.try_into().ok()?;
548            let b: i32 = b.try_into().ok()?;
549
550            if (a != 0 || b != 0) && b >= 0 {
551                Some(Lit::Int(a.pow(b as u32)))
552            } else {
553                None
554            }
555        }
556        Expr::Metavar(_, _) => None,
557        Expr::MinionElementOne(_, _, _, _) => None,
558        Expr::ToInt(_, expression) => {
559            let lit = eval_constant(expression.as_ref())?;
560            match lit {
561                Lit::Int(_) => Some(lit),
562                Lit::Bool(true) => Some(Lit::Int(1)),
563                Lit::Bool(false) => Some(Lit::Int(0)),
564                _ => None,
565            }
566        }
567        Expr::SATInt(_, _, _, _) => {
568            // TODO: If this SATInt is composed of literals, we should evaluate it back to an
569            // integer literal.
570            //
571            // This is important because `is_all_constant` currently returns true for SATInts
572            // containing no references. If we don't evaluate them here, bubble rules will skip
573            // them (thinking they'll be constant-folded later), but they'll actually reach
574            // the solver adaptors as un-encoded unsafe operations, causing panics.
575            None
576        }
577        Expr::PairwiseSum(_, a, b) => {
578            match (eval_constant(a.as_ref())?, eval_constant(b.as_ref())?) {
579                (Lit::Int(a_int), Lit::Int(b_int)) => Some(Lit::Int(a_int + b_int)),
580                _ => None,
581            }
582        }
583        Expr::PairwiseProduct(_, a, b) => {
584            match (eval_constant(a.as_ref())?, eval_constant(b.as_ref())?) {
585                (Lit::Int(a_int), Lit::Int(b_int)) => Some(Lit::Int(a_int * b_int)),
586                _ => None,
587            }
588        }
589        Expr::Defined(_, _) => todo!(),
590        Expr::Range(_, _) => todo!(),
591        Expr::Image(_, _, _) => todo!(),
592        Expr::ImageSet(_, _, _) => todo!(),
593        Expr::PreImage(_, _, _) => todo!(),
594        Expr::Inverse(_, _, _) => todo!(),
595        Expr::Restrict(_, _, _) => todo!(),
596        Expr::LexLt(_, a, b) => {
597            let lt = vec_expr_pairs_op::<i32, _>(a, b, |pairs, (a_len, b_len)| {
598                pairs
599                    .iter()
600                    .find_map(|(a, b)| match a.cmp(b) {
601                        CmpOrdering::Less => Some(true),     // First difference is <
602                        CmpOrdering::Greater => Some(false), // First difference is >
603                        CmpOrdering::Equal => None,          // No difference
604                    })
605                    .unwrap_or(a_len < b_len) // [1,1] <lex [1,1,x]
606            })?;
607            Some(lt.into())
608        }
609        Expr::LexLeq(_, a, b) => {
610            let lt = vec_expr_pairs_op::<i32, _>(a, b, |pairs, (a_len, b_len)| {
611                pairs
612                    .iter()
613                    .find_map(|(a, b)| match a.cmp(b) {
614                        CmpOrdering::Less => Some(true),
615                        CmpOrdering::Greater => Some(false),
616                        CmpOrdering::Equal => None,
617                    })
618                    .unwrap_or(a_len <= b_len) // [1,1] <=lex [1,1,x]
619            })?;
620            Some(lt.into())
621        }
622        Expr::LexGt(_, a, b) => eval_constant(&Expr::LexLt(Metadata::new(), b.clone(), a.clone())),
623        Expr::LexGeq(_, a, b) => {
624            eval_constant(&Expr::LexLeq(Metadata::new(), b.clone(), a.clone()))
625        }
626        Expr::FlatLexLt(_, a, b) => {
627            let lt = atoms_pairs_op::<i32, _>(a, b, |pairs, (a_len, b_len)| {
628                pairs
629                    .iter()
630                    .find_map(|(a, b)| match a.cmp(b) {
631                        CmpOrdering::Less => Some(true),
632                        CmpOrdering::Greater => Some(false),
633                        CmpOrdering::Equal => None,
634                    })
635                    .unwrap_or(a_len < b_len)
636            })?;
637            Some(lt.into())
638        }
639        Expr::FlatLexLeq(_, a, b) => {
640            let lt = atoms_pairs_op::<i32, _>(a, b, |pairs, (a_len, b_len)| {
641                pairs
642                    .iter()
643                    .find_map(|(a, b)| match a.cmp(b) {
644                        CmpOrdering::Less => Some(true),
645                        CmpOrdering::Greater => Some(false),
646                        CmpOrdering::Equal => None,
647                    })
648                    .unwrap_or(a_len <= b_len)
649            })?;
650            Some(lt.into())
651        }
652    }
653}
654
655pub fn un_op<T, A>(f: fn(T) -> A, a: &Expr) -> Option<A>
656where
657    T: TryFrom<Lit>,
658{
659    let a = unwrap_expr::<T>(a)?;
660    Some(f(a))
661}
662
663pub fn bin_op<T, A>(f: fn(T, T) -> A, a: &Expr, b: &Expr) -> Option<A>
664where
665    T: TryFrom<Lit>,
666{
667    let a = unwrap_expr::<T>(a)?;
668    let b = unwrap_expr::<T>(b)?;
669    Some(f(a, b))
670}
671
672#[allow(dead_code)]
673pub fn tern_op<T, A>(f: fn(T, T, T) -> A, a: &Expr, b: &Expr, c: &Expr) -> Option<A>
674where
675    T: TryFrom<Lit>,
676{
677    let a = unwrap_expr::<T>(a)?;
678    let b = unwrap_expr::<T>(b)?;
679    let c = unwrap_expr::<T>(c)?;
680    Some(f(a, b, c))
681}
682
683pub fn vec_op<T, A>(f: fn(Vec<T>) -> A, a: &[Expr]) -> Option<A>
684where
685    T: TryFrom<Lit>,
686{
687    let a = a.iter().map(unwrap_expr).collect::<Option<Vec<T>>>()?;
688    Some(f(a))
689}
690
691pub fn vec_lit_op<T, A>(f: fn(Vec<T>) -> A, a: &Expr) -> Option<A>
692where
693    T: TryFrom<Lit>,
694{
695    Some(f(eval_list_items(a)?))
696}
697
698type PairsCallback<T, A> = fn(Vec<(T, T)>, (usize, usize)) -> A;
699
700/// Calls the given function on each consecutive pair of elements in the list expressions.
701/// Also passes the length of the two lists.
702fn vec_expr_pairs_op<T, A>(a: &Expr, b: &Expr, f: PairsCallback<T, A>) -> Option<A>
703where
704    T: TryFrom<Lit>,
705{
706    let a_exprs = a.clone().unwrap_matrix_unchecked()?.0;
707    let b_exprs = b.clone().unwrap_matrix_unchecked()?.0;
708    let lens = (a_exprs.len(), b_exprs.len());
709
710    let lit_pairs = std::iter::zip(a_exprs, b_exprs)
711        .map(|(a, b)| Some((unwrap_expr(&a)?, unwrap_expr(&b)?)))
712        .collect::<Option<Vec<(T, T)>>>()?;
713    Some(f(lit_pairs, lens))
714}
715
716/// Same as [`vec_expr_pairs_op`], but over slices of atoms.
717fn atoms_pairs_op<T, A>(a: &[Atom], b: &[Atom], f: PairsCallback<T, A>) -> Option<A>
718where
719    T: TryFrom<Atom>,
720{
721    let lit_pairs = Iterator::zip(a.iter(), b.iter())
722        .map(|(a, b)| Some((a.clone().try_into().ok()?, b.clone().try_into().ok()?)))
723        .collect::<Option<Vec<(T, T)>>>()?;
724    Some(f(lit_pairs, (a.len(), b.len())))
725}
726
727pub fn opt_vec_op<T, A>(f: fn(Vec<T>) -> Option<A>, a: &[Expr]) -> Option<A>
728where
729    T: TryFrom<Lit>,
730{
731    let a = a.iter().map(unwrap_expr).collect::<Option<Vec<T>>>()?;
732    f(a)
733}
734
735pub fn opt_vec_lit_op<T, A>(f: fn(Vec<T>) -> Option<A>, a: &Expr) -> Option<A>
736where
737    T: TryFrom<Lit>,
738{
739    f(eval_list_items(a)?)
740}
741
742#[allow(dead_code)]
743pub fn flat_op<T, A>(f: fn(Vec<T>, T) -> A, a: &[Expr], b: &Expr) -> Option<A>
744where
745    T: TryFrom<Lit>,
746{
747    let a = a.iter().map(unwrap_expr).collect::<Option<Vec<T>>>()?;
748    let b = unwrap_expr::<T>(b)?;
749    Some(f(a, b))
750}
751
752pub fn unwrap_expr<T: TryFrom<Lit>>(expr: &Expr) -> Option<T> {
753    let c = eval_constant(expr)?;
754    TryInto::<T>::try_into(c).ok()
755}
756
757fn eval_list_items<T>(expr: &Expr) -> Option<Vec<T>>
758where
759    T: TryFrom<Lit>,
760{
761    if let Some(items) = expr
762        .clone()
763        .unwrap_matrix_unchecked()
764        .map(|(items, _)| items)
765    {
766        return items.iter().map(unwrap_expr).collect();
767    }
768
769    let Lit::AbstractLiteral(list) = eval_constant(expr)? else {
770        return None;
771    };
772
773    let items = list.unwrap_list()?;
774    items
775        .iter()
776        .cloned()
777        .map(TryInto::try_into)
778        .collect::<Result<Vec<_>, _>>()
779        .ok()
780}
781
782fn eval_constant_comprehension(comprehension: &Comprehension) -> Option<Lit> {
783    let mut values = Vec::new();
784    eval_comprehension_qualifiers(comprehension, 0, &mut values)?;
785    Some(Lit::AbstractLiteral(
786        AbstractLiteral::matrix_implied_indices(values),
787    ))
788}
789
790fn eval_comprehension_qualifiers(
791    comprehension: &Comprehension,
792    qualifier_index: usize,
793    values: &mut Vec<Lit>,
794) -> Option<()> {
795    if qualifier_index == comprehension.qualifiers.len() {
796        values.push(eval_constant(&comprehension.return_expression)?);
797        return Some(());
798    }
799
800    match &comprehension.qualifiers[qualifier_index] {
801        ComprehensionQualifier::Generator { ptr } => {
802            let domain = ptr.domain()?;
803            let generator_values = domain.resolve()?.values().ok()?.collect_vec();
804
805            for value in generator_values {
806                with_temporary_quantified_binding(ptr, &value, || {
807                    eval_comprehension_qualifiers(comprehension, qualifier_index + 1, values)
808                })?;
809            }
810        }
811        ComprehensionQualifier::ExpressionGenerator { ptr } => {
812            // clone immediately so the read lock guard is dropped
813            let expr = ptr.as_quantified_expr()?.clone();
814            let generator_values = generator_values_from_expr(&expr)?;
815
816            for value in generator_values {
817                with_temporary_quantified_binding(ptr, &value, || {
818                    eval_comprehension_qualifiers(comprehension, qualifier_index + 1, values)
819                })?;
820            }
821        }
822        ComprehensionQualifier::Condition(condition) => match eval_constant(condition)? {
823            Lit::Bool(true) => {
824                eval_comprehension_qualifiers(comprehension, qualifier_index + 1, values)?
825            }
826            Lit::Bool(false) => {}
827            _ => return None,
828        },
829    }
830
831    Some(())
832}
833
834fn generator_values_from_expr(expr: &Expr) -> Option<Vec<Lit>> {
835    match eval_constant(expr)? {
836        Lit::AbstractLiteral(AbstractLiteral::Set(values))
837        | Lit::AbstractLiteral(AbstractLiteral::MSet(values))
838        | Lit::AbstractLiteral(AbstractLiteral::Tuple(values)) => Some(values),
839        Lit::AbstractLiteral(list) => list.unwrap_list().cloned(),
840        _ => None,
841    }
842}
843
844fn with_temporary_quantified_binding<T>(
845    quantified: &crate::ast::DeclarationPtr,
846    value: &Lit,
847    f: impl FnOnce() -> Option<T>,
848) -> Option<T> {
849    let mut targets = vec![quantified.clone()];
850    if let DeclarationKind::Quantified(inner) = &*quantified.kind()
851        && let Some(generator) = inner.generator()
852    {
853        targets.push(generator.clone());
854    }
855
856    let mut originals = Vec::with_capacity(targets.len());
857    for mut target in targets {
858        let old_kind = target.replace_kind(DeclarationKind::TemporaryValueLetting(Expr::Atomic(
859            Metadata::new(),
860            Atom::Literal(value.clone()),
861        )));
862        originals.push((target, old_kind));
863    }
864
865    let result = f();
866
867    for (mut target, old_kind) in originals.into_iter().rev() {
868        let _ = target.replace_kind(old_kind);
869    }
870
871    result
872}