1
use std::collections::HashSet;
2

            
3
use indexmap::IndexMap;
4

            
5
use crate::ast::Typeable;
6
use crate::{
7
    ast::{
8
        AbstractLiteral, Atom, DomainPtr, Expression as Expr, GroundDomain, Literal as Lit,
9
        Metadata, Moo, Range, ReturnType,
10
    },
11
    into_matrix_expr,
12
    rule_engine::{ApplicationError::RuleNotApplicable, ApplicationResult, RuleEffect},
13
};
14

            
15
/// Constant comparison shape used when dominating bounds under `And`.
16
///
17
/// Only same-operator bounds on the same atomic LHS are merged. Integer strictness is left alone
18
/// (`x > k` is not rewritten to `x >= k+1`) so later solver-family normalisers stay in control.
19
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
20
enum ConstantBoundOp {
21
    /// Keep the largest RHS: `x > a /\ x > b` ~> `x > max(a, b)`.
22
    Gt,
23
    /// Keep the largest RHS: `x >= a /\ x >= b` ~> `x >= max(a, b)`.
24
    Geq,
25
    /// Keep the smallest RHS: `x < a /\ x < b` ~> `x < min(a, b)`.
26
    Lt,
27
    /// Keep the smallest RHS: `x <= a /\ x <= b` ~> `x <= min(a, b)`.
28
    Leq,
29
}
30

            
31
impl ConstantBoundOp {
32
    /// Whether a larger RHS is the stronger bound for this operator.
33
104101
    fn prefers_larger_rhs(self) -> bool {
34
104101
        matches!(self, ConstantBoundOp::Gt | ConstantBoundOp::Geq)
35
104101
    }
36
}
37

            
38
/// Normalises integer ranges so equivalent domains compare structurally equal.
39
6
fn normalise_int_domain(domain: &GroundDomain) -> GroundDomain {
40
6
    match domain {
41
        GroundDomain::Int(ranges, representation) => GroundDomain::Int(
42
5
            Range::squeeze(
43
5
                &ranges
44
5
                    .iter()
45
5
                    .map(|range| Range::new(range.low().copied(), range.high().copied()))
46
                    .collect::<Vec<_>>(),
47
            ),
48
5
            representation.clone(),
49
        ),
50
1
        _ => domain.clone(),
51
    }
52
6
}
53

            
54
/// Returns whether `expr` is safe after resolving any referenced expressions.
55
83010894
fn is_semantically_safe(expr: &Expr) -> bool {
56
119603266
    fn helper(expr: &Expr, resolving: &mut HashSet<crate::ast::serde::ObjId>) -> bool {
57
119603266
        if matches!(
58
119603266
            expr,
59
            Expr::UnsafeDiv(_, _, _)
60
                | Expr::UnsafeMod(_, _, _)
61
                | Expr::UnsafePow(_, _, _)
62
                | Expr::UnsafeIndex(_, _, _)
63
                | Expr::Bubble(_, _, _)
64
                | Expr::UnsafeSlice(_, _, _)
65
                | Expr::Pred(_, _)
66
                | Expr::Succ(_, _)
67
        ) {
68
11128175
            return false;
69
108475091
        }
70

            
71
        // Applying a partial function is undefined outside the positions it defines, so it has to
72
        // keep its undefinedness until a bubble discharges it.
73
108475091
        if let Expr::Image(_, subject, argument) = expr
74
705746
            && crate::ast::expressions::image_can_be_undefined(subject, argument)
75
        {
76
630230
            return false;
77
107844861
        }
78

            
79
107844861
        if let Expr::Atomic(_, Atom::Reference(reference)) = expr {
80
64627024
            let id = reference.id();
81
64627024
            if !resolving.insert(id.clone()) {
82
                return false;
83
64627024
            }
84
64627024
            let is_safe = reference
85
12
                .with_resolved_expression(|resolved| helper(resolved, resolving))
86
64627024
                .unwrap_or(true);
87
64627024
            resolving.remove(&id);
88
64627024
            return is_safe;
89
43217837
        }
90

            
91
43217837
        let mut is_safe = true;
92
43219247
        expr.for_each_expr_child(&mut |child| {
93
37929066
            if is_safe {
94
36592360
                is_safe = helper(child, resolving);
95
1336706
            }
96
37929066
        });
97
43217837
        is_safe
98
119603266
    }
99

            
100
83010894
    helper(expr, &mut HashSet::new())
101
83010894
}
102

            
103
/// Tries to decide `expr in domain` from resolved domains alone.
104
3
fn simplify_in_domain(expr: &Expr, domain: &DomainPtr) -> Option<bool> {
105
3
    if !is_semantically_safe(expr) {
106
        return None;
107
3
    }
108

            
109
3
    let expr_domain = resolved_ground_domain_of_for_partial_eval(expr)?;
110
3
    let domain = domain.resolve().ok()?;
111
3
    let intersection = expr_domain.intersect(&domain).ok()?;
112

            
113
3
    if normalise_int_domain(&intersection) == normalise_int_domain(expr_domain.as_ref()) {
114
1
        return Some(true);
115
2
    }
116

            
117
2
    if intersection.return_type() == ReturnType::Int && intersection.length().ok() == Some(0) {
118
1
        return Some(false);
119
1
    }
120

            
121
1
    None
122
3
}
123

            
124
/// Extracts an integer when `expr` is known to be a singleton integer value.
125
48150703
fn singleton_int_value(expr: &Expr) -> Option<i32> {
126
48150703
    if let Ok(value) = expr.try_into() {
127
44611744
        return Some(value);
128
3538959
    }
129

            
130
3538959
    let domain = resolved_ground_domain_of_for_partial_eval(expr)?;
131
3497419
    let GroundDomain::Int(ranges, _) = domain.as_ref() else {
132
69719
        return None;
133
    };
134
3427700
    let [range] = ranges.as_slice() else {
135
465
        return None;
136
    };
137
3427235
    let (Some(low), Some(high)) = (range.low(), range.high()) else {
138
        return None;
139
    };
140

            
141
3427235
    if low == high { Some(*low) } else { None }
142
48150703
}
143

            
144
/// Extracts a singleton integer without deriving the domain of a compound expression.
145
///
146
/// Local partial evaluation runs on every dirty ancestor. Calling `domain_of` for arithmetic
147
/// expressions here can enumerate the Cartesian product of both operand domains, turning a cheap
148
/// node-local check into the dominant translation cost. Literal and declaration-domain lookup are
149
/// the constant-size cases needed to fold operations such as `x ** 2` for `x : int(2..2)`.
150
234011
fn cheap_singleton_int_value(expr: &Expr) -> Option<i32> {
151
234011
    match expr {
152
937
        Expr::Atomic(_, Atom::Literal(Lit::Int(value))) => Some(*value),
153
        Expr::Atomic(_, Atom::Reference(reference)) => {
154
16043
            let domain = reference.domain()?.resolve().ok()?;
155
16043
            let GroundDomain::Int(ranges, _) = domain.as_ref() else {
156
                return None;
157
            };
158
16043
            let [range] = ranges.as_slice() else {
159
                return None;
160
            };
161
16043
            let (Some(low), Some(high)) = (range.low(), range.high()) else {
162
                return None;
163
            };
164
16043
            (low == high).then_some(*low)
165
        }
166
217031
        _ => None,
167
    }
168
234011
}
169

            
170
159541
fn matrix_index_offset(index_domain: &DomainPtr, index: i32) -> Option<usize> {
171
159541
    integer_index_offset(index_domain.as_int_ground()?, index)
172
159541
}
173

            
174
22692
fn ground_matrix_index_offset(index_domain: &GroundDomain, index: i32) -> Option<usize> {
175
22692
    let GroundDomain::Int(ranges, _) = index_domain else {
176
        return None;
177
    };
178
22692
    integer_index_offset(ranges, index)
179
22692
}
180

            
181
/// Locate a label by its domain position, including gaps, without enumerating ranges.
182
182233
fn integer_index_offset(ranges: &[Range<i32>], index: i32) -> Option<usize> {
183
182233
    let mut offset = 0usize;
184
182233
    for range in ranges {
185
204925
        let lower = i64::from(*range.low()?);
186
204925
        let index = i64::from(index);
187
204925
        let upper = range.high().map(|value| i64::from(*value));
188
204925
        if index >= lower && upper.is_none_or(|upper| index <= upper) {
189
159541
            return offset.checked_add(usize::try_from(index - lower).ok()?);
190
45384
        }
191
45384
        let length = (upper? - lower + 1).max(0);
192
45384
        offset = offset.checked_add(usize::try_from(length).ok()?)?;
193
    }
194
22692
    None
195
182233
}
196

            
197
/// Selects one element from a matrix literal, including a referenced constant matrix.
198
///
199
/// This deliberately clones only the selected element. Resolving the complete matrix into an
200
/// owned `Vec` for every index makes N selections from an N-element matrix quadratic.
201
44627523
fn resolve_matrix_element(subject: &Expr, index: i32) -> Option<Expr> {
202
44627523
    match subject {
203
        Expr::TypeAnnotation(_, inner, _) | Expr::DomainAnnotation(_, inner, _) => {
204
            resolve_matrix_element(inner, index)
205
        }
206
159541
        Expr::AbstractLiteral(_, AbstractLiteral::Matrix(elems, index_domain)) => elems
207
159541
            .get(matrix_index_offset(index_domain, index)?)
208
            .cloned(),
209
        Expr::Atomic(
210
            _,
211
            Atom::Literal(Lit::AbstractLiteral(AbstractLiteral::Matrix(elems, index_domain))),
212
11470
        ) => elems
213
11470
            .get(ground_matrix_index_offset(index_domain, index)?)
214
            .cloned()
215
            .map(|literal| Expr::Atomic(Metadata::new(), Atom::Literal(literal))),
216
43109004
        Expr::Atomic(_, Atom::Reference(reference)) => reference
217
11222
            .with_resolved_expression(|resolved| resolve_matrix_element(resolved, index))
218
            .flatten()
219
43109004
            .or_else(|| {
220
                // Computed constant lettings are uncommon, but retain support for them. This
221
                // fallback may materialise the value; direct matrix lettings above do not.
222
                let Lit::AbstractLiteral(AbstractLiteral::Matrix(elems, index_domain)) =
223
43109004
                    reference.resolve_constant()?
224
                else {
225
                    return None;
226
                };
227
11222
                elems
228
11222
                    .get(ground_matrix_index_offset(&index_domain, index)?)
229
                    .cloned()
230
                    .map(|literal| Expr::Atomic(Metadata::new(), Atom::Literal(literal)))
231
43109004
            }),
232
1347508
        _ => None,
233
    }
234
44627523
}
235

            
236
/// Resolves domains for partial evaluation while avoiding malformed indexing panics.
237
33743043
fn resolved_ground_domain_of_for_partial_eval(expr: &Expr) -> Option<Moo<GroundDomain>> {
238
33743043
    match expr {
239
        Expr::SafeIndex(_, subject, _) => {
240
525047
            let subject_domain = resolved_ground_domain_of_for_partial_eval(subject)?;
241
525047
            let GroundDomain::Matrix(elem_domain, _, _) = subject_domain.as_ref() else {
242
31558
                return None;
243
            };
244

            
245
493489
            Some(elem_domain.clone())
246
        }
247
        Expr::SafeSlice(_, subject, indices) => {
248
            let subject_domain = resolved_ground_domain_of_for_partial_eval(subject)?;
249
            let GroundDomain::Matrix(elem_domain, index_domains, _) = subject_domain.as_ref()
250
            else {
251
                return None;
252
            };
253
            let sliced_dimension = indices.iter().position(Option::is_none);
254

            
255
            match sliced_dimension {
256
                Some(dimension) => Some(Moo::new(GroundDomain::Matrix(
257
                    elem_domain.clone(),
258
                    vec![index_domains[dimension].clone()],
259
                    None,
260
                ))),
261
                None => Some(elem_domain.clone()),
262
            }
263
        }
264
20894
        Expr::UnsafeIndex(_, _, _) | Expr::UnsafeSlice(_, _, _) => None,
265
33197102
        _ => expr.domain_of()?.resolve().ok(),
266
    }
267
33743043
}
268

            
269
/// Whether `expr` is an undefined value whose domain is empty.
270
///
271
/// `min`/`max` of an empty collection carries an empty domain despite being unsafe.
272
/// Enum neighbours also carry useful partial domains and are handled separately below.
273
41086221
fn is_empty_min_max(expr: &Expr) -> bool {
274
41086221
    matches!(expr, Expr::Min(_, values) | Expr::Max(_, values) if is_empty_matrix_operand(values))
275
41086221
}
276

            
277
/// Whether an unsafe expression's domain still describes all values it can take.
278
/// An empty domain rules out both equality and disequality under relational semantics.
279
5255775
fn can_derive_unsafe_domain(expr: &Expr) -> bool {
280
5255775
    matches!(
281
5255775
        expr,
282
        Expr::Image(_, _, _) | Expr::Pred(_, _) | Expr::Succ(_, _)
283
    )
284
5255775
}
285

            
286
/// Tries to decide `expr = lit` and `expr != lit` from the resolved domain of `expr`.
287
///
288
/// Each direction is decided separately, because an expression that can be undefined does not
289
/// settle both at once: where it is undefined, relational semantics make the containing boolean
290
/// false, which agrees with a `false` equality but contradicts a `true` disequality.
291
34619694
fn simplify_comparison_with_literal(
292
34619694
    expr: &Expr,
293
34619694
    lit: &Lit,
294
34619694
) -> Option<(Option<bool>, Option<bool>)> {
295
    // Deriving the domain of a compound expression enumerates its value set, and combining
296
    // operands takes the Cartesian product of those sets -- packed set representations reach tens
297
    // of thousands of values. An unsafe expression can still be decided below -- an empty
298
    // `min`/`max`, or a literal its domain cannot hold -- but nothing else can, so a safe
299
    // expression is worth the lookup unconditionally and an unsafe one only for those shapes.
300
34619694
    let is_safe = is_semantically_safe(expr);
301
34619694
    if !is_safe && !is_empty_min_max(expr) && !can_derive_unsafe_domain(expr) {
302
4940660
        return None;
303
29679034
    }
304

            
305
29679034
    let expr_domain = resolved_ground_domain_of_for_partial_eval(expr)?;
306

            
307
    // An empty domain represents an undefined value. Under relational semantics the closest
308
    // containing Boolean expression is false, for both equality and disequality.
309
29450252
    if matches!(expr_domain.as_ref(), GroundDomain::Empty(_)) {
310
13640
        return Some((Some(false), Some(false)));
311
29436612
    }
312

            
313
29436612
    if !expr_domain.contains(lit).ok()? {
314
        // A representation rewrite can temporarily leave one side in its source shape and the
315
        // other in its represented shape (for example, `record = tuple`). The source domain does
316
        // not contain represented literals, but that does not make the original comparison false.
317
125389
        if let Expr::Atomic(_, Atom::Reference(reference)) = expr
318
60196
            && !reference.ptr().reprs().is_empty()
319
        {
320
28799
            return None;
321
96590
        }
322
        // No value the expression can take equals the literal, and where it is undefined the
323
        // equality is false as well -- so the equality is false either way. The disequality is
324
        // only true where the expression is defined, so it needs safety.
325
96590
        return Some((Some(false), is_safe.then_some(true)));
326
29311223
    }
327

            
328
29311223
    if !is_safe {
329
315115
        return None;
330
28996108
    }
331

            
332
28996108
    match (expr_domain.as_ref(), lit) {
333
864596
        (GroundDomain::Bool, Lit::Bool(_)) => None,
334
        (GroundDomain::Int(ranges, _), Lit::Int(value)) => {
335
23127798
            let [range] = ranges.as_slice() else {
336
688336
                return None;
337
            };
338
22439462
            let (Some(low), Some(high)) = (range.low(), range.high()) else {
339
84
                return None;
340
            };
341

            
342
22439378
            if low == high && low == value {
343
120466
                Some((Some(true), Some(false)))
344
            } else {
345
22318912
                None
346
            }
347
        }
348
5003714
        _ => None,
349
    }
350
34619694
}
351

            
352
/// Whether deciding a comparison against `expr` is worth a domain lookup in this mode.
353
///
354
/// The local evaluator runs on every dirty ancestor after every rewrite, so it only derives a
355
/// domain when that is a constant-size lookup: a declaration's own domain, or the empty domain of
356
/// an empty `min`/`max`. Deep evaluation runs once per expansion and can afford the general case.
357
70436500
fn comparison_domain_lookup_is_cheap(expr: &Expr, mode: PartialEvalMode) -> bool {
358
70436500
    mode == PartialEvalMode::Deep
359
48707482
        || matches!(expr, Expr::Atomic(_, Atom::Reference(_)))
360
35830446
        || is_empty_min_max(expr)
361
70436500
}
362

            
363
/// Tries to decide reflexive equality and inequality when both sides are semantically safe.
364
27173932
fn simplify_reflexive_comparison(x: &Expr, y: &Expr) -> Option<(bool, bool)> {
365
27173932
    if x.identical_atom_to(y) && is_semantically_safe(x) && is_semantically_safe(y) {
366
46128
        return Some((true, false));
367
27127804
    }
368

            
369
27127804
    if is_semantically_safe(x) && is_semantically_safe(y) && x == y {
370
3100
        return Some((true, false));
371
27124704
    }
372

            
373
27124704
    None
374
27173932
}
375

            
376
93254517
fn simplify_reflexive_comparison_with_mode(
377
93254517
    x: &Expr,
378
93254517
    y: &Expr,
379
93254517
    mode: PartialEvalMode,
380
93254517
) -> Option<(bool, bool)> {
381
93254517
    match mode {
382
27173932
        PartialEvalMode::Deep => simplify_reflexive_comparison(x, y),
383
66080585
        PartialEvalMode::Local => x.identical_atom_to(y).then_some((true, false)),
384
    }
385
93254517
}
386

            
387
226368490
pub fn run_partial_evaluator(expr: &Expr) -> ApplicationResult {
388
226368490
    run_partial_evaluator_with_mode(expr, PartialEvalMode::Deep)
389
226368490
}
390

            
391
/// Partially evaluates `expr` using only information already available at the focused node.
392
///
393
/// This is intended for the main rewriter, where recursive simplification is supplied by the
394
/// scheduler. Use [`run_partial_evaluator`] when a caller explicitly wants semantic checks that
395
/// can inspect referenced expressions.
396
1755571594
pub fn run_partial_evaluator_local(expr: &Expr) -> ApplicationResult {
397
1755571594
    run_partial_evaluator_with_mode(expr, PartialEvalMode::Local)
398
1755571594
}
399

            
400
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
401
enum PartialEvalMode {
402
    Deep,
403
    Local,
404
}
405

            
406
/// Rewrites `x = true` / `true = x` to `x` when `x` is a non-literal boolean atom.
407
///
408
/// Nested uses such as `(x = true) <-> and([y = true, ...])` otherwise force Minion flattening to
409
/// introduce aux variables for the left-hand `Eq`, because both sides of the outer equality are
410
/// non-atomic. Lowering the tautological `= true` first keeps a boolean decision variable atomic
411
/// so later equality/reify rules can target it directly.
412
///
413
/// Literal–literal equalities are left alone for constant folding. Non-boolean atoms are refused.
414
101459529
pub fn try_lower_bool_atom_eq_true(expr: &Expr) -> Option<Expr> {
415
101459529
    let Expr::Eq(_, left, right) = expr else {
416
17052
        return None;
417
    };
418

            
419
101442477
    let atom = match (left.as_ref(), right.as_ref()) {
420
        (Expr::Atomic(_, Atom::Literal(Lit::Bool(true))), Expr::Atomic(_, atom))
421
31
            if !matches!(atom, Atom::Literal(_)) =>
422
        {
423
31
            right.as_ref()
424
        }
425
        (Expr::Atomic(_, atom), Expr::Atomic(_, Atom::Literal(Lit::Bool(true))))
426
74138
            if !matches!(atom, Atom::Literal(_)) =>
427
        {
428
74138
            left.as_ref()
429
        }
430
101368308
        _ => return None,
431
    };
432

            
433
74169
    if atom.return_type() != ReturnType::Bool {
434
31
        return None;
435
74138
    }
436

            
437
74138
    Some(atom.clone())
438
101459529
}
439

            
440
1981940084
fn run_partial_evaluator_with_mode(expr: &Expr, mode: PartialEvalMode) -> ApplicationResult {
441
    // NOTE: If nothing changes, we must return RuleNotApplicable, or the rewriter will try this
442
    // rule infinitely!
443
    // This is why we always check whether we found a constant or not.
444
1981940084
    match expr {
445
637
        Expr::Difference(_, _, _) => Err(RuleNotApplicable),
446
3162
        Expr::Union(_, _, _) => Err(RuleNotApplicable),
447
4897801
        Expr::In(_, _, _) => Err(RuleNotApplicable),
448
8804
        Expr::Intersect(_, _, _) => Err(RuleNotApplicable),
449
        Expr::Supset(_, _, _) => Err(RuleNotApplicable),
450
        Expr::SupsetEq(_, _, _) => Err(RuleNotApplicable),
451
103106
        Expr::Subset(_, _, _) => Err(RuleNotApplicable),
452
168350
        Expr::SubsetEq(_, _, _) => Err(RuleNotApplicable),
453
277354481
        Expr::AbstractLiteral(_, _) => Err(RuleNotApplicable),
454
883159
        Expr::CatchUndef(_, _, _) => Err(RuleNotApplicable),
455
5246404
        Expr::Comprehension(_, _) => Err(RuleNotApplicable),
456
        Expr::DominanceRelation(_, _) => Err(RuleNotApplicable),
457
9157
        Expr::TypeAnnotation(_, _, _) => Err(RuleNotApplicable),
458
6714
        Expr::DomainAnnotation(_, _, _) => Err(RuleNotApplicable),
459
        Expr::FromSolution(_, _) => Err(RuleNotApplicable),
460
        Expr::Metavar(_, _) => Err(RuleNotApplicable),
461
12769765
        Expr::UnsafeIndex(_, _, _) => Err(RuleNotApplicable),
462
1213345
        Expr::UnsafeSlice(_, _, _) => Err(RuleNotApplicable),
463
        Expr::Table(_, _, _) | Expr::FlatTable(..) | Expr::FlatShortTable(..) => {
464
1766845
            Err(RuleNotApplicable)
465
        }
466
663648
        Expr::NegativeTable(_, _, _) | Expr::ShortTable(_, _, _) => Err(RuleNotApplicable),
467
932232
        Expr::AtLeast(_, _, _, _) => Err(RuleNotApplicable),
468
343790
        Expr::AtMost(_, _, _, _) => Err(RuleNotApplicable),
469
6169
        Expr::Gcc(_, _, _, _) | Expr::GccWeak(_, _, _, _) => Err(RuleNotApplicable),
470
461063
        Expr::RecordField(_, _, _) => Err(RuleNotApplicable),
471
        Expr::AttributeAsConstraint(_, _, _, _) => Err(RuleNotApplicable),
472
        Expr::SafeIndex(_, subject, indices) => {
473
            // partially evaluate matrix literals indexed by a constant.
474
48150703
            if indices.is_empty() {
475
                return Err(RuleNotApplicable);
476
48150703
            }
477

            
478
            // the leading index must be fixed to a single value
479
48150703
            let index = singleton_int_value(&indices[0]).ok_or(RuleNotApplicable)?;
480

            
481
44616301
            let selected = resolve_matrix_element(subject, index).ok_or(RuleNotApplicable)?;
482
159541
            if indices.len() == 1 {
483
159541
                Ok(RuleEffect::pure(selected))
484
            } else {
485
                Ok(RuleEffect::pure(Expr::SafeIndex(
486
                    Metadata::new(),
487
                    Moo::new(selected),
488
                    indices[1..].to_vec(),
489
                )))
490
            }
491
        }
492
482086
        Expr::SafeSlice(_, _, _) => Err(RuleNotApplicable),
493
        Expr::InDomain(_, x, domain) => {
494
107421
            if mode == PartialEvalMode::Deep
495
3
                && let Some(result) = simplify_in_domain(x, domain)
496
            {
497
2
                Ok(RuleEffect::pure(Expr::Atomic(
498
2
                    Metadata::new(),
499
2
                    result.into(),
500
2
                )))
501
107419
            } else if let Expr::Atomic(_, Atom::Reference(decl)) = x.as_ref() {
502
30198
                let decl_domain = decl
503
30198
                    .domain()
504
30198
                    .ok_or(RuleNotApplicable)?
505
                    .resolve()
506
                    .map_err(|_| RuleNotApplicable)?;
507
30198
                let domain = domain.resolve().map_err(|_| RuleNotApplicable)?;
508

            
509
30198
                let intersection = decl_domain
510
30198
                    .intersect(&domain)
511
                    .map_err(|_| RuleNotApplicable)?;
512

            
513
                // if the declaration's domain is a subset of domain, expr is always true.
514
30198
                if &intersection == decl_domain.as_ref() {
515
1
                    Ok(RuleEffect::pure(Expr::Atomic(Metadata::new(), true.into())))
516
                }
517
                // if no elements of declaration's domain are in the domain (i.e. they have no
518
                // intersection), expr is always false.
519
                //
520
                // Only check this when the intersection is a finite integer domain, as we
521
                // currently don't have a way to check whether other domain kinds are empty or not.
522
                //
523
                // we should expand this to cover more domain types in the future.
524
30197
                else if intersection.return_type() == ReturnType::Int
525
30197
                    && intersection.length().ok() == Some(0)
526
                {
527
1
                    Ok(RuleEffect::pure(Expr::Atomic(
528
1
                        Metadata::new(),
529
1
                        false.into(),
530
1
                    )))
531
                } else {
532
30196
                    Err(RuleNotApplicable)
533
                }
534
77221
            } else if let Expr::Atomic(_, Atom::Literal(lit)) = x.as_ref() {
535
                if domain
536
                    .resolve()
537
                    .and_then(|gd| gd.contains(lit))
538
                    .map_err(|_| RuleNotApplicable)?
539
                {
540
                    Ok(RuleEffect::pure(Expr::Atomic(Metadata::new(), true.into())))
541
                } else {
542
                    Ok(RuleEffect::pure(Expr::Atomic(
543
                        Metadata::new(),
544
                        false.into(),
545
                    )))
546
                }
547
            } else {
548
77221
                Err(RuleNotApplicable)
549
            }
550
        }
551
        Expr::Bubble(_, expr, cond) => {
552
            // definition of bubble is "expr is valid as long as cond is true"
553
            //
554
            // check if cond is true and pop the bubble!
555
2712795
            if let Expr::Atomic(_, Atom::Literal(Lit::Bool(true))) = cond.as_ref() {
556
1662585
                Ok(RuleEffect::pure(Moo::unwrap_or_clone(expr.clone())))
557
            } else {
558
1050210
                Err(RuleNotApplicable)
559
            }
560
        }
561
854604927
        Expr::Atomic(_, _) => Err(RuleNotApplicable),
562
        Expr::ToInt(_, expression) => {
563
73200406
            if expression.return_type() == ReturnType::Int {
564
                Ok(RuleEffect::pure(Moo::unwrap_or_clone(expression.clone())))
565
            } else {
566
73200406
                Err(RuleNotApplicable)
567
            }
568
        }
569
379936
        Expr::Abs(m, e) => match e.as_ref() {
570
4526
            Expr::Neg(_, inner) => Ok(RuleEffect::pure(Expr::Abs(m.clone(), inner.clone()))),
571
375410
            _ => Err(RuleNotApplicable),
572
        },
573
        Expr::Sum(m, vec) => {
574
31906630
            let vec = vec.unwrap_list_cow().ok_or(RuleNotApplicable)?;
575
26727570
            let mut acc = 0;
576
26727570
            let mut n_consts = 0;
577
26727570
            for expr in vec.iter() {
578
128256649
                if let Expr::Atomic(_, Atom::Literal(Lit::Int(x))) = expr {
579
3255798
                    acc += *x;
580
3255798
                    n_consts += 1;
581
125000851
                }
582
            }
583

            
584
26727570
            if n_consts <= 1 {
585
26695820
                return Err(RuleNotApplicable);
586
31750
            }
587

            
588
31750
            let mut new_vec: Vec<Expr> = vec
589
31750
                .iter()
590
131768
                .filter(|expr| !matches!(expr, Expr::Atomic(_, Atom::Literal(Lit::Int(_)))))
591
                .cloned()
592
                .collect();
593
31750
            if acc != 0 {
594
22754
                new_vec.push(Expr::Atomic(
595
22754
                    Default::default(),
596
22754
                    Atom::Literal(Lit::Int(acc)),
597
22754
                ));
598
8996
            }
599

            
600
31750
            Ok(RuleEffect::pure(Expr::Sum(
601
31750
                m.clone(),
602
31750
                Moo::new(into_matrix_expr![new_vec]),
603
31750
            )))
604
        }
605

            
606
        Expr::Product(m, vec) => {
607
8214385
            let mut acc = 1;
608
8214385
            let mut n_consts = 0;
609
8214385
            let vec = vec.unwrap_list_cow().ok_or(RuleNotApplicable)?;
610
8214354
            for expr in vec.iter() {
611
16433714
                if let Expr::Atomic(_, Atom::Literal(Lit::Int(x))) = expr {
612
5678000
                    acc *= *x;
613
5678000
                    n_consts += 1;
614
10755714
                }
615
            }
616

            
617
8214354
            if n_consts == 0 {
618
2536974
                return Err(RuleNotApplicable);
619
5677380
            }
620

            
621
5677380
            if acc == 0 && mode == PartialEvalMode::Local {
622
2
                return Err(RuleNotApplicable);
623
5677378
            }
624

            
625
5677378
            if acc != 0 && n_consts == 1 {
626
5676726
                return Err(RuleNotApplicable);
627
652
            }
628

            
629
652
            let mut new_vec: Vec<Expr> = vec
630
652
                .iter()
631
1924
                .filter(|expr| !matches!(expr, Expr::Atomic(_, Atom::Literal(Lit::Int(_)))))
632
                .cloned()
633
                .collect();
634

            
635
652
            new_vec.push(Expr::Atomic(
636
652
                Default::default(),
637
652
                Atom::Literal(Lit::Int(acc)),
638
652
            ));
639
652
            let new_product = Expr::Product(m.clone(), Moo::new(into_matrix_expr![new_vec]));
640

            
641
652
            if acc == 0 {
642
                // If safe, 0 * exprs ~> 0. Otherwise do not reshuffle: appending the folded
643
                // zero fights `reorder_product` (constant-first) and loops forever under the
644
                // local evaluator. Constant folding/placement is left to `reorder_product`.
645
125
                if mode == PartialEvalMode::Deep && is_semantically_safe(&new_product) {
646
125
                    Ok(RuleEffect::pure(Expr::Atomic(
647
125
                        Default::default(),
648
125
                        Atom::Literal(Lit::Int(0)),
649
125
                    )))
650
                } else {
651
                    Err(RuleNotApplicable)
652
                }
653
            } else {
654
                // acc !=0, multiple constants found
655
527
                Ok(RuleEffect::pure(new_product))
656
            }
657
        }
658

            
659
        Expr::Min(m, e) => {
660
263221
            let Some(vec) = e.unwrap_list_cow() else {
661
258788
                return Err(RuleNotApplicable);
662
            };
663
4433
            let mut acc: Option<i32> = None;
664
4433
            let mut n_consts = 0;
665
4433
            for expr in vec.iter() {
666
2139
                if let Expr::Atomic(_, Atom::Literal(Lit::Int(x))) = expr {
667
93
                    n_consts += 1;
668
93
                    acc = match acc {
669
                        Some(i) => {
670
                            if i > *x {
671
                                Some(*x)
672
                            } else {
673
                                Some(i)
674
                            }
675
                        }
676
93
                        None => Some(*x),
677
                    };
678
2046
                }
679
            }
680

            
681
4433
            if n_consts <= 1 {
682
4433
                return Err(RuleNotApplicable);
683
            }
684

            
685
            let mut new_vec: Vec<Expr> = vec
686
                .iter()
687
                .filter(|expr| !matches!(expr, Expr::Atomic(_, Atom::Literal(Lit::Int(_)))))
688
                .cloned()
689
                .collect();
690
            if let Some(i) = acc {
691
                new_vec.push(Expr::Atomic(Default::default(), Atom::Literal(Lit::Int(i))));
692
            }
693

            
694
            Ok(RuleEffect::pure(Expr::Min(
695
                m.clone(),
696
                Moo::new(into_matrix_expr![new_vec]),
697
            )))
698
        }
699

            
700
        Expr::Max(m, e) => {
701
223076
            let Some(vec) = e.unwrap_list_cow() else {
702
221154
                return Err(RuleNotApplicable);
703
            };
704

            
705
1922
            let mut acc: Option<i32> = None;
706
1922
            let mut n_consts = 0;
707
1922
            for expr in vec.iter() {
708
1767
                if let Expr::Atomic(_, Atom::Literal(Lit::Int(x))) = expr {
709
93
                    n_consts += 1;
710
93
                    acc = match acc {
711
                        Some(i) => {
712
                            if i < *x {
713
                                Some(*x)
714
                            } else {
715
                                Some(i)
716
                            }
717
                        }
718
93
                        None => Some(*x),
719
                    };
720
1674
                }
721
            }
722

            
723
1922
            if n_consts <= 1 {
724
1922
                return Err(RuleNotApplicable);
725
            }
726

            
727
            let mut new_vec: Vec<Expr> = vec
728
                .iter()
729
                .filter(|expr| !matches!(expr, Expr::Atomic(_, Atom::Literal(Lit::Int(_)))))
730
                .cloned()
731
                .collect();
732
            if let Some(i) = acc {
733
                new_vec.push(Expr::Atomic(Default::default(), Atom::Literal(Lit::Int(i))));
734
            }
735

            
736
            Ok(RuleEffect::pure(Expr::Max(
737
                m.clone(),
738
                Moo::new(into_matrix_expr![new_vec]),
739
            )))
740
        }
741
        Expr::Not(_, e1) => {
742
73839590
            let Expr::Imply(_, p, q) = e1.as_ref() else {
743
73839218
                return Err(RuleNotApplicable);
744
            };
745

            
746
372
            if mode == PartialEvalMode::Deep && !is_semantically_safe(e1) {
747
                return Err(RuleNotApplicable);
748
372
            }
749

            
750
372
            match (p.as_ref(), q.as_ref()) {
751
                (_, Expr::Atomic(_, Atom::Literal(Lit::Bool(true)))) => {
752
                    Ok(RuleEffect::pure(Expr::from(false)))
753
                }
754
                (_, Expr::Atomic(_, Atom::Literal(Lit::Bool(false)))) => {
755
                    Ok(RuleEffect::pure(Moo::unwrap_or_clone(p.clone())))
756
                }
757
                (Expr::Atomic(_, Atom::Literal(Lit::Bool(true))), _) => {
758
                    Ok(RuleEffect::pure(Expr::Not(Metadata::new(), q.clone())))
759
                }
760
                (Expr::Atomic(_, Atom::Literal(Lit::Bool(false))), _) => {
761
                    Ok(RuleEffect::pure(Expr::from(false)))
762
                }
763
372
                _ => Err(RuleNotApplicable),
764
            }
765
        }
766
        Expr::Or(m, e) => {
767
            // Empty disjunction is the Or-identity, whatever index domain the matrix carries.
768
229046277
            if is_empty_matrix_operand(e) {
769
5551
                return Ok(RuleEffect::pure(Expr::from(false)));
770
229040726
            }
771

            
772
229040726
            let Some(terms) = e.unwrap_list_cow() else {
773
810178
                return Err(RuleNotApplicable);
774
            };
775

            
776
228230548
            let mut has_changed = false;
777
228230548
            let mut non_literal_terms = 0;
778

            
779
            // Inspection pass: decide applicability from borrowed terms, so a disjunction that
780
            // does not fold costs a walk rather than a copy.
781
228230548
            for expr in terms.iter() {
782
540718727
                if let Expr::Atomic(_, Atom::Literal(Lit::Bool(x))) = expr {
783
2828895
                    has_changed = true;
784

            
785
                    // true ~~> entire or is true
786
                    // false ~~> remove false from the or
787
2828895
                    if *x {
788
1380297
                        return Ok(RuleEffect::pure(true.into()));
789
1448598
                    }
790
                } else {
791
537889832
                    non_literal_terms += 1;
792
                }
793
            }
794

            
795
            // The two supported implication tautologies, in expected O(n).
796
226850251
            if check_pairwise_or_tautologies(&terms) {
797
4588
                return Ok(RuleEffect::pure(true.into()));
798
226845663
            }
799

            
800
            // 3. empty or ~~> false
801
226845663
            if non_literal_terms == 0 {
802
                return Ok(RuleEffect::pure(false.into()));
803
226845663
            }
804

            
805
226845663
            if !has_changed {
806
226288780
                return Err(RuleNotApplicable);
807
556883
            }
808

            
809
556883
            let new_terms = terms
810
556883
                .iter()
811
2024856
                .filter(|expr| !matches!(expr, Expr::Atomic(_, Atom::Literal(Lit::Bool(_)))))
812
                .cloned()
813
                .collect::<Vec<_>>();
814

            
815
556883
            Ok(RuleEffect::pure(Expr::Or(
816
556883
                m.clone(),
817
556883
                Moo::new(into_matrix_expr![new_terms]),
818
556883
            )))
819
        }
820
        Expr::And(_, e) => {
821
            // The evaluator revisits a conjunction after each rewrite elsewhere in the model, so
822
            // establish applicability from borrowed conjuncts and only build a replacement once
823
            // the rule is known to apply. A wide `and` -- what unrolling `forAll i : D. ...`
824
            // produces -- is then walked per visit rather than copied, keeping repeated visits
825
            // linear rather than quadratic in the number of conjuncts.
826
            // Empty conjunction is the And-identity, whatever index domain the matrix carries.
827
72112404
            if is_empty_matrix_operand(e) {
828
2
                return Ok(RuleEffect::pure(Expr::from(true)));
829
72112402
            }
830

            
831
72112402
            let Some(vec) = e.unwrap_list_cow() else {
832
6718742
                return Err(RuleNotApplicable);
833
            };
834

            
835
65393660
            let mut has_changed: bool = false;
836
            // `Atom` is only interior-mutable through `DeclarationPtr`, whose `Hash`/`Eq` use the
837
            // immutable declaration id, so it is stable as a key.
838
            #[allow(clippy::mutable_key_type)]
839
65393660
            let mut distinct_bounds: HashSet<(&Atom, ConstantBoundOp)> = HashSet::new();
840
65393660
            let mut constant_bound_terms: usize = 0;
841
65393660
            for expr in vec.iter() {
842
907003073
                if let Expr::Atomic(_, Atom::Literal(Lit::Bool(x))) = expr {
843
3715865
                    if !x {
844
1321304
                        return Ok(RuleEffect::pure(Expr::Atomic(
845
1321304
                            Default::default(),
846
1321304
                            Atom::Literal(Lit::Bool(false)),
847
1321304
                        )));
848
2394561
                    }
849
2394561
                    has_changed = true;
850
903287208
                } else if let Some((lhs, op, _)) = as_constant_bound_comparison_ref(expr) {
851
584595
                    constant_bound_terms += 1;
852
584595
                    distinct_bounds.insert((lhs, op));
853
902702613
                }
854
            }
855

            
856
            // Only treat bound aggregation as a change when at least one conjunct was dominated.
857
64072356
            if constant_bound_terms > distinct_bounds.len() {
858
4528
                has_changed = true;
859
64067828
            }
860

            
861
64072356
            if !has_changed {
862
61680401
                return Err(RuleNotApplicable);
863
2391955
            }
864
2391955
            drop(distinct_bounds);
865

            
866
            // The rule applies: now build the replacement.
867
2391955
            let mut new_vec: Vec<Expr> = Vec::new();
868
            // Strongest constant bound per (atomic LHS, comparison operator), first-seen order.
869
2391955
            let mut constant_bounds: IndexMap<(Atom, ConstantBoundOp), i32> = IndexMap::new();
870
2391955
            for expr in vec.iter() {
871
6351128
                if matches!(expr, Expr::Atomic(_, Atom::Literal(Lit::Bool(_)))) {
872
2394561
                    continue;
873
3956567
                } else if let Some((lhs, op, rhs)) = as_constant_bound_comparison(expr) {
874
114178
                    merge_constant_bound(&mut constant_bounds, lhs, op, rhs);
875
                } else {
876
3842389
                    new_vec.push(expr.clone());
877
                }
878
            }
879

            
880
2391955
            for ((lhs, op), rhs) in constant_bounds {
881
10077
                new_vec.push(make_constant_bound_comparison(lhs, op, rhs));
882
            }
883

            
884
2391955
            if new_vec.is_empty() {
885
                Ok(RuleEffect::pure(Expr::from(true)))
886
            } else {
887
2391955
                Ok(RuleEffect::pure(Expr::And(
888
2391955
                    Metadata::new(),
889
2391955
                    Moo::new(into_matrix_expr![new_vec]),
890
2391955
                )))
891
            }
892
        }
893

            
894
        // similar to And, but booleans are returned wrapped in Root.
895
        Expr::Root(_, es) => {
896
1759576
            match es.as_slice() {
897
                [] => Err(RuleNotApplicable),
898
                // want to unwrap nested ands
899
5029
                [Expr::And(_, _)] => Ok(()),
900
                // root([true]) / root([false]) are already evaluated
901
1408235
                [_] => Err(RuleNotApplicable),
902
346312
                [_, _, ..] => Ok(()),
903
1408235
            }?;
904

            
905
351341
            let mut new_vec: Vec<Expr> = Vec::new();
906
351341
            let mut has_changed: bool = false;
907
351341
            for expr in es {
908
3075441
                match expr {
909
                    Expr::Atomic(_, Atom::Literal(Lit::Bool(x))) => {
910
1269238
                        has_changed = true;
911
1269238
                        if !x {
912
                            // false
913
249
                            return Ok(RuleEffect::pure(Expr::Root(
914
249
                                Metadata::new(),
915
249
                                vec![Expr::Atomic(
916
249
                                    Default::default(),
917
249
                                    Atom::Literal(Lit::Bool(false)),
918
249
                                )],
919
249
                            )));
920
1268989
                        }
921
                        // remove trues
922
                    }
923

            
924
                    // flatten ands in root, applying the same true/false rules to conjuncts
925
90285
                    Expr::And(_, vecs) => match Moo::unwrap_or_clone(vecs.clone()).into_list() {
926
                        Some(list) => {
927
90285
                            has_changed = true;
928
90285
                            for conjunct in list {
929
544412
                                match conjunct {
930
                                    Expr::Atomic(_, Atom::Literal(Lit::Bool(false))) => {
931
                                        return Ok(RuleEffect::pure(Expr::Root(
932
                                            Metadata::new(),
933
                                            vec![Expr::Atomic(
934
                                                Default::default(),
935
                                                Atom::Literal(Lit::Bool(false)),
936
                                            )],
937
                                        )));
938
                                    }
939
1
                                    Expr::Atomic(_, Atom::Literal(Lit::Bool(true))) => {}
940
544411
                                    other => new_vec.push(other),
941
                                }
942
                            }
943
                        }
944
                        None => new_vec.push(expr.clone()),
945
                    },
946
1715918
                    _ => new_vec.push(expr.clone()),
947
                }
948
            }
949

            
950
351092
            if !has_changed {
951
38813
                Err(RuleNotApplicable)
952
            } else {
953
312279
                if new_vec.is_empty() {
954
283346
                    new_vec.push(true.into());
955
28933
                }
956
312279
                Ok(RuleEffect::pure(Expr::Root(Metadata::new(), new_vec)))
957
            }
958
        }
959
        Expr::Imply(_m, x, y) => {
960
22399922
            if let Expr::Atomic(_, Atom::Literal(Lit::Bool(x))) = x.as_ref() {
961
5182296
                return if *x {
962
                    // (true) -> y ~~> y
963
2460960
                    Ok(RuleEffect::pure(Moo::unwrap_or_clone(y.clone())))
964
                } else {
965
                    // (false) -> y ~~> true
966
2721336
                    Ok(RuleEffect::pure(Expr::Atomic(Metadata::new(), true.into())))
967
                };
968
17217626
            };
969

            
970
17217626
            if let Expr::Atomic(_, Atom::Literal(Lit::Bool(y))) = y.as_ref() {
971
273411
                return if *y {
972
                    // x -> (true) ~~> true
973
129444
                    Ok(RuleEffect::pure(Expr::from(true)))
974
                } else {
975
                    // x -> (false) ~~> !x
976
143967
                    Ok(RuleEffect::pure(Expr::Not(Metadata::new(), x.clone())))
977
                };
978
16944215
            };
979

            
980
            // reflexivity: p -> p ~> true
981

            
982
            // instead of checking syntactic equivalence of a possibly deep expression,
983
            // let identical-CSE turn them into identical variables first. Then, check if they are
984
            // identical variables.
985

            
986
16944215
            if x.identical_atom_to(y.as_ref())
987
2858
                && (mode == PartialEvalMode::Local
988
6
                    || (is_semantically_safe(x) && is_semantically_safe(y)))
989
            {
990
2858
                return Ok(RuleEffect::pure(true.into()));
991
16941357
            }
992

            
993
16941357
            Err(RuleNotApplicable)
994
        }
995
        Expr::Iff(_m, x, y) => {
996
15870473
            if let Expr::Atomic(_, Atom::Literal(Lit::Bool(x))) = x.as_ref() {
997
93
                return if *x {
998
                    // (true) <-> y ~~> y
999
                    Ok(RuleEffect::pure(Moo::unwrap_or_clone(y.clone())))
                } else {
                    // (false) <-> y ~~> !y
93
                    Ok(RuleEffect::pure(Expr::Not(Metadata::new(), y.clone())))
                };
15870380
            };
15870380
            if let Expr::Atomic(_, Atom::Literal(Lit::Bool(y))) = y.as_ref() {
18
                return if *y {
                    // x <-> (true) ~~> x
18
                    Ok(RuleEffect::pure(Moo::unwrap_or_clone(x.clone())))
                } else {
                    // x <-> (false) ~~> !x
                    Ok(RuleEffect::pure(Expr::Not(Metadata::new(), x.clone())))
                };
15870362
            };
            // reflexivity: p <-> p ~> true
            // instead of checking syntactic equivalence of a possibly deep expression,
            // let identical-CSE turn them into identical variables first. Then, check if they are
            // identical variables.
15870362
            if x.identical_atom_to(y.as_ref())
93
                && (mode == PartialEvalMode::Local
                    || (is_semantically_safe(x) && is_semantically_safe(y)))
            {
93
                return Ok(RuleEffect::pure(true.into()));
15870269
            }
15870269
            Err(RuleNotApplicable)
        }
        Expr::Eq(_, x, y) => {
84734510
            if let Some((eq_result, _)) = simplify_reflexive_comparison_with_mode(x, y, mode) {
35991
                Ok(RuleEffect::pure(Expr::Atomic(
35991
                    Metadata::new(),
35991
                    Atom::Literal(Lit::Bool(eq_result)),
35991
                )))
84698519
            } else if let Expr::Atomic(_, Atom::Literal(lit)) = x.as_ref()
1403544
                && comparison_domain_lookup_is_cheap(y, mode)
978891
                && let Some((Some(eq_result), _)) = simplify_comparison_with_literal(y, lit)
            {
62
                Ok(RuleEffect::pure(Expr::Atomic(
62
                    Metadata::new(),
62
                    Atom::Literal(Lit::Bool(eq_result)),
62
                )))
84698457
            } else if let Expr::Atomic(_, Atom::Literal(lit)) = y.as_ref()
63601286
                && comparison_domain_lookup_is_cheap(x, mode)
29601070
                && let Some((Some(eq_result), _)) = simplify_comparison_with_literal(x, lit)
            {
223541
                Ok(RuleEffect::pure(Expr::Atomic(
223541
                    Metadata::new(),
223541
                    Atom::Literal(Lit::Bool(eq_result)),
223541
                )))
84474916
            } else if let Some(atom) = try_lower_bool_atom_eq_true(expr) {
74045
                Ok(RuleEffect::pure(atom))
            } else {
84400871
                Err(RuleNotApplicable)
            }
        }
        Expr::Neq(_, x, y) => {
8520007
            if let Some((_, neq_result)) = simplify_reflexive_comparison_with_mode(x, y, mode) {
19840
                Ok(RuleEffect::pure(Expr::Atomic(
19840
                    Metadata::new(),
19840
                    Atom::Literal(Lit::Bool(neq_result)),
19840
                )))
8500167
            } else if let Expr::Atomic(_, Atom::Literal(lit)) = x.as_ref()
33640
                && comparison_domain_lookup_is_cheap(y, mode)
12711
                && let Some((_, Some(neq_result))) = simplify_comparison_with_literal(y, lit)
            {
434
                Ok(RuleEffect::pure(Expr::Atomic(
434
                    Metadata::new(),
434
                    Atom::Literal(Lit::Bool(neq_result)),
434
                )))
8499733
            } else if let Expr::Atomic(_, Atom::Literal(lit)) = y.as_ref()
5398030
                && comparison_domain_lookup_is_cheap(x, mode)
4027022
                && let Some((_, Some(neq_result))) = simplify_comparison_with_literal(x, lit)
            {
6659
                Ok(RuleEffect::pure(Expr::Atomic(
6659
                    Metadata::new(),
6659
                    Atom::Literal(Lit::Bool(neq_result)),
6659
                )))
            } else {
8493074
                Err(RuleNotApplicable)
            }
        }
6234432
        Expr::Geq(_, _, _) => Err(RuleNotApplicable),
37820773
        Expr::Leq(_, _, _) => Err(RuleNotApplicable),
2008833
        Expr::Gt(_, _, _) => Err(RuleNotApplicable),
11158361
        Expr::Lt(_, _, _) => Err(RuleNotApplicable),
        Expr::Pred(_, _) => Err(RuleNotApplicable),
24
        Expr::Succ(_, _) => Err(RuleNotApplicable),
3697172
        Expr::SafeDiv(_, _, _) => Err(RuleNotApplicable),
6649087
        Expr::UnsafeDiv(_, _, _) => Err(RuleNotApplicable),
1864185
        Expr::Flatten(_, _, _) => Err(RuleNotApplicable), // TODO: check if anything can be done here
        Expr::AllDiff(m, e) => {
1703589
            let Some((vec, _)) = Moo::unwrap_or_clone(e.clone()).unwrap_matrix_unchecked() else {
865517
                return Err(RuleNotApplicable);
            };
838072
            let mut consts: HashSet<Lit> = HashSet::new();
            // A fully constant allDiff can be decided immediately.
838072
            for expr in vec {
843838
                let Expr::Atomic(_, Atom::Literal(lit)) = expr else {
834631
                    return Err(RuleNotApplicable);
                };
9207
                if !consts.insert(lit) {
2604
                    return Ok(RuleEffect::pure(Expr::Atomic(
2604
                        m.clone(),
2604
                        Atom::Literal(Lit::Bool(false)),
2604
                    )));
6603
                }
            }
837
            Ok(RuleEffect::pure(Expr::Atomic(
837
                m.clone(),
837
                Atom::Literal(Lit::Bool(true)),
837
            )))
        }
430410
        Expr::Neg(_, _) => Err(RuleNotApplicable),
        Expr::Factorial(_, _) => Err(RuleNotApplicable),
14486955
        Expr::AuxDeclaration(_, _, _) => Err(RuleNotApplicable),
7624449
        Expr::UnsafeMod(_, _, _) => Err(RuleNotApplicable),
4583832
        Expr::SafeMod(_, _, _) => Err(RuleNotApplicable),
310275
        Expr::UnsafePow(_, _, _) => Err(RuleNotApplicable),
        Expr::SafePow(_, base, exponent) => {
233077
            let base = cheap_singleton_int_value(base).ok_or(RuleNotApplicable)?;
934
            let exponent = cheap_singleton_int_value(exponent).ok_or(RuleNotApplicable)?;
934
            if exponent < 0 || (base == 0 && exponent == 0) {
2
                return Err(RuleNotApplicable);
932
            }
932
            let value = base.checked_pow(exponent as u32).ok_or(RuleNotApplicable)?;
931
            Ok(RuleEffect::pure(Expr::from(value)))
        }
1611409
        Expr::Minus(_, _, _) => Err(RuleNotApplicable),
126109
        Expr::Card(_, _) => Err(RuleNotApplicable),
        // As these are in a low level solver form, I'm assuming that these have already been
        // simplified and partially evaluated.
8047
        Expr::FlatAllDiff(_, _) => Err(RuleNotApplicable),
11811
        Expr::SmtDistinct(_, _) => Err(RuleNotApplicable),
465
        Expr::FlatAbsEq(_, _, _) => Err(RuleNotApplicable),
341
        Expr::FlatMinEq(_, _, _) => Err(RuleNotApplicable),
494301
        Expr::FlatIneq(_, _, _, _) => Err(RuleNotApplicable),
2480
        Expr::FlatMinusEq(_, _, _) => Err(RuleNotApplicable),
8298
        Expr::FlatProductEq(_, _, _, _) => Err(RuleNotApplicable),
92830
        Expr::FlatSumLeq(_, _, _) => Err(RuleNotApplicable),
111411
        Expr::FlatSumGeq(_, _, _) => Err(RuleNotApplicable),
1419492
        Expr::FlatWatchedLiteral(_, _, _) => Err(RuleNotApplicable),
14227
        Expr::FlatWeightedSumLeq(_, _, _, _) => Err(RuleNotApplicable),
13576
        Expr::FlatWeightedSumGeq(_, _, _, _) => Err(RuleNotApplicable),
133780
        Expr::MinionDivEqUndefZero(_, _, _, _) => Err(RuleNotApplicable),
136012
        Expr::MinionModuloEqUndefZero(_, _, _, _) => Err(RuleNotApplicable),
511
        Expr::MinionPow(_, _, _, _) => Err(RuleNotApplicable),
566322
        Expr::MinionReify(_, _, _) => Err(RuleNotApplicable),
208082
        Expr::MinionReifyImply(_, _, _) => Err(RuleNotApplicable),
651
        Expr::MinionWInIntervalSet(_, _, _) => Err(RuleNotApplicable),
279
        Expr::MinionWInSet(_, _, _) => Err(RuleNotApplicable),
26480
        Expr::MinionElementOne(_, _, _, _) => Err(RuleNotApplicable),
33998407
        Expr::SatObjective(..) | Expr::SATInt(_, _, _, _) => Err(RuleNotApplicable),
        Expr::PairwiseSum(_, _, _) => Err(RuleNotApplicable),
        Expr::PairwiseProduct(_, _, _) => Err(RuleNotApplicable),
        Expr::Active(m, variant, alternative) => {
71611
            let active_alternative = match variant.as_ref() {
1
                Expr::AbstractLiteral(_, AbstractLiteral::Variant(field)) => &field.name,
                Expr::Atomic(
                    _,
                    Atom::Literal(Lit::AbstractLiteral(AbstractLiteral::Variant(field))),
                ) => &field.name,
71610
                _ => return Err(RuleNotApplicable),
            };
1
            Ok(RuleEffect::pure(Expr::Atomic(
1
                m.clone(),
1
                Lit::Bool(active_alternative == alternative).into(),
1
            )))
        }
        // Semantic lowering for these lives in registered rules (function/set/mset/relation
        // horizontal rules), not here; the partial evaluator only offers extra constant-folding,
        // which `eval.rs`'s matching arms cover for the fully-constant case. Previously these
        // were `todo!()`, which panicked unconditionally on every rewrite of the operator (not
        // just constant ones), since `normalise_evaluator_local` calls this on every expression
        // node — the same landmine already found and fixed for Subsequence/Substring.
9579
        Expr::Defined(_, _) => Err(RuleNotApplicable),
22816
        Expr::Range(_, _) => Err(RuleNotApplicable),
489025
        Expr::Image(_, _, _) => Err(RuleNotApplicable),
        Expr::ImageSet(_, _, _) => Err(RuleNotApplicable),
        Expr::PreImage(_, _, _) => Err(RuleNotApplicable),
1550
        Expr::Inverse(_, _, _) => Err(RuleNotApplicable),
        Expr::PermInverse(_, _) => Err(RuleNotApplicable),
        Expr::Compose(_, _, _) => Err(RuleNotApplicable),
        Expr::Restrict(_, _, _) => Err(RuleNotApplicable),
        Expr::ToSet(_, _) => Err(RuleNotApplicable),
        Expr::ToMSet(_, _) => Err(RuleNotApplicable),
        Expr::ToRelation(_, _) => Err(RuleNotApplicable),
        Expr::RelationProj(_, _, _) => todo!(),
        Expr::Apart(_, _, _) => Err(RuleNotApplicable),
        Expr::Together(_, _, _) => Err(RuleNotApplicable),
        Expr::Participants(_, _) => Err(RuleNotApplicable),
        Expr::Party(_, _, _) => Err(RuleNotApplicable),
        Expr::Parts(_, _) => Err(RuleNotApplicable),
2697
        Expr::Subsequence(_, _, _) => Err(RuleNotApplicable),
5673
        Expr::Substring(_, _, _) => Err(RuleNotApplicable),
1846484
        Expr::LexLt(_, _, _) => Err(RuleNotApplicable),
479756
        Expr::LexLeq(_, _, _) => Err(RuleNotApplicable),
55986
        Expr::LexGt(_, _, _) => Err(RuleNotApplicable),
111755
        Expr::LexGeq(_, _, _) => Err(RuleNotApplicable),
9703
        Expr::FlatLexLt(_, _, _) => Err(RuleNotApplicable),
3286
        Expr::FlatLexLeq(_, _, _) => Err(RuleNotApplicable),
        Expr::AllDifferentExcept(_, _, _)
        | Expr::ElementId(_, _, _)
        | Expr::IndexOf(_, _, _)
        | Expr::SatElement(_, _, _, _)
5672411
        | Expr::SatAllDifferentComparisons(_, _) => Err(RuleNotApplicable),
    }
1981940084
}
/// Whether an `and`/`or` operand is a matrix literal holding no elements.
///
/// This deliberately ignores the index domain: `unwrap_list*` only recognise the normalised
/// `int(1..)`, and an empty `[]` parses to `[;int(1..0)]`. Matching the elements directly folds
/// `and([])` / `or([])` before `matrix_to_list` normalises the domain, and so before any
/// solver-family rule can fire on an expression that is already known to be constant.
301242195
fn is_empty_matrix_operand(operand: &Expr) -> bool {
301242195
    match operand {
        Expr::TypeAnnotation(_, inner, _) | Expr::DomainAnnotation(_, inner, _) => {
13640
            is_empty_matrix_operand(inner)
        }
293760587
        Expr::AbstractLiteral(_, AbstractLiteral::Matrix(elems, _)) => elems.is_empty(),
        Expr::Atomic(_, Atom::Literal(Lit::AbstractLiteral(AbstractLiteral::Matrix(elems, _)))) => {
19711
            elems.is_empty()
        }
7448257
        _ => false,
    }
301242195
}
/// Extracts `lhs â–· k` where `lhs` is atomic and `k` is an integer literal.
3956567
fn as_constant_bound_comparison(expr: &Expr) -> Option<(Atom, ConstantBoundOp, i32)> {
3956567
    as_constant_bound_comparison_ref(expr).map(|(lhs, op, rhs)| (lhs.clone(), op, rhs))
3956567
}
/// Borrowing variant of [`as_constant_bound_comparison`], for the inspection pass.
907243775
fn as_constant_bound_comparison_ref(expr: &Expr) -> Option<(&Atom, ConstantBoundOp, i32)> {
907243775
    let (lhs, rhs, op) = match expr {
208265
        Expr::Gt(_, lhs, rhs) => (lhs, rhs, ConstantBoundOp::Gt),
5553572
        Expr::Geq(_, lhs, rhs) => (lhs, rhs, ConstantBoundOp::Geq),
426064
        Expr::Lt(_, lhs, rhs) => (lhs, rhs, ConstantBoundOp::Lt),
12372988
        Expr::Leq(_, lhs, rhs) => (lhs, rhs, ConstantBoundOp::Leq),
888682886
        _ => return None,
    };
18560889
    let Expr::Atomic(_, Atom::Literal(Lit::Int(rhs_value))) = rhs.as_ref() else {
5752301
        return None;
    };
12808588
    let Expr::Atomic(_, lhs_atom) = lhs.as_ref() else {
12109815
        return None;
    };
698773
    Some((lhs_atom, op, *rhs_value))
907243775
}
/// Rebuilds a constant bound comparison from its dominated components.
10077
fn make_constant_bound_comparison(lhs: Atom, op: ConstantBoundOp, rhs: i32) -> Expr {
10077
    let lhs = Expr::Atomic(Metadata::new(), lhs);
10077
    let rhs = Expr::Atomic(Metadata::new(), Atom::Literal(Lit::Int(rhs)));
10077
    match op {
2264
        ConstantBoundOp::Gt => Expr::Gt(Metadata::new(), Moo::new(lhs), Moo::new(rhs)),
155
        ConstantBoundOp::Geq => Expr::Geq(Metadata::new(), Moo::new(lhs), Moo::new(rhs)),
3224
        ConstantBoundOp::Lt => Expr::Lt(Metadata::new(), Moo::new(lhs), Moo::new(rhs)),
4434
        ConstantBoundOp::Leq => Expr::Leq(Metadata::new(), Moo::new(lhs), Moo::new(rhs)),
    }
10077
}
/// Keeps the strongest RHS for `(lhs, op)` under conjunction, preserving first-seen order.
///
/// Bounds are keyed rather than searched, so merging `n` bounds over distinct atoms -- the shape
/// unrolling `forAll i : D. x[i] >= k` produces -- is linear in `n` rather than quadratic.
/// `IndexMap` gives the lookup while keeping first-seen order.
114178
fn merge_constant_bound(
114178
    bounds: &mut IndexMap<(Atom, ConstantBoundOp), i32>,
114178
    lhs: Atom,
114178
    op: ConstantBoundOp,
114178
    rhs: i32,
114178
) {
114178
    match bounds.entry((lhs, op)) {
        indexmap::map::Entry::Occupied(mut entry) => {
104101
            let existing = entry.get_mut();
104101
            if op.prefers_larger_rhs() {
99574
                if rhs > *existing {
18105
                    *existing = rhs;
81469
                }
4527
            } else if rhs < *existing {
1
                *existing = rhs;
4526
            }
        }
        indexmap::map::Entry::Vacant(entry) => {
10077
            entry.insert(rhs);
        }
    }
114178
}
/// Checks for tautologies involving pairs of terms inside an or, returning true if one is found.
///
/// This applies the following rules:
///
/// ```text
/// (p->q) \/ (q->p) ~> true    [totality of implication]
/// (p->q) \/ (p-> !q) ~> true  [conditional excluded middle]
/// ```
///
226850251
fn check_pairwise_or_tautologies(or_terms: &[Expr]) -> bool {
    // `identical_atom_to` can only succeed when both sides are atomic, so index the atomic pairs
    // and look each candidate up. This is expected O(n), not the O(n^2) of comparing every pair.
    #[allow(clippy::mutable_key_type)]
226850251
    let mut p_implies_q: HashSet<(&Atom, &Atom)> = HashSet::new();
    #[allow(clippy::mutable_key_type)]
226850251
    let mut p_implies_not_q: HashSet<(&Atom, &Atom)> = HashSet::new();
226850251
    for term in or_terms {
538150971
        if let Expr::Imply(_, p, q) = term {
1777757
            if let Expr::Not(_, q_1) = q.as_ref() {
332723
                if let (Expr::Atomic(_, p), Expr::Atomic(_, q)) = (p.as_ref(), q_1.as_ref()) {
2294
                    p_implies_not_q.insert((p, q));
330429
                }
1445034
            } else if let (Expr::Atomic(_, p), Expr::Atomic(_, q)) = (p.as_ref(), q.as_ref()) {
28644
                p_implies_q.insert((p, q));
1416390
            }
536373214
        }
    }
    // `(p->q) \/ (q->p) ~> true    [totality of implication]`
226850251
    for &(p, q) in &p_implies_q {
26350
        if p_implies_q.contains(&(q, p)) {
2294
            return true;
24056
        }
    }
    // `(p->q) \/ (p-> !q) ~> true`    [conditional excluded middle]
226847957
    p_implies_not_q
226847957
        .iter()
2294
        .any(|pair| p_implies_q.contains(pair))
226850251
}
#[cfg(test)]
mod tests {
    use super::*;
    use crate::ast::{DeclarationPtr, Domain, Name};
20
    fn int_lit(value: i32) -> Expr {
20
        Expr::Atomic(Metadata::new(), Atom::Literal(Lit::Int(value)))
20
    }
9
    fn bool_lit(value: bool) -> Expr {
9
        Expr::Atomic(Metadata::new(), Atom::Literal(Lit::Bool(value)))
9
    }
7
    fn atom_ref(name: &str) -> Expr {
7
        Expr::Atomic(
7
            Metadata::new(),
7
            Atom::Reference(crate::ast::Reference::new(DeclarationPtr::new_find(
7
                Name::user(name),
7
                Domain::int(vec![Range::Bounded(1, 20)]),
7
            ))),
7
        )
7
    }
1
    fn singleton_ref(name: &str, value: i32) -> Expr {
1
        Expr::Atomic(
1
            Metadata::new(),
1
            Atom::Reference(crate::ast::Reference::new(DeclarationPtr::new_find(
1
                Name::user(name),
1
                Domain::int(vec![Range::Bounded(value, value)]),
1
            ))),
1
        )
1
    }
5
    fn safe_pow(base: Expr, exponent: Expr) -> Expr {
5
        Expr::SafePow(Metadata::new(), Moo::new(base), Moo::new(exponent))
5
    }
    #[test]
1
    fn in_domain_simplification_does_not_expand_large_integer_domains() {
1
        let domain = Domain::int(vec![Range::Bounded(-1_000_000_000, 1_000_000_000)]);
        let variable: Expr =
1
            crate::ast::Reference::new(DeclarationPtr::new_find(Name::user("wide"), domain)).into();
1
        for evaluate in [run_partial_evaluator, run_partial_evaluator_local] {
2
            for (target, expected) in [
2
                (Domain::int(vec![Range::Bounded(i32::MIN, i32::MAX)]), true),
2
                (
2
                    Domain::int(vec![Range::Bounded(1_000_000_001, i32::MAX)]),
2
                    false,
2
                ),
2
            ] {
                let expression =
4
                    Expr::InDomain(Metadata::new(), Moo::new(variable.clone()), target);
4
                assert_eq!(
4
                    evaluate(&expression).unwrap().new_expression,
4
                    bool_lit(expected)
                );
            }
2
            let expression = Expr::InDomain(
2
                Metadata::new(),
2
                Moo::new(variable.clone()),
2
                Domain::int(vec![Range::Bounded(0, 1_000_000_000)]),
2
            );
2
            assert!(evaluate(&expression).is_err());
        }
1
    }
    /// A power folds when both operands are singletons, taking the base from a declaration domain.
    #[test]
1
    fn safe_pow_folds_singleton_operands() {
1
        let reduced = run_partial_evaluator_local(&safe_pow(singleton_ref("x", 2), int_lit(3)))
1
            .expect("evaluates")
1
            .new_expression;
1
        assert_eq!(reduced, int_lit(8));
1
    }
    /// A non-singleton operand leaves the power alone: its value is not yet known.
    #[test]
1
    fn safe_pow_keeps_non_singleton_operands() {
1
        assert!(run_partial_evaluator_local(&safe_pow(atom_ref("x"), int_lit(3))).is_err());
1
    }
    /// `0 ** 0` is undefined, and a negative exponent has no integer result.
    #[test]
1
    fn safe_pow_leaves_undefined_powers_alone() {
1
        assert!(run_partial_evaluator_local(&safe_pow(int_lit(0), int_lit(0))).is_err());
1
        assert!(run_partial_evaluator_local(&safe_pow(int_lit(2), int_lit(-1))).is_err());
1
    }
    /// Overflow is not folded: the model keeps the power rather than wrapping.
    #[test]
1
    fn safe_pow_leaves_overflowing_powers_alone() {
1
        assert!(run_partial_evaluator_local(&safe_pow(int_lit(i32::MAX), int_lit(2))).is_err());
1
    }
5
    fn and(exprs: Vec<Expr>) -> Expr {
5
        Expr::And(Metadata::new(), Moo::new(into_matrix_expr![exprs]))
5
    }
1
    fn or(exprs: Vec<Expr>) -> Expr {
1
        Expr::Or(Metadata::new(), Moo::new(into_matrix_expr![exprs]))
1
    }
    /// An empty conjunction is the identity of `and`.
    ///
    /// The partial evaluator is the only thing that implements this: its hook runs after every
    /// rewrite, so it reaches an empty `and`/`or` before any rule can.
    #[test]
1
    fn empty_and_is_true() {
1
        let reduced = run_partial_evaluator_local(&and(vec![]))
1
            .expect("evaluates")
1
            .new_expression;
1
        assert_eq!(reduced, bool_lit(true));
1
    }
    /// An empty disjunction is the identity of `or`. See [`empty_and_is_true`].
    #[test]
1
    fn empty_or_is_false() {
1
        let reduced = run_partial_evaluator_local(&or(vec![]))
1
            .expect("evaluates")
1
            .new_expression;
1
        assert_eq!(reduced, bool_lit(false));
1
    }
    /// An empty matrix written as `[]` parses with the *empty* index domain `int(1..0)`, not the
    /// normalised `int(1..)` that `unwrap_list` looks for. The evaluator must fold it regardless,
    /// so that no solver-family rule sees an expression that is already known to be constant.
2
    fn empty_matrix_with_empty_index_domain() -> Expr {
2
        Expr::AbstractLiteral(
2
            Metadata::new(),
2
            AbstractLiteral::Matrix(
2
                vec![],
2
                DomainPtr::from(Domain::int(vec![Range::Bounded(1, 0)])),
2
            ),
2
        )
2
    }
    #[test]
1
    fn empty_and_with_empty_index_domain_is_true() {
1
        let expr = Expr::And(
1
            Metadata::new(),
1
            Moo::new(empty_matrix_with_empty_index_domain()),
1
        );
1
        let reduced = run_partial_evaluator_local(&expr)
1
            .expect("evaluates")
1
            .new_expression;
1
        assert_eq!(reduced, bool_lit(true));
1
    }
    #[test]
1
    fn empty_or_with_empty_index_domain_is_false() {
1
        let expr = Expr::Or(
1
            Metadata::new(),
1
            Moo::new(empty_matrix_with_empty_index_domain()),
1
        );
1
        let reduced = run_partial_evaluator_local(&expr)
1
            .expect("evaluates")
1
            .new_expression;
1
        assert_eq!(reduced, bool_lit(false));
1
    }
    #[test]
1
    fn non_empty_and_is_not_collapsed_to_a_boolean() {
1
        let x = atom_ref("x");
1
        let expr = and(vec![Expr::Gt(
1
            Metadata::new(),
1
            Moo::new(x),
1
            Moo::new(int_lit(3)),
1
        )]);
        // Either it does not apply, or it rewrites to something that is not a bare boolean.
1
        if let Ok(reduced) = run_partial_evaluator_local(&expr) {
            assert_ne!(reduced.new_expression, bool_lit(true));
            assert_ne!(reduced.new_expression, bool_lit(false));
1
        }
1
    }
    #[test]
1
    fn and_dominates_constant_lower_bounds_on_same_atom() {
1
        let x = atom_ref("x");
1
        let expr = and(vec![
1
            Expr::Gt(Metadata::new(), Moo::new(x.clone()), Moo::new(int_lit(3))),
1
            bool_lit(true),
1
            Expr::Gt(Metadata::new(), Moo::new(x.clone()), Moo::new(int_lit(9))),
1
            Expr::Gt(Metadata::new(), Moo::new(x), Moo::new(int_lit(1))),
1
        ]);
1
        let reduced = run_partial_evaluator_local(&expr).unwrap().new_expression;
1
        let Expr::And(_, operands) = reduced else {
            panic!("expected And, got {reduced}");
        };
1
        let list = Moo::unwrap_or_clone(operands).unwrap_list().unwrap();
1
        assert_eq!(list.len(), 1);
1
        assert!(matches!(
1
            &list[0],
            Expr::Gt(_, lhs, rhs)
1
                if matches!(rhs.as_ref(), Expr::Atomic(_, Atom::Literal(Lit::Int(9))))
1
                    && matches!(lhs.as_ref(), Expr::Atomic(_, Atom::Reference(_)))
        ));
1
    }
    #[test]
1
    fn and_dominates_constant_upper_bounds_on_same_atom() {
1
        let x = atom_ref("x");
1
        let expr = and(vec![
1
            Expr::Leq(Metadata::new(), Moo::new(x.clone()), Moo::new(int_lit(8))),
1
            Expr::Leq(Metadata::new(), Moo::new(x), Moo::new(int_lit(4))),
1
        ]);
1
        let reduced = run_partial_evaluator_local(&expr).unwrap().new_expression;
1
        let Expr::And(_, operands) = reduced else {
            panic!("expected And, got {reduced}");
        };
1
        let list = Moo::unwrap_or_clone(operands).unwrap_list().unwrap();
1
        assert_eq!(list.len(), 1);
1
        assert!(matches!(
1
            &list[0],
            Expr::Leq(_, _, rhs)
1
                if matches!(rhs.as_ref(), Expr::Atomic(_, Atom::Literal(Lit::Int(4))))
        ));
1
    }
    #[test]
1
    fn and_does_not_merge_a_single_constant_bound() {
1
        let x = atom_ref("x");
1
        let expr = and(vec![Expr::Gt(
1
            Metadata::new(),
1
            Moo::new(x),
1
            Moo::new(int_lit(3)),
1
        )]);
1
        assert!(run_partial_evaluator_local(&expr).is_err());
1
    }
3
    fn product(factors: Vec<Expr>) -> Expr {
3
        Expr::Product(Metadata::new(), Moo::new(into_matrix_expr![factors]))
3
    }
    /// Local evaluation must not move a lone zero factor to the end of a product.
    ///
    /// That reshuffle undoes `reorder_product`'s constant-first form and causes an infinite
    /// rewrite loop on models such as `savilerow/diet` (`x[i] * 0`).
    #[test]
1
    fn local_product_does_not_reshuffle_zero_factor() {
1
        let x = atom_ref("x");
1
        let constant_first = product(vec![int_lit(0), x.clone()]);
1
        let variable_first = product(vec![x, int_lit(0)]);
1
        assert!(run_partial_evaluator_local(&constant_first).is_err());
1
        assert!(run_partial_evaluator_local(&variable_first).is_err());
1
    }
    /// Deep evaluation still collapses a safe `0 * x` product to the literal zero.
    #[test]
1
    fn deep_product_collapses_safe_zero_factor() {
1
        let expr = product(vec![int_lit(0), atom_ref("x")]);
1
        let reduced = run_partial_evaluator(&expr).unwrap().new_expression;
1
        assert_eq!(reduced, int_lit(0));
1
    }
    #[test]
1
    fn symbolic_cardinality_is_left_for_representation_rules() {
1
        let set = Expr::Atomic(
1
            Metadata::new(),
1
            Atom::Reference(crate::ast::Reference::new(DeclarationPtr::new_find(
1
                Name::user("s"),
1
                Domain::set(
1
                    crate::ast::SetAttr::new_max_size(2),
1
                    Domain::int(vec![Range::Bounded(1, 2)]),
1
                ),
1
            ))),
1
        );
1
        let cardinality = Expr::Card(Metadata::new(), Moo::new(set));
1
        assert!(run_partial_evaluator_local(&cardinality).is_err());
1
    }
}