1
mod lex;
2
mod normalise;
3
mod set;
4
mod short_table;
5

            
6
/************************************************************************/
7
/*        Rules for translating to Minion-supported constraints         */
8
/************************************************************************/
9

            
10
use std::{
11
    collections::{HashMap, HashSet},
12
    convert::TryInto,
13
};
14

            
15
use crate::types::matrix::MatrixComponents;
16
use conjure_cp::representation::ReprRule;
17

            
18
use crate::extra_check;
19
use crate::shared::utils::{
20
    defer_aux_var, flatten_children_to_aux_vars, is_flat, rewrite_children, to_aux_var_in,
21
};
22
use crate::types::matrix::try_index_matrix_components;
23
use conjure_cp::ast::categories::{Category, CategoryOf};
24
use conjure_cp::ast::{Domain, DomainPtr, GroundDomain, HasDomain, Moo, eval_constant};
25
use conjure_cp::{
26
    ast::Metadata,
27
    ast::{
28
        AbstractLiteral, Atom, Expression as Expr, Literal as Lit, Name, Range, Reference,
29
        ReturnType, SymbolTable, Typeable,
30
    },
31
    into_matrix_expr, matrix_expr,
32
    rule_engine::{
33
        ApplicationError, ApplicationResult, RuleEffect, register_rule, register_rule_set,
34
    },
35
    settings::SolverFamily,
36
};
37

            
38
use ApplicationError::RuleNotApplicable;
39
use itertools::Itertools;
40

            
41
register_rule_set!("Minion", ("Base"), |f: &SolverFamily| {
42
380303
    matches!(f, SolverFamily::Minion)
43
380303
});
44

            
45
/// Inlines constant matrix references just for Minion so Base matrix rules can lower them
46
/// without affecting other backends.
47
#[register_rule("Minion", 9000, [SafeIndex])]
48
676396
fn inline_constant_matrix_subject_for_minion(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
49
676396
    let Expr::SafeIndex(_, subject, indices) = expr else {
50
10928
        return Err(RuleNotApplicable);
51
    };
52

            
53
665468
    let Expr::Atomic(_, Atom::Reference(reference)) = subject.as_ref() else {
54
55991
        return Err(RuleNotApplicable);
55
    };
56

            
57
    // When all but the leading index are fixed, project those dimensions while the value letting
58
    // is still borrowed. The generic matrix rules would otherwise clone the complete matrix and
59
    // build one SafeIndex per outer element, only to evaluate every one of them independently.
60
609477
    if let Some(projected) = reference
61
27
        .with_resolved_expression(|resolved| {
62
27
            specialise_literal_matrix_index(resolved, indices.as_slice())
63
27
        })
64
        .flatten()
65
    {
66
        return Ok(RuleEffect::pure(projected));
67
609477
    }
68

            
69
609477
    let constant = reference.resolve_constant().ok_or(RuleNotApplicable)?;
70
27
    let Lit::AbstractLiteral(AbstractLiteral::Matrix(_, _)) = &constant else {
71
        return Err(RuleNotApplicable);
72
    };
73

            
74
27
    Ok(RuleEffect::pure(Expr::SafeIndex(
75
27
        Metadata::new(),
76
27
        Moo::new(Expr::Atomic(Metadata::new(), Atom::Literal(constant))),
77
27
        indices.clone(),
78
27
    )))
79
676396
}
80

            
81
18
fn literal_matrix_offset(domain: &GroundDomain, index: i32) -> Option<usize> {
82
18
    let GroundDomain::Int(ranges, _) = domain else {
83
        return None;
84
    };
85
18
    let [range] = ranges.as_slice() else {
86
18
        return None;
87
    };
88
    usize::try_from(index.checked_sub(*range.low()?)?).ok()
89
18
}
90

            
91
18
fn literal_at_matrix_indices<'a>(mut value: &'a Lit, indices: &[i32]) -> Option<&'a Lit> {
92
18
    for &index in indices {
93
18
        let Lit::AbstractLiteral(AbstractLiteral::Matrix(elems, domain)) = value else {
94
            return None;
95
        };
96
18
        value = elems.get(literal_matrix_offset(domain, index)?)?;
97
    }
98
    Some(value)
99
18
}
100

            
101
/// Projects fixed trailing dimensions from a directly stored literal matrix.
102
///
103
/// For example, `m[i, 2]` becomes `[m[1,2], ..., m[n,2]][i]` in one rewrite, without cloning `m`
104
/// or constructing `n` intermediate SafeIndex expressions.
105
27
fn specialise_literal_matrix_index(resolved: &Expr, indices: &[Expr]) -> Option<Expr> {
106
27
    if indices.len() < 2 {
107
        return None;
108
27
    }
109

            
110
    let Expr::Atomic(
111
        _,
112
        Atom::Literal(Lit::AbstractLiteral(AbstractLiteral::Matrix(outer_elems, outer_domain))),
113
27
    ) = resolved
114
    else {
115
        return None;
116
    };
117

            
118
27
    let trailing_indices = indices[1..]
119
27
        .iter()
120
27
        .map(|index| match eval_constant(index)? {
121
18
            Lit::Int(value) => Some(value),
122
            _ => None,
123
27
        })
124
9
        .collect::<Option<Vec<_>>>()?;
125

            
126
18
    let projected = outer_elems
127
18
        .iter()
128
18
        .map(|row| literal_at_matrix_indices(row, &trailing_indices).cloned())
129
18
        .collect::<Option<Vec<_>>>()?;
130

            
131
    Some(Expr::SafeIndex(
132
        Metadata::new(),
133
        Moo::new(Expr::Atomic(
134
            Metadata::new(),
135
            Atom::Literal(Lit::AbstractLiteral(AbstractLiteral::Matrix(
136
                projected,
137
                outer_domain.clone(),
138
            ))),
139
        )),
140
        vec![indices[0].clone()],
141
    ))
142
27
}
143

            
144
/// Lower modelling collections to Minion's scalar table relation.
145
#[register_rule("Minion", 4050, [Table, NegativeTable])]
146
2755
fn flatten_table(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
147
2755
    let (inputs, rows, negative) = match expr {
148
882
        Expr::Table(_, inputs, rows) => (inputs, rows, false),
149
54
        Expr::NegativeTable(_, inputs, rows) => (inputs, rows, true),
150
1819
        _ => return Err(RuleNotApplicable),
151
    };
152
936
    let inputs = crate::shared::utils::table_ordered_entries(inputs).ok_or(RuleNotApplicable)?;
153
936
    let rows = crate::shared::utils::table_rows(rows).ok_or(RuleNotApplicable)?;
154
936
    let rows = rows
155
936
        .iter()
156
5031
        .map(|row| {
157
5031
            let row = crate::shared::utils::table_ordered_entries(row)?;
158
5031
            if row.len() != inputs.len() {
159
                return None;
160
5031
            }
161
5031
            row.iter()
162
14688
                .map(|value| match eval_constant(value)? {
163
14688
                    Lit::Int(value) => Some(value),
164
                    Lit::Bool(value) => Some(i32::from(value)),
165
                    _ => None,
166
14688
                })
167
                .collect::<Option<Vec<_>>>()
168
5031
        })
169
        .collect::<Option<Vec<_>>>()
170
936
        .ok_or(RuleNotApplicable)?;
171
936
    let mut symbols = symbols.clone();
172
936
    let mut top = vec![];
173
936
    let inputs = inputs
174
936
        .into_iter()
175
2637
        .map(|input| flatten_expression_to_atom(input, &mut symbols, &mut top))
176
        .collect::<Result<Vec<_>, _>>()?;
177
936
    Ok(RuleEffect::new(
178
936
        Expr::FlatTable(Metadata::new(), inputs, rows, negative),
179
936
        top,
180
936
        symbols,
181
936
    ))
182
2755
}
183

            
184
#[register_rule("Minion", 4200, [Eq / Product, AuxDeclaration / Product])]
185
3874
fn introduce_producteq(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
186
    // product = val
187
    let val: Atom;
188
    let product: Moo<Expr>;
189

            
190
3874
    match expr.clone() {
191
        Expr::Eq(_m, a, b) => {
192
351
            let a_atom: Option<&Atom> = (&a).try_into().ok();
193
351
            let b_atom: Option<&Atom> = (&b).try_into().ok();
194

            
195
351
            if let Some(f) = a_atom {
196
                // val = product
197
123
                val = f.clone();
198
123
                product = b;
199
228
            } else if let Some(f) = b_atom {
200
                // product = val
201
108
                val = f.clone();
202
108
                product = a;
203
            } else {
204
120
                return Err(RuleNotApplicable);
205
            }
206
        }
207
        Expr::AuxDeclaration(_m, reference, e) => {
208
492
            val = Atom::Reference(reference);
209
492
            product = e;
210
        }
211
        _ => {
212
3031
            return Err(RuleNotApplicable);
213
        }
214
    }
215

            
216
723
    if !(matches!(&*product, Expr::Product(_, _,))) {
217
96
        return Err(RuleNotApplicable);
218
627
    }
219

            
220
627
    let Expr::Product(_, factors) = &*product else {
221
        return Err(RuleNotApplicable);
222
    };
223

            
224
627
    let mut factors_vec = (**factors).clone().into_list().ok_or(RuleNotApplicable)?;
225
627
    if factors_vec.len() < 2 {
226
        return Err(RuleNotApplicable);
227
627
    }
228

            
229
    // Product is a vecop, but FlatProductEq a binop.
230
    // Introduce auxvars until it is a binop
231

            
232
    // the expression returned will be x*y=val.
233
    // if factors is > 2 arguments, y will be an auxiliary variable
234

            
235
    #[allow(clippy::unwrap_used)] // should never panic - length is checked above
236
627
    let x: Atom = factors_vec
237
627
        .pop()
238
627
        .unwrap()
239
627
        .try_into()
240
627
        .or(Err(RuleNotApplicable))?;
241

            
242
    #[allow(clippy::unwrap_used)] // should never panic - length is checked above
243
561
    let mut y: Atom = factors_vec
244
561
        .pop()
245
561
        .unwrap()
246
561
        .try_into()
247
561
        .or(Err(RuleNotApplicable))?;
248

            
249
561
    let mut symbols = symbols.clone();
250
561
    let mut new_tops: Vec<Expr> = vec![];
251

            
252
    // FIXME: add a test for this
253
840
    while let Some(next_factor) = factors_vec.pop() {
254
        // Despite adding auxvars, I still require all atoms as factors, making this rule act
255
        // similar to other introduction rules.
256
279
        let next_factor_atom: Atom = next_factor.clone().try_into().or(Err(RuleNotApplicable))?;
257

            
258
        // TODO: find this domain without having to make unnecessary Expr and Metadata objects
259
        // Just using the domain of expr doesn't work
260
279
        let aux_domain = Expr::Product(
261
279
            Metadata::new(),
262
279
            Moo::new(matrix_expr![y.clone().into(), next_factor]),
263
279
        )
264
279
        .domain_of()
265
        // Essence domain_of rejects bool arithmetic; Minion treats BOOL as 0/1.
266
        .or_else(|| minion_product_aux_domain_from_atoms(&y, &next_factor_atom))
267
279
        .ok_or(ApplicationError::DomainError)?;
268

            
269
279
        let aux_decl = symbols.gen_find_auxiliary(&aux_domain);
270
279
        let aux_var = Atom::Reference(Reference::new(aux_decl));
271

            
272
279
        let new_top_expr = Expr::FlatProductEq(
273
279
            Metadata::new(),
274
279
            Moo::new(y),
275
279
            Moo::new(next_factor_atom),
276
279
            Moo::new(aux_var.clone()),
277
279
        );
278

            
279
279
        new_tops.push(new_top_expr);
280
279
        y = aux_var;
281
    }
282

            
283
561
    Ok(RuleEffect::new(
284
561
        Expr::FlatProductEq(Metadata::new(), Moo::new(x), Moo::new(y), Moo::new(val)),
285
561
        new_tops,
286
561
        symbols,
287
561
    ))
288
3874
}
289

            
290
/// Introduces `FlatWeightedSumLeq`, `FlatWeightedSumGeq`, `FlatSumLeq`, FlatSumGeq` constraints.
291
///
292
/// If the input is a weighted sum, the weighted sum constraints are used, otherwise the standard
293
/// sum constraints are used.
294
///
295
/// # Details
296
/// This rule is a bit unusual compared to other introduction rules in that
297
/// it does its own flattening.
298
///
299
/// Weighted sums are expressed as sums of products, which are not
300
/// flat. Flattening a weighted sum generically makes it indistinguishable
301
/// from a sum:
302
///
303
///```text
304
/// 1*a + 2*b + 3*c + d <= 10
305
///   ~~> flatten_vecop
306
/// __0 + __1 + __2 + d <= 10
307
///
308
///
309
/// __0 =aux 1*a
310
/// __1 =aux 2*b
311
/// __2 =aux 3*c
312
/// ```
313
///
314
/// Therefore, introduce_weightedsumleq_sumgeq does its own flattening.
315
///
316
/// Having custom flattening semantics means that we can make more things
317
/// weighted sums.
318
///
319
/// For example, consider `a + 2*b + 3*c*d + (e / f) + 5*(g/h) <= 18`. This
320
/// rule turns this into a single flat_weightedsumleq constraint:
321
///
322
///```text
323
/// a + 2*b + 3*c*d + (e/f) + 5*(g/h) <= 30
324
///
325
///   ~> introduce_weightedsumleq_sumgeq
326
///
327
/// flat_weightedsumleq([1,2,3,1,5],[a,b,__0,__1,__2],30)
328
///
329
/// with new top level constraints
330
///
331
/// __0 = c*d
332
/// __1 = e/f
333
/// __2 = g/h
334
/// ```
335
///
336
/// The rules to turn terms into coefficient variable pairs are the following:
337
///
338
/// 1. Non-weighted atom: `a ~> (1,a)`
339
/// 2. Other non-weighted term: `e ~> (1,__0)`, with new constraint `__0 =aux e`
340
/// 3. Weighted atom: `c*a ~> (c,a)`
341
/// 4. Weighted non-atom: `c*e ~> (c,__0)` with new constraint` __0 =aux e`
342
/// 5. Weighted product: `c*e*f ~> (c,__0)` with new constraint `__0 =aux (e*f)`
343
/// 6. Negated atom: `-x ~> (-1,x)`
344
/// 7. Negated expression: `-e ~> (-1,__0)` with new constraint `__0 = e`
345
///
346
/// Cases 6 and 7 could potentially be a normalising rule `-e ~> -1*e`. However, I think that we
347
/// should only turn negations into a product when they are inside a sum, not all the time.
348
#[register_rule("Minion", 4600, [Leq / Sum, Geq / Sum, Eq / Sum, AuxDeclaration / Sum])]
349
36787
fn introduce_weighted_sumleq_sumgeq(expr: &Expr, symtab: &SymbolTable) -> ApplicationResult {
350
    // Keep track of which type of (in)equality was in the input, and use this to decide what
351
    // constraints to make at the end
352

            
353
    // We handle Eq directly in this rule instead of letting it be decomposed to <= and >=
354
    // elsewhere, as this caused cyclic rule application:
355
    //
356
    // ```
357
    // 2*a + b = c
358
    //
359
    //   ~~> sumeq_to_inequalities
360
    //
361
    // 2*a + b <=c /\ 2*a + b >= c
362
    //
363
    // --
364
    //
365
    // 2*a + b <= c
366
    //
367
    //   ~~> flatten_generic
368
    // __1 <=c
369
    //
370
    // with new top level constraint
371
    //
372
    // 2*a + b =aux __1
373
    //
374
    // --
375
    //
376
    // 2*a + b =aux __1
377
    //
378
    //   ~~> sumeq_to_inequalities
379
    //
380
    // LOOP!
381
    // ```
382
    enum EqualityKind {
383
        Eq,
384
        Leq,
385
        Geq,
386
    }
387

            
388
    // Given the LHS, RHS, and the type of inequality, return the sum, total, and new inequality.
389
    //
390
    // The inequality returned is the one that puts the sum is on the left hand side and the total
391
    // on the right hand side.
392
    //
393
    // For example, `1 <= a + b` will result in ([a,b],1,Geq).
394
18898
    fn match_sum_total(
395
18898
        a: Moo<Expr>,
396
18898
        b: Moo<Expr>,
397
18898
        equality_kind: EqualityKind,
398
18898
    ) -> Result<(Vec<Expr>, Atom, EqualityKind), ApplicationError> {
399
18898
        match (
400
18898
            Moo::unwrap_or_clone(a),
401
18898
            Moo::unwrap_or_clone(b),
402
18898
            equality_kind,
403
18898
        ) {
404
            (Expr::Sum(_, sum_terms), Expr::Atomic(_, total), EqualityKind::Leq) => {
405
2289
                let sum_terms = Moo::unwrap_or_clone(sum_terms)
406
2289
                    .into_list()
407
2289
                    .ok_or(RuleNotApplicable)?;
408
1839
                Ok((sum_terms, total, EqualityKind::Leq))
409
            }
410
            (Expr::Atomic(_, total), Expr::Sum(_, sum_terms), EqualityKind::Leq) => {
411
4301
                let sum_terms = Moo::unwrap_or_clone(sum_terms)
412
4301
                    .into_list()
413
4301
                    .ok_or(RuleNotApplicable)?;
414
4293
                Ok((sum_terms, total, EqualityKind::Geq))
415
            }
416
            (Expr::Sum(_, sum_terms), Expr::Atomic(_, total), EqualityKind::Geq) => {
417
1693
                let sum_terms = Moo::unwrap_or_clone(sum_terms)
418
1693
                    .into_list()
419
1693
                    .ok_or(RuleNotApplicable)?;
420
1504
                Ok((sum_terms, total, EqualityKind::Geq))
421
            }
422
            (Expr::Atomic(_, total), Expr::Sum(_, sum_terms), EqualityKind::Geq) => {
423
972
                let sum_terms = Moo::unwrap_or_clone(sum_terms)
424
972
                    .into_list()
425
972
                    .ok_or(RuleNotApplicable)?;
426
936
                Ok((sum_terms, total, EqualityKind::Leq))
427
            }
428
            (Expr::Sum(_, sum_terms), Expr::Atomic(_, total), EqualityKind::Eq) => {
429
6909
                let sum_terms = Moo::unwrap_or_clone(sum_terms)
430
6909
                    .into_list()
431
6909
                    .ok_or(RuleNotApplicable)?;
432
6287
                Ok((sum_terms, total, EqualityKind::Eq))
433
            }
434
            (Expr::Atomic(_, total), Expr::Sum(_, sum_terms), EqualityKind::Eq) => {
435
1882
                let sum_terms = Moo::unwrap_or_clone(sum_terms)
436
1882
                    .into_list()
437
1882
                    .ok_or(RuleNotApplicable)?;
438
1648
                Ok((sum_terms, total, EqualityKind::Eq))
439
            }
440
852
            _ => Err(RuleNotApplicable),
441
        }
442
18898
    }
443

            
444
36787
    let (sum_exprs, total, equality_kind) = match expr.clone() {
445
6875
        Expr::Leq(_, a, b) => Ok(match_sum_total(a, b, EqualityKind::Leq)?),
446
2665
        Expr::Geq(_, a, b) => Ok(match_sum_total(a, b, EqualityKind::Geq)?),
447
9358
        Expr::Eq(_, a, b) => Ok(match_sum_total(a, b, EqualityKind::Eq)?),
448
        Expr::AuxDeclaration(_, reference, a) => {
449
12122
            let total: Atom = Atom::Reference(reference);
450
12122
            if let Expr::Sum(_, sum_terms) = Moo::unwrap_or_clone(a) {
451
11942
                let sum_terms = Moo::unwrap_or_clone(sum_terms)
452
11942
                    .into_list()
453
11942
                    .ok_or(RuleNotApplicable)?;
454
11403
                Ok((sum_terms, total, EqualityKind::Eq))
455
            } else {
456
180
                Err(RuleNotApplicable)
457
            }
458
        }
459
5767
        _ => Err(RuleNotApplicable),
460
5947
    }?;
461

            
462
27910
    let mut new_top_exprs: Vec<Expr> = vec![];
463
27910
    let mut symtab = symtab.clone();
464

            
465
    #[allow(clippy::mutable_key_type)]
466
27910
    let mut coefficients_and_vars: HashMap<Atom, i32> = HashMap::new();
467

            
468
    // Every summand must stand for a single term. An unexpanded comprehension stands for many, and
469
    // flattening it here mints an auxiliary holding the whole matrix, which no solver can take.
470
    // Leave it for comprehension expansion. (A comprehension's return type is its element type, so
471
    // this has to match the variant rather than ask for the type.)
472
27910
    if sum_exprs
473
27910
        .iter()
474
83814
        .any(|term| matches!(term, Expr::Comprehension(_, _)))
475
    {
476
        return Err(RuleNotApplicable);
477
27910
    }
478

            
479
    // for each sub-term, get the coefficient and the variable, flattening if necessary.
480
    //
481
27910
    for expr in sum_exprs {
482
83238
        let (coeff, var) = flatten_weighted_sum_term(expr, &mut symtab, &mut new_top_exprs)?;
483

            
484
82662
        if coeff == 0 {
485
            continue;
486
82662
        }
487

            
488
        // collect coefficients for like terms, so 2*x + -1*x ~~> 1*x
489
82662
        coefficients_and_vars
490
82662
            .entry(var)
491
126
            .and_modify(|x| *x += coeff)
492
82662
            .or_insert(coeff);
493
    }
494

            
495
    // the expr should use a regular sum instead if the coefficients are all 1.
496
77780
    let use_weighted_sum = !coefficients_and_vars.values().all(|x| *x == 1 || *x == 0);
497

            
498
    // This needs a consistent iteration order so that the output is deterministic. However,
499
    // HashMap doesn't provide this. Can't use BTreeMap or Ord to achieve this, as not everything
500
    // in the AST implements Ord. Instead, order things by their pretty printed value.
501
27334
    let (vars, coefficients): (Vec<Atom>, Vec<Lit>) = coefficients_and_vars
502
27334
        .into_iter()
503
82536
        .filter(|(_, c)| *c != 0)
504
132947
        .sorted_by(|a, b| {
505
132947
            let a_atom_str = format!("{}", a.0);
506
132947
            let b_atom_str = format!("{}", b.0);
507
132947
            a_atom_str.cmp(&b_atom_str)
508
132947
        })
509
82527
        .map(|(v, c)| (v, Lit::Int(c)))
510
        .unzip();
511

            
512
27334
    let new_expr: Expr = match (equality_kind, use_weighted_sum) {
513
3892
        (EqualityKind::Eq, true) => Expr::And(
514
3892
            Metadata::new(),
515
3892
            Moo::new(matrix_expr![
516
3892
                Expr::FlatWeightedSumLeq(
517
3892
                    Metadata::new(),
518
3892
                    coefficients.clone(),
519
3892
                    vars.clone(),
520
3892
                    Moo::new(total.clone()),
521
3892
                ),
522
3892
                Expr::FlatWeightedSumGeq(Metadata::new(), coefficients, vars, Moo::new(total)),
523
3892
            ]),
524
3892
        ),
525
14870
        (EqualityKind::Eq, false) => Expr::And(
526
14870
            Metadata::new(),
527
14870
            Moo::new(matrix_expr![
528
14870
                Expr::FlatSumLeq(Metadata::new(), vars.clone(), total.clone()),
529
14870
                Expr::FlatSumGeq(Metadata::new(), vars, total),
530
14870
            ]),
531
14870
        ),
532
        (EqualityKind::Leq, true) => {
533
207
            Expr::FlatWeightedSumLeq(Metadata::new(), coefficients, vars, Moo::new(total))
534
        }
535
2568
        (EqualityKind::Leq, false) => Expr::FlatSumLeq(Metadata::new(), vars, total),
536
        (EqualityKind::Geq, true) => {
537
36
            Expr::FlatWeightedSumGeq(Metadata::new(), coefficients, vars, Moo::new(total))
538
        }
539
5761
        (EqualityKind::Geq, false) => Expr::FlatSumGeq(Metadata::new(), vars, total),
540
    };
541

            
542
27334
    Ok(RuleEffect::new(new_expr, new_top_exprs, symtab))
543
36787
}
544

            
545
/// For a term inside a weighted sum, return coefficient*variable.
546
///
547
///
548
/// If the term is in the form <coefficient> * <non flat expression>, the expression is flattened
549
/// to a new auxvar, which is returned as the variable for this term.
550
///
551
/// New auxvars are added to `symtab`, and their top level constraints to `top_level_exprs`.
552
///
553
/// # Errors
554
///
555
/// + Returns [`ApplicationError::RuleNotApplicable`] if a non-flat expression cannot be turned
556
///   into an atom. See [`flatten_expression_to_atom`].
557
///
558
/// + Returns [`ApplicationError::RuleNotApplicable`] if the term is a product containing a matrix
559
///   literal, and that matrix literal is not a list.
560
///
561
///
562
3226
fn try_eval_i32_coeff(expr: &Expr) -> Option<i32> {
563
3226
    if let Expr::Atomic(_, Atom::Literal(Lit::Int(coeff))) = expr {
564
        return Some(*coeff);
565
3226
    }
566
3226
    eval_constant(expr).and_then(|lit| match lit {
567
        Lit::Int(coeff) => Some(coeff),
568
        _ => None,
569
    })
570
3226
}
571

            
572
3226
fn flatten_weighted_sum_product_factor(
573
3226
    expr: Expr,
574
3226
    symtab: &mut SymbolTable,
575
3226
    top_level_exprs: &mut Vec<Expr>,
576
3226
) -> Result<Atom, ApplicationError> {
577
3226
    if let Expr::Atomic(_, atom) = &expr {
578
216
        return Ok(atom.clone());
579
3010
    }
580

            
581
    // Parameter or constant matrix lookups can appear as coefficients inside sums.
582
3010
    if let Expr::SafeIndex(_, subject, indices) = &expr {
583
45
        let indices_are_atomic = indices
584
45
            .iter()
585
45
            .all(|index| matches!(index, Expr::Atomic(_, _)));
586
45
        if indices_are_atomic
587
45
            && let Expr::Atomic(_, Atom::Reference(reference)) = subject.as_ref()
588
            && matches!(
589
                reference.category_of(),
590
                Category::Parameter | Category::Constant
591
            )
592
        {
593
            let domain = expr.domain_of().ok_or(RuleNotApplicable)?;
594
            let decl = symtab.gen_find_auxiliary(&domain);
595
            top_level_exprs.push(Expr::AuxDeclaration(
596
                Metadata::new(),
597
                Reference::new(decl.clone()),
598
                Moo::new(expr),
599
            ));
600
            return Ok(Atom::Reference(Reference::new(decl)));
601
45
        }
602
2965
    }
603

            
604
3010
    flatten_expression_to_atom(expr, symtab, top_level_exprs)
605
3226
}
606

            
607
1613
fn flatten_weighted_sum_binary_product(
608
1613
    a: Expr,
609
1613
    b: Expr,
610
1613
    symtab: &mut SymbolTable,
611
1613
    top_level_exprs: &mut Vec<Expr>,
612
1613
) -> Result<Atom, ApplicationError> {
613
1613
    let a_atom = flatten_weighted_sum_product_factor(a, symtab, top_level_exprs)?;
614
1613
    let b_atom = flatten_weighted_sum_product_factor(b, symtab, top_level_exprs)?;
615

            
616
1613
    let product = Expr::Product(
617
1613
        Metadata::new(),
618
1613
        Moo::new(matrix_expr![
619
1613
            Expr::Atomic(Metadata::new(), a_atom.clone()),
620
1613
            Expr::Atomic(Metadata::new(), b_atom.clone()),
621
1613
        ]),
622
1613
    );
623
    // Essence domain_of rejects bool arithmetic; after stripping toInt(bool) for
624
    // Minion we still need an int aux domain (BOOL is 0/1 in the solver).
625
1613
    let domain = product
626
1613
        .domain_of()
627
1417
        .or_else(|| minion_product_aux_domain_from_atoms(&a_atom, &b_atom))
628
1613
        .ok_or(RuleNotApplicable)?;
629
1613
    let decl = symtab.gen_find_auxiliary(&domain);
630
1613
    let aux = Atom::Reference(Reference::new(decl));
631

            
632
1613
    top_level_exprs.push(Expr::FlatProductEq(
633
1613
        Metadata::new(),
634
1613
        Moo::new(a_atom),
635
1613
        Moo::new(b_atom),
636
1613
        Moo::new(aux.clone()),
637
1613
    ));
638

            
639
1613
    Ok(aux)
640
1613
}
641

            
642
/// Minion treats BOOL as 0/1. Use that only when emitting solver constraints —
643
/// not for Essence typechecking / `domain_of`.
644
2951
fn minion_atom_as_i32_bounds(atom: &Atom) -> Option<(i32, i32)> {
645
2951
    let resolved = atom.domain_of().resolve().ok()?;
646
2951
    match resolved.as_ref() {
647
2795
        GroundDomain::Bool => Some((0, 1)),
648
        GroundDomain::Int(ranges, _) => {
649
156
            let mut lo = i32::MAX;
650
156
            let mut hi = i32::MIN;
651
156
            for range in ranges {
652
156
                match range {
653
                    Range::Single(x) => {
654
63
                        lo = lo.min(*x);
655
63
                        hi = hi.max(*x);
656
                    }
657
                    Range::Bounded(a, b) => {
658
93
                        lo = lo.min(*a);
659
93
                        hi = hi.max(*b);
660
                    }
661
                    _ => return None,
662
                }
663
            }
664
156
            (lo <= hi).then_some((lo, hi))
665
        }
666
        _ => None,
667
    }
668
2951
}
669

            
670
1417
fn minion_product_aux_domain_from_atoms(a: &Atom, b: &Atom) -> Option<DomainPtr> {
671
1417
    let (a_lo, a_hi) = minion_atom_as_i32_bounds(a)?;
672
1417
    let (b_lo, b_hi) = minion_atom_as_i32_bounds(b)?;
673
    let corners = [
674
1417
        a_lo.checked_mul(b_lo)?,
675
1417
        a_lo.checked_mul(b_hi)?,
676
1417
        a_hi.checked_mul(b_lo)?,
677
1417
        a_hi.checked_mul(b_hi)?,
678
    ];
679
1417
    let lo = *corners.iter().min()?;
680
1417
    let hi = *corners.iter().max()?;
681
1417
    if lo == hi {
682
        Some(Domain::int(vec![Range::Single(lo)]))
683
    } else {
684
1417
        Some(Domain::int(vec![Range::Bounded(lo, hi)]))
685
    }
686
1417
}
687

            
688
83238
fn flatten_weighted_sum_term(
689
83238
    term: Expr,
690
83238
    symtab: &mut SymbolTable,
691
83238
    top_level_exprs: &mut Vec<Expr>,
692
83238
) -> Result<(i32, Atom), ApplicationError> {
693
83238
    match term {
694
        // we can only see check the product for coefficients it contains a matrix literal.
695
        //
696
        // e.g. the input expression `product([2,x])` returns (2,x), but `product(my_matrix)`
697
        // returns (1,product(my_matrix)).
698
        //
699
        // if the product contains a matrix literal but it is not a list, throw `RuleNotApplicable`
700
        // to allow it to be changed into a list by another rule.
701
6132
        Expr::Product(_, factors) if factors.is_matrix_literal() => {
702
            // this fails if factors is not a matrix literal or that matrix literal is not a list.
703
            //
704
            // we already check for the first case above, so this should only error when we have a
705
            // non-list matrix literal.
706
6132
            let factors = Moo::unwrap_or_clone(factors)
707
6132
                .into_list()
708
6132
                .ok_or(RuleNotApplicable)?;
709

            
710
6132
            match factors.as_slice() {
711
                // product([]) ~~> (0,0)
712
                // coefficients of 0 should be ignored by the caller.
713
                [] => Ok((0, Atom::Literal(Lit::Int(0)))),
714

            
715
                // assume the coefficients have been placed at the front by normalisation rules
716

            
717
                // product[1,x,y,...] ~> return (coeff,product([x,y,...]))
718
                [
719
                    Expr::Atomic(_, Atom::Literal(Lit::Int(coeff))),
720
                    e,
721
                    rest @ ..,
722
                ] => {
723
                    // A lone remaining factor is the term itself. Wrapping it back up as
724
                    // `product([x])` would ask for an auxiliary holding a one-element product,
725
                    // which has no integer domain when `x` is a bool -- and a bool is exactly what
726
                    // `flatten_product` leaves behind, since Minion reads it as 0/1.
727
4465
                    if rest.is_empty() {
728
                        return Ok((
729
4354
                            *coeff,
730
4354
                            flatten_expression_to_atom(e.clone(), symtab, top_level_exprs)?,
731
                        ));
732
111
                    }
733

            
734
111
                    let mut product_terms = Vec::from(rest);
735
111
                    product_terms.push(e.clone());
736
                    let product =
737
111
                        Expr::Product(Metadata::new(), Moo::new(into_matrix_expr!(product_terms)));
738
                    Ok((
739
111
                        *coeff,
740
111
                        flatten_expression_to_atom(product, symtab, top_level_exprs)?,
741
                    ))
742
                }
743

            
744
                // product([c,y]) or product([y,c]) when one factor is a constant coefficient
745
                [a, b] => {
746
1613
                    if let Some(coeff) = try_eval_i32_coeff(a) {
747
                        Ok((
748
                            coeff,
749
                            flatten_expression_to_atom(b.clone(), symtab, top_level_exprs)?,
750
                        ))
751
1613
                    } else if let Some(coeff) = try_eval_i32_coeff(b) {
752
                        Ok((
753
                            coeff,
754
                            flatten_expression_to_atom(a.clone(), symtab, top_level_exprs)?,
755
                        ))
756
                    } else {
757
                        Ok((
758
1613
                            1,
759
1613
                            flatten_weighted_sum_binary_product(
760
1613
                                a.clone(),
761
1613
                                b.clone(),
762
1613
                                symtab,
763
1613
                                top_level_exprs,
764
1613
                            )?,
765
                        ))
766
                    }
767
                }
768

            
769
                // product([x,y,z,...]) ~~> (1,product([x,y,z,...]))
770
                _ => {
771
                    let product =
772
54
                        Expr::Product(Metadata::new(), Moo::new(into_matrix_expr!(factors)));
773
                    Ok((
774
54
                        1,
775
54
                        flatten_expression_to_atom(product, symtab, top_level_exprs)?,
776
                    ))
777
                }
778
            }
779
        }
780
        Expr::Neg(_, inner_term) => Ok((
781
1071
            -1,
782
1071
            flatten_expression_to_atom(Moo::unwrap_or_clone(inner_term), symtab, top_level_exprs)?,
783
        )),
784
        term => Ok((
785
76035
            1,
786
76035
            flatten_expression_to_atom(term, symtab, top_level_exprs)?,
787
        )),
788
    }
789
83238
}
790

            
791
/// Converts the input expression to an atom, placing it into a new auxiliary variable if
792
/// necessary.
793
///
794
/// The auxiliary variable will be added to the symbol table and its top-level-constraint to
795
/// `top_level_exprs`.
796
///
797
/// If the expression is already atomic, no auxiliary variables are created, and the atom is
798
/// returned as-is.
799
///
800
/// # Errors
801
///
802
///  + Returns [`ApplicationError::RuleNotApplicable`] if the expression cannot be placed into an
803
///    auxiliary variable. For example, expressions that do not have domains.
804
///
805
///    This function supports the same expressions as [`to_aux_var_in`], except that this function
806
///    succeeds when the expression given is atomic.
807
///
808
///    See [`to_aux_var_in`] for more information.
809
///
810
88236
fn flatten_expression_to_atom(
811
88236
    expr: Expr,
812
88236
    symtab: &mut SymbolTable,
813
88236
    top_level_exprs: &mut Vec<Expr>,
814
88236
) -> Result<Atom, ApplicationError> {
815
88236
    if let Expr::Atomic(_, atom) = expr {
816
41720
        return Ok(atom);
817
46516
    }
818

            
819
    // Minion treats BOOL as 0/1, so `toInt(atom)` needs no aux variable.
820
    // SavileRow posts bools directly into sumleq/sumgeq; without this, every
821
    // `toInt(b)` becomes `__ =aux toInt(b)` and roughly doubles the variable count
822
    // on models like solitaire_battleship.
823
46516
    if let Expr::ToInt(_, inner) = &expr
824
28976
        && let Expr::Atomic(_, atom) = inner.as_ref()
825
    {
826
22724
        return Ok(atom.clone());
827
23792
    }
828

            
829
23792
    let (reference, top) = to_aux_var_in(&expr, symtab).ok_or(RuleNotApplicable)?;
830
23216
    top_level_exprs.push(top);
831

            
832
23216
    Ok(Atom::Reference(reference))
833
88236
}
834

            
835
#[register_rule("Minion", 4200, [Eq / SafeDiv, AuxDeclaration / SafeDiv])]
836
42073
fn introduce_diveq(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
837
    // div = val
838
    let val: Atom;
839
    let div: Moo<Expr>;
840
    let meta: Metadata;
841

            
842
42073
    match expr.clone() {
843
        Expr::Eq(m, a, b) => {
844
369
            meta = m;
845

            
846
369
            let a_atom: Option<&Atom> = (&a).try_into().ok();
847
369
            let b_atom: Option<&Atom> = (&b).try_into().ok();
848

            
849
369
            if let Some(f) = a_atom {
850
                // val = div
851
186
                val = f.clone();
852
186
                div = b;
853
183
            } else if let Some(f) = b_atom {
854
                // div = val
855
171
                val = f.clone();
856
171
                div = a;
857
            } else {
858
12
                return Err(RuleNotApplicable);
859
            }
860
        }
861
        Expr::AuxDeclaration(m, reference, e) => {
862
38673
            meta = m;
863
38673
            val = Atom::Reference(reference);
864
38673
            div = e;
865
        }
866
        _ => {
867
3031
            return Err(RuleNotApplicable);
868
        }
869
    }
870

            
871
39030
    if !(matches!(&*div, Expr::SafeDiv(_, _, _))) {
872
96
        return Err(RuleNotApplicable);
873
38934
    }
874

            
875
38934
    let Expr::SafeDiv(_, a, b) = div.as_ref() else {
876
        return Err(RuleNotApplicable);
877
    };
878
38934
    let a: &Atom = a.as_ref().try_into().or(Err(RuleNotApplicable))?;
879
38898
    let b: &Atom = b.as_ref().try_into().or(Err(RuleNotApplicable))?;
880

            
881
38880
    Ok(RuleEffect::pure(Expr::MinionDivEqUndefZero(
882
38880
        meta,
883
38880
        Moo::new(a.clone()),
884
38880
        Moo::new(b.clone()),
885
38880
        Moo::new(val),
886
38880
    )))
887
42073
}
888

            
889
#[register_rule("Minion", 4200, [Eq / SafeMod, AuxDeclaration / SafeMod])]
890
79180
fn introduce_modeq(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
891
    // div = val
892
    let val: Atom;
893
    let div: Moo<Expr>;
894
    let meta: Metadata;
895

            
896
79180
    match expr.clone() {
897
        Expr::Eq(m, a, b) => {
898
33901
            meta = m;
899
33901
            let a_atom: Option<&Atom> = (&a).try_into().ok();
900
33901
            let b_atom: Option<&Atom> = (&b).try_into().ok();
901

            
902
33901
            if let Some(f) = a_atom {
903
                // val = div
904
222
                val = f.clone();
905
222
                div = b;
906
33679
            } else if let Some(f) = b_atom {
907
                // div = val
908
33487
                val = f.clone();
909
33487
                div = a;
910
            } else {
911
192
                return Err(RuleNotApplicable);
912
            }
913
        }
914
        Expr::AuxDeclaration(m, reference, e) => {
915
42248
            meta = m;
916
42248
            val = Atom::Reference(reference);
917
42248
            div = e;
918
        }
919
        _ => {
920
3031
            return Err(RuleNotApplicable);
921
        }
922
    }
923

            
924
75957
    if !(matches!(&*div, Expr::SafeMod(_, _, _))) {
925
96
        return Err(RuleNotApplicable);
926
75861
    }
927

            
928
75861
    let Expr::SafeMod(_, a, b) = div.as_ref() else {
929
        return Err(RuleNotApplicable);
930
    };
931
75861
    let a: &Atom = a.as_ref().try_into().or(Err(RuleNotApplicable))?;
932
39528
    let b: &Atom = b.as_ref().try_into().or(Err(RuleNotApplicable))?;
933

            
934
39528
    Ok(RuleEffect::pure(Expr::MinionModuloEqUndefZero(
935
39528
        meta,
936
39528
        Moo::new(a.clone()),
937
39528
        Moo::new(b.clone()),
938
39528
        Moo::new(val),
939
39528
    )))
940
79180
}
941

            
942
/// Lowers a Lee-metric atom `min([|e|, K - |e|])` to flat Minion constraints in one step.
943
///
944
/// The alphabet-size form `min([|x - y|, K - |x - y|])` otherwise pays a long micro-pipeline
945
/// (`minus_to_sum`, flatten, `introduce_abseq`, `introduce_mineq`, `matrix_to_list`) and, worse,
946
/// duplicates work on the two copies of `|e|`. This rule runs above `minus_to_sum` (8400) so the
947
/// shared absolute value is preserved, and emits:
948
///
949
/// - `diff` channelled from `e` (weighted sum when `e` is an atomic minus),
950
/// - `AbsEq(abs, diff)`,
951
/// - `abs + complement = K`,
952
/// - `FlatMinEq([abs, complement], result)`.
953
///
954
/// Also accepts the post-`minus_to_sum` complement shape `sum([K, -(|e|)])`.
955
#[register_rule("Minion", 8600, [Min])]
956
8182
fn introduce_lee_distance_atom(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
957
8182
    let Some((inner, alphabet_size)) = match_lee_distance_min(expr) else {
958
8180
        return Err(RuleNotApplicable);
959
    };
960

            
961
2
    let result_domain = expr.domain_of().ok_or(ApplicationError::DomainError)?;
962
2
    let abs_domain = Expr::Abs(Metadata::new(), Moo::new(inner.clone()))
963
2
        .domain_of()
964
2
        .ok_or(ApplicationError::DomainError)?;
965

            
966
2
    let mut symbols = symbols.clone();
967
2
    let mut new_tops: Vec<Expr> = Vec::new();
968

            
969
2
    let diff_atom = flatten_lee_diff_to_atom(inner, &mut symbols, &mut new_tops)?;
970

            
971
2
    let abs_atom = Atom::new_ref(symbols.gen_find_auxiliary(&abs_domain));
972
2
    new_tops.push(Expr::FlatAbsEq(
973
2
        Metadata::new(),
974
2
        Moo::new(abs_atom.clone()),
975
2
        Moo::new(diff_atom),
976
2
    ));
977

            
978
2
    let complement_domain = Domain::int(vec![Range::Bounded(0, alphabet_size)]);
979
2
    let complement_atom = Atom::new_ref(symbols.gen_find_auxiliary(&complement_domain));
980
2
    let alphabet_atom = Atom::Literal(Lit::Int(alphabet_size));
981
2
    new_tops.push(Expr::FlatSumLeq(
982
2
        Metadata::new(),
983
2
        vec![abs_atom.clone(), complement_atom.clone()],
984
2
        alphabet_atom.clone(),
985
2
    ));
986
2
    new_tops.push(Expr::FlatSumGeq(
987
2
        Metadata::new(),
988
2
        vec![abs_atom.clone(), complement_atom.clone()],
989
2
        alphabet_atom,
990
2
    ));
991

            
992
2
    let result_atom = Atom::new_ref(symbols.gen_find_auxiliary(&result_domain));
993
2
    new_tops.push(Expr::FlatMinEq(
994
2
        Metadata::new(),
995
2
        vec![abs_atom, complement_atom],
996
2
        result_atom.clone(),
997
2
    ));
998

            
999
2
    Ok(RuleEffect::new(
2
        Expr::Atomic(Metadata::new(), result_atom),
2
        new_tops,
2
        symbols,
2
    ))
8182
}
/// Match `min([|e|, K - |e|])` / `min([|e|, sum([K, -(|e|)])])`, returning `(e, K)`.
8182
fn match_lee_distance_min(expr: &Expr) -> Option<(Expr, i32)> {
8182
    let Expr::Min(_, inside) = expr else {
7891
        return None;
    };
291
    let (elems, _) = inside.as_ref().clone().unwrap_matrix_unchecked()?;
291
    if elems.len() != 2 {
18
        return None;
273
    }
273
    match_lee_distance_arms(&elems[0], &elems[1])
271
        .or_else(|| match_lee_distance_arms(&elems[1], &elems[0]))
8182
}
544
fn match_lee_distance_arms(abs_arm: &Expr, complement_arm: &Expr) -> Option<(Expr, i32)> {
544
    let Expr::Abs(_, inner) = abs_arm else {
542
        return None;
    };
2
    let alphabet_size = match_lee_complement(complement_arm, inner.as_ref())?;
2
    if alphabet_size <= 0 {
        return None;
2
    }
2
    Some((Moo::unwrap_or_clone(inner.clone()), alphabet_size))
544
}
2
fn match_lee_complement(complement: &Expr, expected_inner: &Expr) -> Option<i32> {
2
    match complement {
        Expr::Minus(_, lhs, rhs) => {
1
            let alphabet_size = as_int_literal(lhs.as_ref())?;
1
            let Expr::Abs(_, inner) = rhs.as_ref() else {
                return None;
            };
1
            (inner.as_ref() == expected_inner).then_some(alphabet_size)
        }
        Expr::Sum(_, matrix) => {
1
            let matrix = matrix.as_ref().clone();
1
            let terms = if matrix.is_list() {
1
                matrix.into_list()
            } else {
                matrix
                    .unwrap_matrix_unchecked()
                    .map(|(elements, _)| elements)
            }?;
1
            if terms.len() != 2 {
                return None;
1
            }
1
            match_lee_sum_complement(&terms[0], &terms[1], expected_inner)
                .or_else(|| match_lee_sum_complement(&terms[1], &terms[0], expected_inner))
        }
        _ => None,
    }
2
}
1
fn match_lee_sum_complement(a: &Expr, b: &Expr, expected_inner: &Expr) -> Option<i32> {
1
    let alphabet_size = as_int_literal(a)?;
1
    let Expr::Neg(_, negand) = b else {
        return None;
    };
1
    let Expr::Abs(_, inner) = negand.as_ref() else {
        return None;
    };
1
    (inner.as_ref() == expected_inner).then_some(alphabet_size)
1
}
2
fn as_int_literal(expr: &Expr) -> Option<i32> {
2
    match expr {
2
        Expr::Atomic(_, Atom::Literal(Lit::Int(n))) => Some(*n),
        _ => None,
    }
2
}
/// Channel `e` into an atom for the Lee abs argument, preferring a flat weighted sum for `a - b`.
2
fn flatten_lee_diff_to_atom(
2
    inner: Expr,
2
    symbols: &mut SymbolTable,
2
    top_level_exprs: &mut Vec<Expr>,
2
) -> Result<Atom, ApplicationError> {
2
    if let Expr::Minus(_, lhs, rhs) = &inner {
2
        let lhs_atom: Result<&Atom, _> = lhs.as_ref().try_into();
2
        let rhs_atom: Result<&Atom, _> = rhs.as_ref().try_into();
2
        if let (Ok(a), Ok(b)) = (lhs_atom, rhs_atom) {
2
            let domain = inner.domain_of().ok_or(ApplicationError::DomainError)?;
2
            let diff = Atom::new_ref(symbols.gen_find_auxiliary(&domain));
2
            let coefficients = vec![Lit::Int(1), Lit::Int(-1)];
2
            let vars = vec![a.clone(), b.clone()];
2
            top_level_exprs.push(Expr::FlatWeightedSumLeq(
2
                Metadata::new(),
2
                coefficients.clone(),
2
                vars.clone(),
2
                Moo::new(diff.clone()),
2
            ));
2
            top_level_exprs.push(Expr::FlatWeightedSumGeq(
2
                Metadata::new(),
2
                coefficients,
2
                vars,
2
                Moo::new(diff.clone()),
2
            ));
2
            return Ok(diff);
        }
    }
    flatten_expression_to_atom(inner, symbols, top_level_exprs)
2
}
/// Lowers a bare `min([a, b, ...])` to an auxiliary bound by Minion's native `min` constraint.
///
/// Priority is above Base `min_to_var` so Minion keeps Savile Row's `min(vars, aux)` encoding
/// instead of expanding into leq/or/eq constraints that become watched-or.
#[register_rule("Minion", 6100, [Min])]
8063
fn introduce_mineq_from_min(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
8063
    let Expr::Min(_, inside_min_expr) = expr else {
7774
        return Err(RuleNotApplicable);
    };
289
    let Some(exprs) = inside_min_expr.as_ref().clone().into_list() else {
189
        return Err(RuleNotApplicable);
    };
100
    if exprs.is_empty() {
        return Err(RuleNotApplicable);
100
    }
100
    let domain = expr.domain_of().ok_or(ApplicationError::DomainError)?;
100
    let mut symbols = symbols.clone();
100
    let mut new_tops: Vec<Expr> = Vec::new();
100
    let mut atoms = Vec::with_capacity(exprs.len());
100
    for child in exprs {
209
        atoms.push(flatten_expression_to_atom(
209
            child,
209
            &mut symbols,
209
            &mut new_tops,
209
        )?);
    }
100
    let aux = Atom::new_ref(symbols.gen_find_auxiliary(&domain));
100
    new_tops.push(Expr::FlatMinEq(Metadata::new(), atoms, aux.clone()));
100
    Ok(RuleEffect::new(
100
        Expr::Atomic(Metadata::new(), aux),
100
        new_tops,
100
        symbols,
100
    ))
8063
}
/// Lowers `x = min([a, b, ...])` / auxiliary declarations of `min` to [`Expr::FlatMinEq`].
#[register_rule("Minion", 6100, [Eq / Min, AuxDeclaration / Min])]
7874
fn introduce_mineq(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
7874
    let (result, min_expr): (Atom, Expr) = match expr.clone() {
        Expr::Eq(_, a, b) => {
234
            let a = Moo::unwrap_or_clone(a);
234
            let b = Moo::unwrap_or_clone(b);
234
            let a_atom: Option<&Atom> = (&a).try_into().ok();
234
            let b_atom: Option<&Atom> = (&b).try_into().ok();
234
            if let Some(a_atom) = a_atom {
168
                Ok((a_atom.clone(), b))
66
            } else if let Some(b_atom) = b_atom {
18
                Ok((b_atom.clone(), a))
            } else {
48
                Err(RuleNotApplicable)
            }
        }
        Expr::AuxDeclaration(_, reference, inner) => {
295
            Ok((Atom::Reference(reference), Moo::unwrap_or_clone(inner)))
        }
7345
        _ => Err(RuleNotApplicable),
7393
    }?;
481
    let Expr::Min(_, inside_min_expr) = min_expr else {
381
        return Err(RuleNotApplicable);
    };
100
    let Some(exprs) = inside_min_expr.as_ref().clone().into_list() else {
99
        return Err(RuleNotApplicable);
    };
1
    if exprs.is_empty() {
        return Err(RuleNotApplicable);
1
    }
1
    let mut symbols = symbols.clone();
1
    let mut new_tops: Vec<Expr> = Vec::new();
1
    let mut atoms = Vec::with_capacity(exprs.len());
1
    for child in exprs {
2
        atoms.push(flatten_expression_to_atom(
2
            child,
2
            &mut symbols,
2
            &mut new_tops,
2
        )?);
    }
1
    let flat = Expr::FlatMinEq(Metadata::new(), atoms, result);
1
    if new_tops.is_empty() {
1
        Ok(RuleEffect::pure(flat))
    } else {
        Ok(RuleEffect::new(flat, new_tops, symbols))
    }
7874
}
#[register_rule("Minion", 4400, [Eq / Abs, AuxDeclaration / Abs])]
5701
fn introduce_abseq(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
5701
    let (x, abs_y): (Atom, Expr) = match expr.clone() {
        Expr::Eq(_, a, b) => {
177
            let a: Expr = Moo::unwrap_or_clone(a);
177
            let b: Expr = Moo::unwrap_or_clone(b);
177
            let a_atom: Option<&Atom> = (&a).try_into().ok();
177
            let b_atom: Option<&Atom> = (&b).try_into().ok();
177
            if let Some(a_atom) = a_atom {
156
                Ok((a_atom.clone(), b))
21
            } else if let Some(b_atom) = b_atom {
9
                Ok((b_atom.clone(), a))
            } else {
12
                Err(RuleNotApplicable)
            }
        }
        Expr::AuxDeclaration(_, reference, expr) => {
285
            let a = Atom::Reference(reference);
285
            let expr = Moo::unwrap_or_clone(expr);
285
            Ok((a, expr))
        }
5239
        _ => Err(RuleNotApplicable),
5251
    }?;
450
    let Expr::Abs(_, y) = abs_y else {
288
        return Err(RuleNotApplicable);
    };
162
    let y = Moo::unwrap_or_clone(y);
162
    let y: Atom = y.try_into().or(Err(RuleNotApplicable))?;
135
    Ok(RuleEffect::pure(Expr::FlatAbsEq(
135
        Metadata::new(),
135
        Moo::new(x),
135
        Moo::new(y),
135
    )))
5701
}
/// Introduces a `MinionPowEq` constraint from a `SafePow`
#[register_rule("Minion", 4200, [Eq / SafePow, AuxDeclaration / SafePow])]
3238
fn introduce_poweq(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
3238
    let (a, b, total) = match expr.clone() {
135
        Expr::Eq(_, e1, e2) => match (Moo::unwrap_or_clone(e1), Moo::unwrap_or_clone(e2)) {
            (Expr::Atomic(_, total), Expr::SafePow(_, a, b)) => Ok((a, b, total)),
54
            (Expr::SafePow(_, a, b), Expr::Atomic(_, total)) => Ok((a, b, total)),
81
            _ => Err(RuleNotApplicable),
        },
72
        Expr::AuxDeclaration(_, total_reference, e) => match Moo::unwrap_or_clone(e) {
            Expr::SafePow(_, a, b) => {
72
                let total_ref_atom = Atom::Reference(total_reference);
72
                Ok((a, b, total_ref_atom))
            }
            _ => Err(RuleNotApplicable),
        },
3031
        _ => Err(RuleNotApplicable),
3112
    }?;
126
    let a: Atom = Moo::unwrap_or_clone(a)
126
        .try_into()
126
        .or(Err(RuleNotApplicable))?;
117
    let b: Atom = Moo::unwrap_or_clone(b)
117
        .try_into()
117
        .or(Err(RuleNotApplicable))?;
    // `SafePow` leaves its value unconstrained where `a ** b` is undefined (negative exponents and
    // `0 ** 0`); definedness is enforced separately. Minion's `pow` instead fails on most negative
    // exponents and gives `0 ** 0 = 1`, so it only defines the result where the power is defined.
135
    let can_be_zero = |atom: &Atom| {
135
        atom.domain_of()
135
            .resolve()
135
            .ok()
135
            .is_none_or(|domain| domain.contains(&Lit::Int(0)).unwrap_or(true))
135
    };
117
    let mut defined = Vec::new();
117
    if can_be_zero(&a) && can_be_zero(&b) {
9
        defined.push(Expr::Or(
9
            Metadata::new(),
9
            Moo::new(matrix_expr![
9
                Expr::Neq(
9
                    Metadata::new(),
9
                    Moo::new(Expr::Atomic(Metadata::new(), a.clone())),
9
                    Moo::new(0.into()),
9
                ),
9
                Expr::Neq(
9
                    Metadata::new(),
9
                    Moo::new(Expr::Atomic(Metadata::new(), b.clone())),
9
                    Moo::new(0.into()),
9
                ),
9
            ]),
9
        ));
108
    }
117
    if minion_atom_as_i32_bounds(&b).is_none_or(|(low, _)| low < 0) {
18
        defined.push(Expr::Geq(
18
            Metadata::new(),
18
            Moo::new(Expr::Atomic(Metadata::new(), b.clone())),
18
            Moo::new(0.into()),
18
        ));
99
    }
117
    let pow = Expr::MinionPow(Metadata::new(), Moo::new(a), Moo::new(b), Moo::new(total));
117
    if defined.is_empty() {
99
        return Ok(RuleEffect::pure(pow));
18
    }
18
    let defined = if defined.len() == 1 {
9
        defined.pop().unwrap()
    } else {
9
        Expr::And(Metadata::new(), Moo::new(into_matrix_expr!(defined)))
    };
18
    Ok(RuleEffect::pure(Expr::Imply(
18
        Metadata::new(),
18
        Moo::new(defined),
18
        Moo::new(pow),
18
    )))
3238
}
/// Introduces a `FlatAlldiff` constraint from an `AllDiff`
#[register_rule("Minion", 4200, [AllDiff])]
5962
fn introduce_flat_alldiff(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
5962
    let Expr::AllDiff(_, es) = expr else {
3139
        return Err(RuleNotApplicable);
    };
2823
    let matrix_expr = match es.as_ref() {
189
        Expr::Flatten(_, None, m) => Moo::unwrap_or_clone(m.clone()),
2634
        _ => Moo::unwrap_or_clone(es.clone()),
    };
2823
    let es = if matrix_expr.is_list() {
1899
        matrix_expr.into_list()
    } else {
924
        matrix_expr
924
            .unwrap_matrix_unchecked()
            .map(|(elements, _)| elements)
    }
2823
    .ok_or(RuleNotApplicable)?;
2388
    let atoms = es
2388
        .into_iter()
16683
        .map(|e| match e {
16638
            Expr::Atomic(_, atom) => Ok(atom),
45
            _ => Err(RuleNotApplicable),
16683
        })
2388
        .process_results(|iter| iter.collect_vec())?;
2343
    Ok(RuleEffect::pure(Expr::FlatAllDiff(Metadata::new(), atoms)))
5962
}
639
fn unwrap_flatten_operand(operand: &Moo<Expr>) -> Option<Moo<Expr>> {
639
    match operand.as_ref() {
108
        Expr::Flatten(_, None, inner) => Some(inner.clone()),
531
        _ => None,
    }
639
}
/// Unwraps `flatten(m)` operands in global cardinality constraints.
#[register_rule("Minion", 4050, [AtMost, AtLeast, Gcc, GccWeak])]
2458
fn unwrap_flatten_in_global_cardinality(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
2458
    match expr {
        Expr::AtMost(meta, vars, counts, values) => {
369
            let Some(vars) = unwrap_flatten_operand(vars) else {
261
                return Err(RuleNotApplicable);
            };
108
            Ok(RuleEffect::pure(Expr::AtMost(
108
                meta.clone(),
108
                vars,
108
                counts.clone(),
108
                values.clone(),
108
            )))
        }
        Expr::AtLeast(meta, vars, counts, values) => {
90
            let Some(vars) = unwrap_flatten_operand(vars) else {
90
                return Err(RuleNotApplicable);
            };
            Ok(RuleEffect::pure(Expr::AtLeast(
                meta.clone(),
                vars,
                counts.clone(),
                values.clone(),
            )))
        }
        Expr::Gcc(meta, vars, values, counts) => {
108
            let Some(vars) = unwrap_flatten_operand(vars) else {
108
                return Err(RuleNotApplicable);
            };
            Ok(RuleEffect::pure(Expr::Gcc(
                meta.clone(),
                vars,
                values.clone(),
                counts.clone(),
            )))
        }
        Expr::GccWeak(meta, vars, values, counts) => {
72
            let Some(vars) = unwrap_flatten_operand(vars) else {
72
                return Err(RuleNotApplicable);
            };
            Ok(RuleEffect::pure(Expr::GccWeak(
                meta.clone(),
                vars,
                values.clone(),
                counts.clone(),
            )))
        }
1819
        _ => Err(RuleNotApplicable),
    }
2458
}
/// Lowers `allDifferentExcept` to Minion's `gccweak`, matching Savile Row.
#[register_rule("Minion", 4100, [AllDifferentExcept])]
2593
fn alldifferent_except_to_gccweak(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
2593
    let Expr::AllDifferentExcept(_, matrix, except) = expr else {
2431
        return Err(RuleNotApplicable);
    };
162
    let es = (**matrix).clone().into_list().ok_or(RuleNotApplicable)?;
72
    if es.is_empty() {
        return Err(RuleNotApplicable);
72
    }
72
    let Lit::Int(except_val) = eval_constant(except.as_ref()).ok_or(RuleNotApplicable)? else {
        return Err(RuleNotApplicable);
    };
27
    let domain = es[0]
27
        .domain_of()
27
        .ok_or(RuleNotApplicable)?
        .resolve()
        .map_err(|_| RuleNotApplicable)?;
27
    let GroundDomain::Int(_, _) = domain.as_ref() else {
        return Err(RuleNotApplicable);
    };
27
    let values: Vec<i32> = domain
27
        .values()
        .map_err(|_| RuleNotApplicable)?
234
        .filter_map(|v| match v {
234
            Lit::Int(i) if i != except_val => Some(i),
27
            _ => None,
234
        })
        .collect();
27
    let mut symbols = symbols.clone();
27
    let mut count_exprs = vec![];
27
    for _ in &values {
207
        let decl = symbols.gen_find_auxiliary(&Domain::bool());
207
        count_exprs.push(Expr::Atomic(
207
            Metadata::new(),
207
            Atom::Reference(Reference::new(decl)),
207
        ));
    }
27
    let value_exprs = values
27
        .iter()
207
        .map(|v| Expr::Atomic(Metadata::new(), Atom::Literal(Lit::Int(*v))))
        .collect_vec();
27
    Ok(RuleEffect::new(
27
        Expr::GccWeak(
27
            Metadata::new(),
27
            Moo::new(into_matrix_expr![es]),
27
            Moo::new(into_matrix_expr![value_exprs]),
27
            Moo::new(into_matrix_expr![count_exprs]),
27
        ),
27
        vec![],
27
        symbols,
27
    ))
2593
}
/// A variable exception uses defined occurrence counts, even beneath reification.
#[register_rule("Minion", 4100, [AllDifferentExcept])]
2593
fn alldifferent_variable_except(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
2593
    let Expr::AllDifferentExcept(_, matrix, except) = expr else {
2431
        return Err(RuleNotApplicable);
    };
162
    if eval_constant(except).is_some() || !except.domain_of().is_some_and(|domain| domain.is_int())
    {
72
        return Err(RuleNotApplicable);
90
    }
90
    let inputs = matrix.unwrap_list_cow().ok_or(RuleNotApplicable)?;
45
    if inputs.len() < 2 {
        return Ok(RuleEffect::pure(true.into()));
45
    }
45
    let size = i32::try_from(inputs.len()).map_err(|_| RuleNotApplicable)?;
45
    let mut values = std::collections::BTreeSet::new();
    // Large domains use pairwise comparisons rather than enumerating every value.
45
    let limit = inputs.len().saturating_mul(inputs.len());
45
    for input in inputs.iter() {
135
        let domain = input
135
            .domain_of()
135
            .ok_or(RuleNotApplicable)?
            .resolve()
            .map_err(|_| RuleNotApplicable)?;
135
        if !matches!(domain.as_ref(), GroundDomain::Int(_, _)) {
            return Err(RuleNotApplicable);
135
        }
135
        for value in domain.values().map_err(|_| RuleNotApplicable)? {
369
            let Lit::Int(value) = value else {
                return Err(RuleNotApplicable);
            };
369
            values.insert(value);
369
            if values.len() > limit {
                let mut pairs = Vec::new();
                for (index, left) in inputs.iter().enumerate() {
                    for right in &inputs[index + 1..] {
                        pairs.push(Expr::Or(
                            Metadata::new(),
                            Moo::new(into_matrix_expr![vec![
                                Expr::Neq(
                                    Metadata::new(),
                                    Moo::new(left.clone()),
                                    Moo::new(right.clone())
                                ),
                                Expr::Eq(Metadata::new(), Moo::new(left.clone()), except.clone()),
                            ]]),
                        ));
                    }
                }
                return Ok(RuleEffect::pure(Expr::And(
                    Metadata::new(),
                    Moo::new(into_matrix_expr![pairs]),
                )));
369
            }
        }
    }
45
    let mut symbols = symbols.clone();
45
    let mut counts = Vec::new();
45
    let mut bounds = Vec::new();
45
    let mut literals = Vec::new();
45
    for value in values {
        let count: Expr =
135
            Reference::new(symbols.gen_find_auxiliary(&Domain::int(vec![Range::Bounded(0, size)])))
135
                .into();
135
        let value: Expr = value.into();
135
        bounds.push(Expr::Or(
135
            Metadata::new(),
135
            Moo::new(into_matrix_expr![vec![
135
                Expr::Eq(Metadata::new(), except.clone(), Moo::new(value.clone())),
135
                Expr::Leq(Metadata::new(), Moo::new(count.clone()), Moo::new(1.into())),
135
            ]]),
135
        ));
135
        counts.push(count);
135
        literals.push(value);
    }
45
    let definition = Expr::GccWeak(
45
        Metadata::new(),
45
        Moo::new(into_matrix_expr![inputs.into_owned()]),
45
        Moo::new(into_matrix_expr![literals]),
45
        Moo::new(into_matrix_expr![counts]),
45
    );
45
    Ok(RuleEffect::new(
45
        Expr::And(Metadata::new(), Moo::new(into_matrix_expr![bounds])),
45
        vec![definition],
45
        symbols,
45
    ))
2593
}
/// Native element requires a valid index; materialise identity entries across the finite bounds.
#[register_rule("Minion", 19500, [ElementId])]
11597
fn total_identity_element(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
11597
    let Expr::ElementId(_, matrix, index) = expr else {
11336
        return Err(RuleNotApplicable);
    };
261
    let (entries, labels) = (**matrix)
261
        .clone()
261
        .unwrap_matrix_unchecked()
261
        .ok_or(RuleNotApplicable)?;
225
    if entries.is_empty() {
        let default = if index.return_type() == ReturnType::Bool {
            Expr::ToInt(Metadata::new(), index.clone())
        } else {
            (**index).clone()
        };
        return Ok(RuleEffect::pure(default));
225
    }
225
    if entries
225
        .iter()
450
        .any(|entry| !matches!(entry.return_type(), ReturnType::Int | ReturnType::Bool))
    {
        return Err(RuleNotApplicable);
225
    }
225
    let labels = if matrix.is_list() {
        (1..=entries.len())
            .map(|label| i32::try_from(label).ok())
            .collect::<Option<Vec<_>>>()
            .ok_or(RuleNotApplicable)?
    } else {
225
        labels
225
            .resolve()
            .map_err(|_| RuleNotApplicable)?
            .values()
            .map_err(|_| RuleNotApplicable)?
450
            .map(|label| match label {
450
                Lit::Int(value) => Some(value),
                Lit::Bool(value) => Some(i32::from(value)),
                _ => None,
450
            })
            .collect::<Option<Vec<_>>>()
225
            .ok_or(RuleNotApplicable)?
    };
225
    if labels.len() != entries.len() {
        return Err(RuleNotApplicable);
225
    }
225
    let domain = index
225
        .domain_of()
225
        .ok_or(RuleNotApplicable)?
        .resolve()
        .map_err(|_| RuleNotApplicable)?;
225
    let (minimum, maximum, index) = match domain.as_ref() {
        GroundDomain::Bool => (0, 1, Expr::ToInt(Metadata::new(), index.clone())),
        GroundDomain::Int(ranges, _) => {
225
            let bounds = ranges
225
                .iter()
225
                .map(|range| match range {
                    Range::Single(value) => Some((*value, *value)),
225
                    Range::Bounded(lower, upper) => Some((*lower, *upper)),
                    _ => None,
225
                })
                .collect::<Option<Vec<_>>>()
225
                .ok_or(RuleNotApplicable)?;
            (
225
                bounds
225
                    .iter()
225
                    .map(|(lower, _)| *lower)
                    .min()
225
                    .ok_or(RuleNotApplicable)?,
225
                bounds
225
                    .iter()
225
                    .map(|(_, upper)| *upper)
                    .max()
225
                    .ok_or(RuleNotApplicable)?,
225
                (**index).clone(),
            )
        }
        _ => return Err(RuleNotApplicable),
    };
225
    let entries: HashMap<_, _> = labels.into_iter().zip(entries).collect();
225
    let total = (minimum..=maximum)
1125
        .map(|label| {
1125
            let entry = entries.get(&label).cloned().unwrap_or_else(|| label.into());
1125
            if entry.return_type() == ReturnType::Bool {
                Expr::ToInt(Metadata::new(), Moo::new(entry))
            } else {
1125
                entry
            }
1125
        })
        .collect::<Vec<_>>();
225
    Ok(RuleEffect::pure(Expr::UnsafeIndex(
225
        Metadata::new(),
225
        Moo::new(into_matrix_expr![total; Domain::int(vec![Range::Bounded(minimum, maximum)])]),
225
        vec![index],
225
    )))
11597
}
/// Introduces `MinionElementOne` from an auxiliary variable bound to `indexOf`.
#[register_rule("Minion", 4400, [AuxDeclaration])]
186162
fn introduce_index_of_from_aux_decl(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
186162
    let Expr::AuxDeclaration(_, reference, inner) = expr else {
5371
        return Err(RuleNotApplicable);
    };
180791
    let Expr::IndexOf(_, matrix, value) = inner.as_ref() else {
179450
        return Err(RuleNotApplicable);
    };
1341
    let value_expr = (**value).clone();
1341
    let value_atom: Atom = value_expr.clone().try_into().or(Err(RuleNotApplicable))?;
693
    let matrix_elems = (**matrix)
693
        .clone()
693
        .unwrap_matrix_unchecked()
        .map(|(elements, _)| elements);
693
    if let Some(elems) = matrix_elems {
693
        let mut atom_list = vec![];
693
        for elem in elems {
2988
            let Expr::Atomic(_, elem) = elem else {
                return Err(RuleNotApplicable);
            };
2988
            atom_list.push(elem);
        }
        // Neither Minion's native `element` constraint nor its `table` fallback (both used
        // below) can take a compound (e.g. tuple) value as a list entry -- both need a plain
        // int/bool atom per position. When the search list holds compound literals (as
        // `FunctionAsRelation`/`FunctionExplicit`'s own `image()` rules build for a compound
        // function domain), fall back to an explicit per-candidate lookup instead: `reference`
        // (the position) is pinned by a disjunction trying each candidate position, guarded by
        // `value_expr` equalling that candidate's own literal -- the same "compare against each
        // candidate" shape `RelationPacked::tuple_membership_expr` and the tuple-literal equality
        // rules (`types::tuple::horizontal::tuple_literal_eq_literal`) already use for compound
        // values elsewhere, just built directly here since this list is always fully literal.
693
        if let Some(lookup) = compound_index_of_lookup(&atom_list, &value_expr, reference) {
            return Ok(RuleEffect::pure(lookup));
693
        }
        // Use table only if the search value can be out of bounds; otherwise element_one.
693
        if let Some(search_values) = literal_matrix_int_values(&atom_list)
693
            && index_of_value_may_be_outside_matrix(&value_expr, &search_values)
        {
9
            if let Ok(atom_list) = indexed_index_of_inverse_lookup(matrix.as_ref(), &value_expr) {
9
                return Ok(RuleEffect::pure(Expr::MinionElementOne(
9
                    Metadata::new(),
9
                    atom_list,
9
                    Moo::new(Atom::Reference(reference.clone())),
9
                    Moo::new(value_atom),
9
                )));
            }
            let rows = index_of_table_rows(&value_expr, &search_values)?;
            let tuple = into_matrix_expr![vec![
                value_expr,
                Expr::Atomic(Metadata::new(), Atom::Reference(reference.clone()),),
            ]];
            return Ok(RuleEffect::pure(Expr::Table(
                Metadata::new(),
                Moo::new(tuple),
                Moo::new(rows),
            )));
684
        }
684
        let atom_list = pad_indexed_index_of_list(matrix.as_ref(), atom_list.clone(), reference)
            .or_else(|| pad_represented_index_of_list(atom_list.clone(), reference))
684
            .unwrap_or(atom_list);
684
        return Ok(RuleEffect::pure(Expr::MinionElementOne(
684
            Metadata::new(),
684
            atom_list,
684
            Moo::new(Atom::Reference(reference.clone())),
684
            Moo::new(value_atom),
684
        )));
    }
    let atom_list = indexed_index_of_inverse_lookup(matrix.as_ref(), &value_expr)?;
    Ok(RuleEffect::pure(Expr::MinionElementOne(
        Metadata::new(),
        atom_list,
        Moo::new(value_atom),
        Moo::new(Atom::Reference(reference.clone())),
    )))
186162
}
/// `indexOf([e1,...,en], value) = reference` where at least one `ei` is a *compound* literal
/// (a matrix of plain int/bool literals is left to the native `element`/`table` lowering, which
/// already handles it): `reference` is pinned to the one-based position `i` such that `value`
/// equals `ei`, expressed directly as a disjunction over positions rather than through any
/// Minion-specific "list of atoms" primitive, since a compound element has no single atom to put
/// in such a list. `value`'s own equality against a compound literal is resolved by the ordinary
/// tuple-literal-equality machinery once this reaches the general rule engine again (this rule
/// only ever fires after the whole model has already been rewritten down to the `Minion`
/// ruleset's own passes, but the `Eq`/`In` nodes built here are still plain AST nodes, not
/// Minion-specific ones, so earlier "Base"/"ReprGeneral" rules such as
/// `types::tuple::horizontal::tuple_literal_eq_literal` still apply to them on the next pass).
///
/// Returns `None` (not an error) when every element is already scalar, so the caller falls
/// through to the existing, more efficient native-constraint paths unchanged.
693
fn compound_index_of_lookup(
693
    atom_list: &[Atom],
693
    value_expr: &Expr,
693
    reference: &Reference,
693
) -> Option<Expr> {
693
    if literal_matrix_int_values(atom_list).is_some() {
693
        return None;
    }
    let literals: Vec<&Lit> = atom_list
        .iter()
        .map(|atom| match atom {
            Atom::Literal(lit) => Some(lit),
            Atom::Reference(_) => None,
        })
        .collect::<Option<_>>()?;
    let reference_expr = Expr::Atomic(Metadata::new(), Atom::Reference(reference.clone()));
    let choices: Vec<Expr> = literals
        .into_iter()
        .enumerate()
        .map(|(zero_based_index, lit)| {
            let position = zero_based_index as i32 + 1;
            let matches_value = Expr::Eq(
                Metadata::new(),
                Moo::new(value_expr.clone()),
                Moo::new(Expr::Atomic(Metadata::new(), Atom::Literal(lit.clone()))),
            );
            let pins_position = Expr::Eq(
                Metadata::new(),
                Moo::new(reference_expr.clone()),
                Moo::new(position.into()),
            );
            Expr::And(
                Metadata::new(),
                Moo::new(matrix_expr![matches_value, pins_position]),
            )
        })
        .collect();
    Some(Expr::Or(
        Metadata::new(),
        Moo::new(into_matrix_expr![choices]),
    ))
693
}
9
fn indexed_index_of_inverse_lookup(
9
    matrix_expr: &Expr,
9
    value_expr: &Expr,
9
) -> Result<Vec<Atom>, ApplicationError> {
    let (elems, index_domain) =
9
        indexed_index_of_literal_parts(matrix_expr).ok_or(RuleNotApplicable)?;
9
    let GroundDomain::Int(index_ranges, _) = index_domain.as_ref() else {
        return Err(RuleNotApplicable);
    };
9
    let index_values = Range::values(index_ranges)
9
        .ok_or(RuleNotApplicable)?
        .collect_vec();
9
    if index_values.len() != elems.len() {
        return Err(RuleNotApplicable);
9
    }
9
    let value_domain = value_expr.domain_of().ok_or(RuleNotApplicable)?;
9
    let value_domain = value_domain.resolve().map_err(|_| RuleNotApplicable)?;
9
    let GroundDomain::Int(value_ranges, _) = value_domain.as_ref() else {
        return Err(RuleNotApplicable);
    };
9
    let value_values = Range::values(value_ranges)
9
        .ok_or(RuleNotApplicable)?
        .collect_vec();
9
    let max_value = value_values
9
        .iter()
9
        .copied()
9
        .max()
9
        .ok_or(RuleNotApplicable)?;
27
    if value_values.iter().any(|value| *value < 1) {
        return Err(RuleNotApplicable);
9
    }
9
    let mut lookup: Vec<i32> = (1..=max_value).collect();
9
    let mut seen_elements = HashSet::new();
9
    for (index, elem) in index_values.into_iter().zip(elems) {
18
        if elem < 1 || elem > max_value || !seen_elements.insert(elem) {
            return Err(RuleNotApplicable);
18
        }
18
        lookup[(elem - 1) as usize] = index;
    }
9
    Ok(lookup
9
        .into_iter()
27
        .map(|value| Atom::Literal(Lit::Int(value)))
        .collect())
9
}
684
fn pad_indexed_index_of_list(
684
    matrix_expr: &Expr,
684
    atom_list: Vec<Atom>,
684
    result: &Reference,
684
) -> Option<Vec<Atom>> {
684
    let index_domain = match matrix_expr {
        Expr::AbstractLiteral(_, AbstractLiteral::Matrix(_, index_domain)) => {
            index_domain.resolve().ok()?
        }
        Expr::Atomic(
            _,
            Atom::Literal(Lit::AbstractLiteral(AbstractLiteral::Matrix(_, index_domain))),
684
        ) => index_domain.clone(),
        _ => return None,
    };
684
    let GroundDomain::Int(index_ranges, _) = index_domain.as_ref() else {
        return None;
    };
684
    let index_values = Range::values(index_ranges)?.collect_vec();
684
    if index_values.len() != atom_list.len() {
        return None;
684
    }
684
    let result_domain = result.domain()?.resolve().ok()?;
684
    let GroundDomain::Int(result_ranges, _) = result_domain.as_ref() else {
        return None;
    };
684
    let max_result = Range::values(result_ranges)?.max()?;
684
    let mut padded: Vec<Atom> = (1..=max_result)
2970
        .map(|value| Lit::Int(value).into())
        .collect();
684
    for (index, atom) in index_values.into_iter().zip(atom_list) {
2970
        if !(1..=max_result).contains(&index) {
            return None;
2970
        }
2970
        padded[(index - 1) as usize] = atom;
    }
684
    Some(padded)
684
}
fn pad_represented_index_of_list(atom_list: Vec<Atom>, result: &Reference) -> Option<Vec<Atom>> {
    let result_domain = result.domain()?.resolve().ok()?;
    let GroundDomain::Int(result_ranges, _) = result_domain.as_ref() else {
        return None;
    };
    let result_values = Range::values(result_ranges)?.collect_vec();
    let max_result = result_values.iter().copied().max()?;
    if max_result <= atom_list.len() as i32 {
        return None;
    }
    let mut padded: Vec<Atom> = (1..=max_result)
        .map(|value| Lit::Int(value).into())
        .collect();
    let mut changed = false;
    for atom in atom_list {
        let position = represented_matrix_to_atom_index(&atom)?;
        if !(1..=max_result).contains(&position) {
            return None;
        }
        padded[(position - 1) as usize] = atom;
        changed = true;
    }
    changed.then_some(padded)
}
fn represented_matrix_to_atom_index(atom: &Atom) -> Option<i32> {
    let Atom::Reference(reference) = atom else {
        return None;
    };
    let name = reference.name();
    let Name::Represented(fields) = &*name else {
        return None;
    };
    let (_, rule, suffix) = fields.as_ref();
    if *rule != MatrixComponents::id() {
        return None;
    }
    suffix.as_str().parse().ok()
}
9
fn indexed_index_of_literal_parts(matrix_expr: &Expr) -> Option<(Vec<i32>, Moo<GroundDomain>)> {
9
    match matrix_expr {
        Expr::AbstractLiteral(_, AbstractLiteral::Matrix(elems, index_domain)) => Some((
            elems.iter().map(expr_int_literal).collect::<Option<_>>()?,
            index_domain.resolve().ok()?,
        )),
        Expr::Atomic(
            _,
            Atom::Literal(Lit::AbstractLiteral(AbstractLiteral::Matrix(elems, index_domain))),
        ) => Some((
9
            elems.iter().map(lit_int).collect::<Option<_>>()?,
9
            index_domain.clone(),
        )),
        _ => None,
    }
9
}
fn expr_int_literal(expr: &Expr) -> Option<i32> {
    match expr {
        Expr::Atomic(_, Atom::Literal(lit)) => lit_int(lit),
        _ => None,
    }
}
5994
fn lit_int(lit: &Lit) -> Option<i32> {
5994
    match lit {
5994
        Lit::Int(value) => Some(*value),
        _ => None,
    }
5994
}
1386
fn literal_matrix_int_values(atoms: &[Atom]) -> Option<Vec<i32>> {
1386
    atoms
1386
        .iter()
5976
        .map(|atom| match atom {
5976
            Atom::Literal(lit) => lit_int(lit),
            _ => None,
5976
        })
        .collect()
1386
}
693
fn index_of_value_may_be_outside_matrix(value_expr: &Expr, search_values: &[i32]) -> bool {
693
    let Some(value_domain) = value_expr
693
        .domain_of()
693
        .and_then(|domain| domain.resolve().ok())
    else {
        return true;
    };
693
    let Ok(value_values) = value_domain.values_i32() else {
        return true;
    };
693
    value_values
693
        .iter()
2997
        .any(|value| !search_values.contains(value))
693
}
fn index_of_table_rows(value_expr: &Expr, search_values: &[i32]) -> Result<Expr, ApplicationError> {
    let value_domain = value_expr
        .domain_of()
        .ok_or(RuleNotApplicable)?
        .resolve()
        .map_err(|_| RuleNotApplicable)?;
    let value_values = value_domain.values_i32().map_err(|_| RuleNotApplicable)?;
    let sentinel = i32::try_from(search_values.len()).map_err(|_| RuleNotApplicable)? + 1;
    let value_to_index: HashMap<i32, i32> = search_values
        .iter()
        .enumerate()
        .map(|(index, value)| (*value, (index + 1) as i32))
        .collect();
    let rows = value_values
        .into_iter()
        .map(|value| {
            let index = value_to_index.get(&value).copied().unwrap_or(sentinel);
            into_matrix_expr![vec![
                Expr::Atomic(Metadata::new(), Lit::Int(value).into()),
                Expr::Atomic(Metadata::new(), Lit::Int(index).into()),
            ]]
        })
        .collect_vec();
    Ok(into_matrix_expr![rows])
}
/// General (any-`Literal`) counterpart to [`indexed_index_of_literal_parts`], used when the
/// search target may itself be compound (e.g. a tuple), not just a plain int.
974
fn indexed_index_of_parts(matrix_expr: &Expr) -> Option<(Vec<Lit>, Moo<GroundDomain>)> {
974
    match matrix_expr {
        Expr::AbstractLiteral(_, AbstractLiteral::Matrix(elems, index_domain)) => Some((
2
            elems.iter().map(eval_constant).collect::<Option<_>>()?,
2
            index_domain.resolve().ok()?,
        )),
        Expr::Atomic(
            _,
            Atom::Literal(Lit::AbstractLiteral(AbstractLiteral::Matrix(elems, index_domain))),
972
        ) => Some((elems.clone(), index_domain.clone())),
        _ => None,
    }
974
}
3287
fn fold_constant_index_of_to_index(index_of: &Expr) -> Option<Expr> {
3287
    let Expr::IndexOf(_, matrix, value) = index_of else {
2313
        return None;
    };
974
    let search_value = eval_constant(value.as_ref())?;
974
    let (elems, index_domain) = indexed_index_of_parts(matrix.as_ref())?;
974
    let GroundDomain::Int(index_ranges, _) = index_domain.as_ref() else {
        return None;
    };
974
    let index_values = Range::values(index_ranges)?.collect_vec();
974
    if elems.len() != index_values.len() {
        return None;
974
    }
974
    for (elem, index) in elems.into_iter().zip(index_values) {
2598
        if elem.essence_cmp(&search_value).is_eq() {
974
            return Some(Expr::Atomic(
974
                Metadata::new(),
974
                Atom::Literal(Lit::Int(index)),
974
            ));
1624
        }
    }
    // Match the identity-padding used by [`pad_indexed_index_of_list`] / Minion `element_one`
    // for partial permutations (e.g. `indexOf([j,i;int(i,j)], k)`): values absent from the
    // matrix map to themselves as indices. Without this, out-of-matrix lookups become unconstrained
    // auxiliaries and lex constraints are weakened. Only meaningful for a plain int value -- a
    // compound value has no "map to itself as an index" reading, so it's left unfolded (the
    // AuxDeclaration-based path, `compound_index_of_lookup`, still handles it structurally).
    if let Lit::Int(search_value) = search_value {
        return Some(Expr::Atomic(
            Metadata::new(),
            Atom::Literal(Lit::Int(search_value)),
        ));
    }
    None
3287
}
/// Introduces an auxiliary variable for `indexOf` used as a matrix index.
#[register_rule("Minion", 4300, [SafeIndex])]
14137
fn flatten_index_of_index(expr: &Expr, _symbols: &SymbolTable) -> ApplicationResult {
14137
    let Expr::SafeIndex(meta, subject, indices) = expr else {
4903
        return Err(RuleNotApplicable);
    };
9234
    if indices.len() != 1 {
        return Err(RuleNotApplicable);
9234
    }
9234
    let Expr::IndexOf(_, _, _) = indices[0].clone() else {
8262
        return Err(RuleNotApplicable);
    };
972
    if let Some(index) = fold_constant_index_of_to_index(&indices[0]) {
972
        return Ok(RuleEffect::pure(Expr::SafeIndex(
972
            meta.clone(),
972
            subject.clone(),
972
            vec![index],
972
        )));
    }
    defer_aux_var(&indices[0], {
        let meta = meta.clone();
        let subject = subject.clone();
        move |aux_var_info| {
            RuleEffect::new(
                Expr::SafeIndex(meta.clone(), subject.clone(), vec![aux_var_info.as_expr()]),
                vec![aux_var_info.top_level_expr()],
                aux_var_info.symbols(),
            )
        }
    })
    .ok_or(RuleNotApplicable)
14137
}
/// Introduces a Minion `MinusEq` constraint from `x = -y`, where x and y are atoms.
///
/// ```text
/// x = -y ~> MinusEq(x,y)
///
///   where x,y are atoms
/// ```
#[register_rule("Minion", 4400, [Eq])]
205855
fn introduce_minuseq_from_eq(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
205855
    let Expr::Eq(_, a, b) = expr else {
5407
        return Err(RuleNotApplicable);
    };
400869
    fn try_get_atoms(a: &Moo<Expr>, b: &Moo<Expr>) -> Option<(Atom, Atom)> {
400869
        let a: &Atom = (&**a).try_into().ok()?;
340575
        let Expr::Neg(_, b) = &**b else {
340530
            return None;
        };
45
        let b: &Atom = b.try_into().ok()?;
36
        Some((a.clone(), b.clone()))
400869
    }
    // x = - y. Find this symmetrically (a = - b or b = -a)
200448
    let Some((x, y)) = try_get_atoms(a, b).or_else(|| try_get_atoms(b, a)) else {
200412
        return Err(RuleNotApplicable);
    };
36
    Ok(RuleEffect::pure(Expr::FlatMinusEq(
36
        Metadata::new(),
36
        Moo::new(x),
36
        Moo::new(y),
36
    )))
205855
}
/// Introduces a Minion `MinusEq` constraint from `x =aux -y`, where x and y are atoms.
///
/// ```text
/// x =aux -y ~> MinusEq(x,y)
///
///   where x,y are atoms
/// ```
#[register_rule("Minion", 4400, [AuxDeclaration])]
186162
fn introduce_minuseq_from_aux_decl(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
    // a =aux -b
    //
186162
    let Expr::AuxDeclaration(_, reference, b) = expr else {
5371
        return Err(RuleNotApplicable);
    };
180791
    let a = Atom::Reference(reference.clone());
180791
    let Expr::Neg(_, b) = (**b).clone() else {
180098
        return Err(RuleNotApplicable);
    };
693
    let Ok(b) = b.try_into() else {
9
        return Err(RuleNotApplicable);
    };
684
    Ok(RuleEffect::pure(Expr::FlatMinusEq(
684
        Metadata::new(),
684
        Moo::new(a),
684
        Moo::new(b),
684
    )))
186162
}
/// Converts an implication to either `ineq` or `reifyimply`
///
/// ```text
/// x -> y ~> ineq(x,y,0)
/// where x is atomic, y is atomic
///
/// x -> y ~> reifyimply(y,x)
/// where x is atomic, y is non-atomic
/// ```
#[register_rule("Minion", 4400, [Imply])]
62993
fn introduce_reifyimply_ineq_from_imply(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
62993
    let Expr::Imply(_, x, y) = expr else {
5455
        return Err(RuleNotApplicable);
    };
57538
    let x_atom: &Atom = x.as_ref().try_into().or(Err(RuleNotApplicable))?;
    // if both x and y are atoms,  x -> y ~> ineq(x,y,0)
    //
    // if only x is an atom, x -> y ~> reifyimply(y,x)
26428
    if let Ok(y_atom) = TryInto::<&Atom>::try_into(y.as_ref()) {
2036
        Ok(RuleEffect::pure(Expr::FlatIneq(
2036
            Metadata::new(),
2036
            Moo::new(x_atom.clone()),
2036
            Moo::new(y_atom.clone()),
2036
            Box::new(0.into()),
2036
        )))
    } else {
24392
        Ok(RuleEffect::pure(Expr::MinionReifyImply(
24392
            Metadata::new(),
24392
            y.clone(),
24392
            x_atom.clone(),
24392
        )))
    }
62993
}
/// Constant-folds `__inDomain(indexOf(...), domain)` when the indexOf result domain is
/// already contained in `domain`.
#[register_rule("Minion", 4350, [InDomain])]
4930
fn constant_fold_indomain_index_of(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
4930
    let Expr::InDomain(_, e, domain) = expr else {
4903
        return Err(RuleNotApplicable);
    };
27
    let Expr::IndexOf(..) = e.as_ref() else {
27
        return Err(RuleNotApplicable);
    };
    let expr_domain = e
        .domain_of()
        .ok_or(RuleNotApplicable)?
        .resolve()
        .map_err(|_| RuleNotApplicable)?;
    let domain = domain.resolve().map_err(|_| RuleNotApplicable)?;
    let intersection = expr_domain
        .intersect(&domain)
        .map_err(|_| RuleNotApplicable)?;
    let GroundDomain::Int(_, _) = expr_domain.as_ref() else {
        return Err(RuleNotApplicable);
    };
    let GroundDomain::Int(_, _) = &intersection else {
        return Err(RuleNotApplicable);
    };
    if normalise_int_domain(&intersection) == normalise_int_domain(expr_domain.as_ref()) {
        return Ok(RuleEffect::pure(true.into()));
    }
    if let Ok(values) = intersection.values_i32()
        && values.is_empty()
    {
        return Ok(RuleEffect::pure(false.into()));
    }
    Err(RuleNotApplicable)
4930
}
fn normalise_int_domain(domain: &GroundDomain) -> GroundDomain {
    match domain {
        GroundDomain::Int(ranges, representation) => GroundDomain::Int(
            Range::squeeze(
                &ranges
                    .iter()
                    .map(|range| Range::new(range.low().copied(), range.high().copied()))
                    .collect_vec(),
            ),
            representation.clone(),
        ),
        _ => domain.clone(),
    }
}
/// Resolves `__n =aux matrix[index]` when `index` is a constant `indexOf` lookup.
#[register_rule("Minion", 4450, [AuxDeclaration])]
186714
fn resolve_safeindex_index_of_aux(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
186714
    let Expr::AuxDeclaration(meta, reference, inner) = expr else {
5911
        return Err(RuleNotApplicable);
    };
180803
    let Expr::SafeIndex(index_meta, subject, indices) = inner.as_ref() else {
178490
        return Err(RuleNotApplicable);
    };
2313
    if indices.len() != 1 {
        return Err(RuleNotApplicable);
2313
    }
2313
    let index = fold_constant_index_of_to_index(&indices[0]).ok_or(RuleNotApplicable)?;
    let safeindex = Expr::SafeIndex(index_meta.clone(), subject.clone(), vec![index]);
    let RuleEffect { new_expression, .. } = try_index_matrix_components(&safeindex, symbols)?;
    Ok(RuleEffect::pure(Expr::Eq(
        meta.clone(),
        Moo::new(Expr::Atomic(
            Metadata::new(),
            Atom::Reference(reference.clone()),
        )),
        Moo::new(new_expression),
    )))
186714
}
/// Rewrites `__n =aux matrix[indexOf(..., k)]` when constant `k` is absent from the matrix.
///
/// Uses the same identity-index fallback as [`fold_constant_index_of_to_index`]: the lookup
/// becomes `matrix[k]`. Previously this dropped the aux link entirely, leaving unconstrained
/// auxiliaries inside lex constraints.
#[register_rule("Minion", 4450, [AuxDeclaration])]
186714
fn drop_invalid_constant_index_of_safeindex_aux(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
186714
    let Expr::AuxDeclaration(meta, reference, inner) = expr else {
5911
        return Err(RuleNotApplicable);
    };
180803
    let Expr::SafeIndex(index_meta, subject, indices) = inner.as_ref() else {
178490
        return Err(RuleNotApplicable);
    };
2313
    if indices.len() != 1 {
        return Err(RuleNotApplicable);
2313
    }
2313
    let Expr::IndexOf(_, _, value) = &indices[0] else {
2313
        return Err(RuleNotApplicable);
    };
    // Prefer the shared folder (including identity padding). If it succeeds, rewrite to a plain
    // SafeIndex with that constant index; flatten_index_of_index / resolve paths usually handle
    // this earlier, so this is a fallback.
    let Some(index) = fold_constant_index_of_to_index(&indices[0]) else {
        return Err(RuleNotApplicable);
    };
    if expr_int_literal(value.as_ref()).is_none() {
        return Err(RuleNotApplicable);
    }
    Ok(RuleEffect::pure(Expr::AuxDeclaration(
        meta.clone(),
        reference.clone(),
        Moo::new(Expr::SafeIndex(
            index_meta.clone(),
            subject.clone(),
            vec![index],
        )),
    )))
186714
}
/// Converts `__inDomain(a,domain) to w-inintervalset.
///
/// This applies if domain is integer and finite.
#[register_rule("Minion", 4400, [InDomain])]
5719
fn introduce_wininterval_set_from_indomain(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
5719
    let Expr::InDomain(_, e, domain) = expr else {
5539
        return Err(RuleNotApplicable);
    };
180
    let Expr::Atomic(_, atom @ Atom::Reference(_)) = e.as_ref() else {
27
        return Err(RuleNotApplicable);
    };
153
    let Some(ranges) = domain.as_int_ground() else {
        return Err(RuleNotApplicable);
    };
153
    let mut out_ranges = vec![];
153
    for range in ranges {
225
        match range {
            Range::Single(x) => {
108
                out_ranges.push(*x);
108
                out_ranges.push(*x);
            }
            Range::Bounded(x, y) => {
117
                out_ranges.push(*x);
117
                out_ranges.push(*y);
            }
            Range::UnboundedR(_) | Range::UnboundedL(_) | Range::Unbounded => {
                return Err(RuleNotApplicable);
            }
        }
    }
153
    Ok(RuleEffect::pure(Expr::MinionWInIntervalSet(
153
        Metadata::new(),
153
        atom.clone(),
153
        out_ranges,
153
    )))
5719
}
/// Converts `[....][i]` to `element_one` if:
///
/// 1. the subject is a list literal
/// 2. the subject is one dimensional
#[register_rule(
    "Minion",
    4400,
    [Eq / SafeIndex, AuxDeclaration / SafeIndex, SafeIndex]
)]
26738
fn introduce_element_from_index(expr: &Expr, symtab: &SymbolTable) -> ApplicationResult {
26738
    let (equalto, subject, indices) = match expr.clone() {
8898
        Expr::Eq(_, e1, e2) => match (Moo::unwrap_or_clone(e1), Moo::unwrap_or_clone(e2)) {
            (Expr::Atomic(_, eq), Expr::SafeIndex(_, subject, indices)) => {
27
                Ok((eq, subject, indices))
            }
            (Expr::SafeIndex(_, subject, indices), Expr::Atomic(_, eq)) => {
6903
                Ok((eq, subject, indices))
            }
1968
            _ => Err(RuleNotApplicable),
        },
2481
        Expr::AuxDeclaration(_, reference, expr) => match Moo::unwrap_or_clone(expr) {
            Expr::SafeIndex(_, subject, indices) => {
2313
                Ok((Atom::Reference(reference), subject, indices))
            }
168
            _ => Err(RuleNotApplicable),
        },
10120
        Expr::SafeIndex(_, subject, indices) if expr.return_type() == ReturnType::Bool => {
1786
            Ok((Atom::Literal(Lit::Bool(true)), subject, indices))
        }
13573
        _ => Err(RuleNotApplicable),
15709
    }?;
11029
    if indices.len() != 1 {
        return Err(RuleNotApplicable);
11029
    }
    // Minion's `element` is 1-based. A list already is, so it needs no shift; any other contiguous
    // integer index domain does, which is why this rule used to decline for e.g.
    // `[10,20,30,40; int(0..3)][i]`.
11029
    let subject = Moo::unwrap_or_clone(subject);
11029
    let mut symtab = symtab.clone();
11029
    let mut top_level_exprs = vec![];
11029
    let (list, index) = match subject.clone().into_list() {
        Some(list) => {
10705
            let Expr::Atomic(_, index) = indices[0].clone() else {
4131
                return Err(RuleNotApplicable);
            };
6574
            (list, index)
        }
        None => {
324
            let Some((list, index_domain)) = subject.unwrap_matrix_unchecked() else {
                return Err(RuleNotApplicable);
            };
324
            let offset = offset_to_one_based(&index_domain, list.len()).ok_or(RuleNotApplicable)?;
324
            if offset == 0 {
                // Already 1-based; use the index as it stands rather than minting an auxiliary
                // for `index + 0`.
279
                let Expr::Atomic(_, index) = indices[0].clone() else {
                    return Err(RuleNotApplicable);
                };
279
                (list, index)
            } else {
45
                let index_expr = Expr::Sum(
45
                    Metadata::new(),
45
                    Moo::new(into_matrix_expr![vec![
45
                        indices[0].clone(),
45
                        Expr::Atomic(Metadata::new(), Atom::Literal(Lit::Int(offset))),
45
                    ]]),
45
                );
                let index =
45
                    flatten_expression_to_atom(index_expr, &mut symtab, &mut top_level_exprs)?;
45
                (list, index)
            }
        }
    };
6898
    let mut atom_list = vec![];
6898
    for elem in list {
163394
        let Expr::Atomic(_, elem) = elem else {
81
            return Err(RuleNotApplicable);
        };
163313
        atom_list.push(elem);
    }
6817
    Ok(RuleEffect::new(
6817
        Expr::MinionElementOne(
6817
            Metadata::new(),
6817
            atom_list,
6817
            Moo::new(index),
6817
            Moo::new(equalto),
6817
        ),
6817
        top_level_exprs,
6817
        symtab,
6817
    ))
26738
}
/// How much to add to an Essence index to reach Minion's 1-based `element` position.
///
/// `None` when the index domain is not a contiguous integer range covering exactly the elements,
/// in which case the caller has no straightforward shift to apply.
324
fn offset_to_one_based(index_domain: &DomainPtr, elements: usize) -> Option<i32> {
324
    let resolved = index_domain.resolve().ok()?;
324
    let GroundDomain::Int(ranges, _) = resolved.as_ref() else {
        return None;
    };
324
    if !Range::is_contiguous(ranges) {
        return None;
324
    }
324
    let low = Range::low_of(ranges)?;
324
    let values = Range::values(ranges)?.count();
324
    (values == elements).then_some(1 - low)
324
}
/// Flattens an implication.
///
/// ```text
/// e -> y  (where e is non atomic)
///  ~~>
/// __0 -> y,
///
/// with new top level constraints
/// __0 =aux x
///
/// ```
///
/// Unlike other expressions, only the left hand side of implications are flattened. This is
/// because implications can be expressed as a `reifyimply` constraint, which takes a constraint as
/// an argument:
///
/// ``` text
/// r -> c ~> refifyimply(r,c)
///  where r is an atom, c is a constraint
/// ```
///
/// See [`introduce_reifyimply_ineq_from_imply`].
#[register_rule("Minion", 4200, [Imply])]
23374
fn flatten_imply(expr: &Expr, _symbols: &SymbolTable) -> ApplicationResult {
23374
    let Expr::Imply(meta, x, y) = expr else {
3115
        return Err(RuleNotApplicable);
    };
    // flatten x
20259
    defer_aux_var(x.as_ref(), {
20259
        let meta = meta.clone();
20259
        let y = y.clone();
20247
        move |aux_var_info| {
20247
            RuleEffect::new(
20247
                Expr::Imply(meta.clone(), Moo::new(aux_var_info.as_expr()), y.clone()),
20247
                vec![aux_var_info.top_level_expr()],
20247
                aux_var_info.symbols(),
20247
            )
20247
        }
    })
20259
    .ok_or(RuleNotApplicable)
23374
}
#[register_rule("Minion", 4200, [SafeDiv, Neq, SafeMod, SafePow, Leq, Geq, Abs, Neg, Not, SafeIndex, InDomain, ToInt])]
498810
fn flatten_generic(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
498810
    if !matches!(
498810
        expr,
498810
        Expr::SafeDiv(_, _, _)
498810
            | Expr::Neq(_, _, _)
498810
            | Expr::SafeMod(_, _, _)
498810
            | Expr::SafePow(_, _, _)
498810
            | Expr::Leq(_, _, _)
498810
            | Expr::Geq(_, _, _)
498810
            | Expr::Abs(_, _)
498810
            | Expr::Neg(_, _)
498810
            | Expr::Not(_, _)
498810
            | Expr::SafeIndex(_, _, _)
498810
            | Expr::InDomain(_, _, _)
498810
            | Expr::ToInt(_, _)
498810
    ) {
2803
        return Err(RuleNotApplicable);
496007
    }
    // Cloning the model-wide symbol table costs a clone per declaration, and most calls reach
    // this rule with already-atomic children. Decide applicability from the child domains
    // first, and hand those domains to the rewrite so they are only derived once.
    let (expr, new_tops, symbols) =
496007
        flatten_children_to_aux_vars(expr, symbols, |needs_aux, _| needs_aux > 0)
496007
            .ok_or(RuleNotApplicable)?;
110169
    Ok(RuleEffect::new(expr, new_tops, symbols))
498810
}
#[register_rule("Minion", 4200, [Eq])]
49106
fn flatten_eq(expr: &Expr, symbols: &SymbolTable) -> ApplicationResult {
49106
    if !matches!(expr, Expr::Eq(_, _, _)) {
3067
        return Err(RuleNotApplicable);
46039
    }
    // eq: both sides have to be non flat for the rule to be applicable. Deciding that from the
    // child domains keeps the symbol-table clone off the failure path.
    let (expr, new_tops, symbols) =
46039
        flatten_children_to_aux_vars(expr, symbols, |needs_aux, num_children| {
46039
            num_children == 2 && needs_aux == 2
46039
        })
46039
        .ok_or(RuleNotApplicable)?;
1623
    Ok(RuleEffect::new(expr, new_tops, symbols))
49106
}
/// Flattens products containing lists.
///
/// For example,
///
/// ```plain
/// product([|x|,y,z]) ~~> product([aux1,y,z]), aux1=|x|
/// ```
#[register_rule("Minion", 4200, [Product])]
3376
fn flatten_product(expr: &Expr, symtab: &SymbolTable) -> ApplicationResult {
    // product cannot use flatten_generic as we don't want to put the immediate child in an aux
    // var, as that is the matrix literal. Instead we want to put the children of the matrix
    // literal in an aux var.
    //
    // e.g.
    //
    // flatten_generic would do
    //
    // product([|x|,y,z]) ~~> product(aux1), aux1=[x,y,z]
    //
    // we want to do
    //
    // product([|x|,y,z]) ~~> product([aux1,y,z]), aux1=|x|
    //
    // We only want to flatten products containing matrix literals that are lists but not child terms, e.g.
    //
    //  product(x[1,..]) ~~> product(aux1),aux1 = x[1,..].
    //
    //  Instead, we let the representation and vertical rules for matrices turn x[1,..] into a
    //  matrix literal.
    //
    //  product(x[1,..]) ~~ slice_matrix_components ~~> product([x11,x12,x13,x14])
3376
    let Expr::Product(_, factors) = expr else {
3139
        return Err(RuleNotApplicable);
    };
237
    let factors = (**factors).clone().into_list().ok_or(RuleNotApplicable)?;
237
    let mut new_factors = vec![];
237
    let mut top_level_exprs = vec![];
237
    let mut symtab = symtab.clone();
237
    let mut changed = false;
237
    for factor in factors {
        // Already-flat atoms are left alone. Non-atoms (including toInt(bool),
        // which Minion treats as the bool atom itself) must be rewritten.
474
        let was_atomic = matches!(&factor, Expr::Atomic(_, _));
474
        let atom = flatten_expression_to_atom(factor, &mut symtab, &mut top_level_exprs)?;
474
        if !was_atomic {
177
            changed = true;
297
        }
474
        new_factors.push(Expr::Atomic(Metadata::new(), atom));
    }
    // have we done anything?
    // Aux-vars add top-level declarations; stripping toInt(bool) → bool atom
    // rewrites factors without creating auxes, so also count that as progress.
237
    if !changed && top_level_exprs.is_empty() {
144
        return Err(RuleNotApplicable);
93
    }
93
    let new_expr = Expr::Product(Metadata::new(), Moo::new(into_matrix_expr![new_factors]));
93
    Ok(RuleEffect::new(new_expr, top_level_exprs, symtab))
3376
}
/// Flattens a matrix literal that contains expressions.
///
/// For example,
///
/// ```plain
/// [1,e/2,f*5] ~~> [1,__0,__1],
///
/// where
/// __0 =aux e/2,
/// __1 =aux f*5
/// ```
// Match parents of matrix values whether they appear as `AbstractLiteral`
// nodes or as `Atomic` literals wrapping a matrix.
#[register_rule("Minion", 1000, [* / AbstractLiteral, * / Atomic])] // lower than matrix_to_list
406994
fn flatten_matrix_literal(expr: &Expr, symtab: &SymbolTable) -> ApplicationResult {
    // do not flatten matrix literals inside sum, or, and, product as these expressions either do
    // their own flattening, or do not need flat expressions.
406994
    if matches!(
406994
        expr,
        Expr::And(_, _) | Expr::Or(_, _) | Expr::Sum(_, _) | Expr::Product(_, _)
    ) {
218795
        return Err(RuleNotApplicable);
188199
    }
188199
    let mut symbols = symtab.clone();
188199
    let mut top_level_exprs = vec![];
    // flatten any children that are matrix literals
474310
    let (expr, num_changed) = rewrite_children(expr, |child| {
        // is this a matrix literal?
        //
        // as we arn't changing the number of arguments in the matrix, we can apply this to all
        // matrices, not just those that are lists.
        //
        // this also means that this rule works with n-d matrices -- the inner dimensions of n-d
        // matrices cant be turned into lists, as described the docstring for matrix_to_list.
474310
        let Some((mut es, index_domain)) = child.clone().unwrap_matrix_unchecked() else {
473410
            return (child, false);
        };
900
        let mut child_changed = false;
        // flatten expressions
900
        for e in es.iter_mut() {
4896
            if let Some((reference, top)) = to_aux_var_in(e, &mut symbols) {
198
                *e = Expr::Atomic(Metadata::new(), Atom::Reference(reference));
198
                top_level_exprs.push(top);
198
                child_changed = true;
4698
            } else if let Expr::SafeIndex(_, subject, indices) = e {
                let index_has_index_of = indices
                    .iter()
                    .any(|index| matches!(index, Expr::IndexOf(..)));
                let subject_is_ref = matches!(**subject, Expr::Atomic(_, Atom::Reference(_)));
                if !index_has_index_of && subject_is_ref {
                    continue;
                }
                // we dont normally flatten indexing expressions, but we want to do it if they are
                // inside a matrix list.
                //
                // remove_dimension_from_matrix_indexing turns [[1,2,3],[4,5,6]][i,j]
                // into [[1,2,3][j],[4,5,6][j],[7,8,9][j]][i].
                //
                // we want to flatten this to
                // [__0,__1,__2][i]
                let Some(domain) = e.domain_of() else {
                    continue;
                };
                let categories = e.universe_categories();
                // must contain a decision variable
                if !categories.contains(&Category::Decision) {
                    continue;
                }
                // must not contain givens or quantified variables
                if categories.contains(&Category::Parameter)
                    || categories.contains(&Category::Quantified)
                {
                    continue;
                }
                let decl = symbols.gen_find_auxiliary(&domain);
                top_level_exprs.push(Expr::AuxDeclaration(
                    Metadata::new(),
                    Reference::new(decl.clone()),
                    Moo::new(e.clone()),
                ));
                *e = Expr::Atomic(Metadata::new(), Atom::Reference(Reference::new(decl)));
                child_changed = true;
4698
            }
        }
900
        (into_matrix_expr!(es;index_domain), child_changed)
474310
    });
188199
    if num_changed != 0 {
90
        Ok(RuleEffect::new(expr, top_level_exprs, symbols))
    } else {
188109
        Err(RuleNotApplicable)
    }
406994
}
/// Converts a Geq to an Ineq
///
/// ```text
/// x >= y ~> y <= x + 0 ~> ineq(y,x,0)
/// ```
#[register_rule("Minion", 4100, [Geq])]
43434
fn geq_to_ineq(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
43434
    let Expr::Geq(meta, e1, e2) = expr.clone() else {
2431
        return Err(RuleNotApplicable);
    };
41003
    let Expr::Atomic(_, x) = Moo::unwrap_or_clone(e1) else {
        return Err(RuleNotApplicable);
    };
41003
    let Expr::Atomic(_, y) = Moo::unwrap_or_clone(e2) else {
        return Err(RuleNotApplicable);
    };
41003
    Ok(RuleEffect::pure(Expr::FlatIneq(
41003
        meta,
41003
        Moo::new(y),
41003
        Moo::new(x),
41003
        Box::new(Lit::Int(0)),
41003
    )))
43434
}
/// Converts a Leq to an Ineq
///
/// ```text
/// x <= y ~> x <= y + 0 ~> ineq(x,y,0)
/// ```
#[register_rule("Minion", 4100, [Leq])]
116076
fn leq_to_ineq(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
116076
    let Expr::Leq(meta, e1, e2) = expr.clone() else {
2407
        return Err(RuleNotApplicable);
    };
113669
    let Expr::Atomic(_, x) = Moo::unwrap_or_clone(e1) else {
144
        return Err(RuleNotApplicable);
    };
113525
    let Expr::Atomic(_, y) = Moo::unwrap_or_clone(e2) else {
        return Err(RuleNotApplicable);
    };
113525
    Ok(RuleEffect::pure(Expr::FlatIneq(
113525
        meta,
113525
        Moo::new(x),
113525
        Moo::new(y),
113525
        Box::new(Lit::Int(0)),
113525
    )))
116076
}
// TODO: add this rule for geq
/// ```text
/// x <= y + k ~> ineq(x,y,k)
/// ```
#[register_rule("Minion", 4500, [Leq])]
341755
fn x_leq_y_plus_k_to_ineq(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
341755
    let Expr::Leq(meta, e1, e2) = expr.clone() else {
5839
        return Err(RuleNotApplicable);
    };
335916
    let Expr::Atomic(_, x) = Moo::unwrap_or_clone(e1) else {
558
        return Err(RuleNotApplicable);
    };
335358
    let Expr::Sum(_, sum_exprs) = Moo::unwrap_or_clone(e2) else {
335341
        return Err(RuleNotApplicable);
    };
17
    let sum_exprs = (*sum_exprs).clone().into_list().ok_or(RuleNotApplicable)?;
9
    let (y, k) = match sum_exprs.as_slice() {
9
        [Expr::Atomic(_, y), Expr::Atomic(_, Atom::Literal(k))] => (y, k),
        [Expr::Atomic(_, Atom::Literal(k)), Expr::Atomic(_, y)] => (y, k),
        _ => {
            return Err(RuleNotApplicable);
        }
    };
9
    Ok(RuleEffect::pure(Expr::FlatIneq(
9
        meta,
9
        Moo::new(x),
9
        Moo::new(y.clone()),
9
        Box::new(k.clone()),
9
    )))
341755
}
/// ```text
/// y + k >= x ~> ineq(x,y,k)
/// ```
#[register_rule("Minion", 4800, [Geq])]
54629
fn y_plus_k_geq_x_to_ineq(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
    // impl same as x_leq_y_plus_k but with lhs and rhs flipped
54629
    let Expr::Geq(meta, e2, e1) = expr.clone() else {
6730
        return Err(RuleNotApplicable);
    };
47899
    let Expr::Atomic(_, x) = Moo::unwrap_or_clone(e1) else {
972
        return Err(RuleNotApplicable);
    };
46927
    let Expr::Sum(_, sum_exprs) = Moo::unwrap_or_clone(e2) else {
41588
        return Err(RuleNotApplicable);
    };
5339
    let sum_exprs = Moo::unwrap_or_clone(sum_exprs)
5339
        .into_list()
5339
        .ok_or(RuleNotApplicable)?;
5150
    let (y, k) = match sum_exprs.as_slice() {
3610
        [Expr::Atomic(_, y), Expr::Atomic(_, Atom::Literal(k))] => (y, k),
9
        [Expr::Atomic(_, Atom::Literal(k)), Expr::Atomic(_, y)] => (y, k),
        _ => {
1531
            return Err(RuleNotApplicable);
        }
    };
3619
    Ok(RuleEffect::pure(Expr::FlatIneq(
3619
        meta,
3619
        Moo::new(x),
3619
        Moo::new(y.clone()),
3619
        Box::new(k.clone()),
3619
    )))
54629
}
/// Flattening rule for not(bool_lit)
///
/// For some boolean variable x:
/// ```text
///  not(x)      ~>  w-literal(x,0)
/// ```
///
/// ## Rationale
///
/// Minion's watched-and and watched-or constraints only takes other constraints as arguments.
///
/// This restates boolean variables as the equivalent constraint "SAT if x is true".
///
/// The regular bool_lit case is dealt with directly by the Minion solver interface (as it is a
/// trivial match).
#[register_rule("Minion", 4100, [Not])]
67729
fn not_literal_to_wliteral(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
67729
    match expr {
        Expr::Not(m, expr) => {
65298
            if let Expr::Atomic(_, Atom::Reference(reference)) = (**expr).clone()
65298
                && reference.ptr().domain().is_some_and(|d| d.is_bool())
            {
65298
                return Ok(RuleEffect::pure(Expr::FlatWatchedLiteral(
65298
                    m.clone(),
65298
                    reference,
65298
                    Lit::Bool(false),
65298
                )));
            }
            Err(RuleNotApplicable)
        }
2431
        _ => Err(RuleNotApplicable),
    }
67729
}
/// Flattening rule for not(X) in Minion, where X is a constraint.
///
/// ```text
/// not(X) ~> reify(X,0)
/// ```
///
/// This rule has lower priority than boolean_literal_to_wliteral so that we can assume that the
/// nested expressions are constraints not variables.
#[register_rule("Minion", 4090, [Not])]
1819
fn not_constraint_to_reify(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
1819
    if !matches!(expr, Expr::Not(_,c) if !matches!(**c, Expr::Atomic(_,_))) {
1819
        return Err(RuleNotApplicable);
    }
    let Expr::Not(m, e) = expr else {
        unreachable!();
    };
    extra_check! {
        if !is_flat(e) {
            return Err(RuleNotApplicable);
        }
    };
    Ok(RuleEffect::pure(Expr::MinionReify(
        m.clone(),
        e.clone(),
        Atom::Literal(Lit::Bool(false)),
    )))
1819
}
/// Converts an equality between a decision variable and a constant into `w-literal`.
///
/// ```text
/// x = k  ~>  w-literal(x, k)
/// k = x  ~>  w-literal(x, k)
/// ```
///
/// SavileRow posts forced assignments this way. Minion's `eq(x,k)` is valid, but
/// `w-literal` is the watched form used for domain assignments and propagates
/// more cleanly alongside other watched constraints.
#[register_rule("Minion", 4400, [Eq])]
205856
fn eq_atom_literal_to_wliteral(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
205856
    let Expr::Eq(m, a, b) = expr else {
5407
        return Err(RuleNotApplicable);
    };
200449
    let (reference, lit) = match (a.as_ref(), b.as_ref()) {
        (Expr::Atomic(_, Atom::Reference(reference)), Expr::Atomic(_, Atom::Literal(lit))) => {
136269
            (reference, lit)
        }
        (Expr::Atomic(_, Atom::Literal(lit)), Expr::Atomic(_, Atom::Reference(reference))) => {
2034
            (reference, lit)
        }
62146
        _ => return Err(RuleNotApplicable),
    };
138303
    Ok(RuleEffect::pure(Expr::FlatWatchedLiteral(
138303
        m.clone(),
138303
        reference.clone(),
138303
        lit.clone(),
138303
    )))
205856
}
/// Converts an equality to a boolean constraint into a `reify` constraint.
///
/// ```text
/// x =aux c ~> reify(c,x)
/// x = c ~> reify(c,x)
///
/// where c is a non-atomic boolean constraint
/// ```
///
/// Atomic equalities such as `x = false` or `x = y` are left alone: Minion can emit `eq`
/// directly, and turning `x = false` into `reify(false, x)` embeds a posted constraint form
/// as a Boolean subexpression (for example as the LHS of `Imply`), which neither
/// [`flatten_imply`] nor [`introduce_reifyimply_ineq_from_imply`] can lower.
#[register_rule("Minion", 4400, [AuxDeclaration, Eq])]
386481
fn bool_eq_to_reify(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
386481
    let (atom, e): (Atom, Moo<Expr>) = match expr {
180791
        Expr::AuxDeclaration(_, reference, e) => Ok((Atom::from(reference.clone()), e.clone())),
200451
        Expr::Eq(_, a, b) => match (a.as_ref(), b.as_ref()) {
144446
            (Expr::Atomic(_, atom), _) => Ok((atom.clone(), b.clone())),
52487
            (_, Expr::Atomic(_, atom)) => Ok((atom.clone(), a.clone())),
3518
            _ => Err(RuleNotApplicable),
        },
5239
        _ => Err(RuleNotApplicable),
8757
    }?;
    // Reify targets a constraint, not another atom. Atomic Bool equalities stay as `eq`.
377724
    if matches!(e.as_ref(), Expr::Atomic(_, _)) {
143836
        return Err(RuleNotApplicable);
233888
    }
    // e does not have to be valid minion constraint yet, as long as we know it can turn into one
    // (i.e. it is boolean).
233888
    if e.as_ref().return_type() != ReturnType::Bool {
157231
        return Err(RuleNotApplicable);
76657
    };
76657
    Ok(RuleEffect::pure(Expr::MinionReify(
76657
        Metadata::new(),
76657
        e,
76657
        atom,
76657
    )))
386481
}
/// Converts an iff into Minion form in one step.
///
/// ```text
/// Iff(x, c) ~> reify(c, x)     when x is atomic and c is a non-atomic Bool
/// Iff(a, b) ~> Eq(a, b)        otherwise (including atomic Bool equalities)
/// ```
///
/// Going via `Iff ~> Eq ~> reify` used two successful rewrites (and two dirty
/// cascades) for every ship-linkage constraint on models like
/// solitaire_battleship. Fusing the common case removes that intermediate pass.
#[register_rule("Minion", 4400, [Iff])]
7204
fn iff_to_eq(expr: &Expr, _: &SymbolTable) -> ApplicationResult {
7204
    let Expr::Iff(_, x, y) = expr else {
5539
        return Err(RuleNotApplicable);
    };
1665
    match (x.as_ref(), y.as_ref()) {
900
        (Expr::Atomic(_, atom), other) if !matches!(other, Expr::Atomic(_, _)) => {
855
            if other.return_type() != ReturnType::Bool {
                return Err(RuleNotApplicable);
855
            }
855
            Ok(RuleEffect::pure(Expr::MinionReify(
855
                Metadata::new(),
855
                y.clone(),
855
                atom.clone(),
855
            )))
        }
225
        (other, Expr::Atomic(_, atom)) if !matches!(other, Expr::Atomic(_, _)) => {
180
            if other.return_type() != ReturnType::Bool {
                return Err(RuleNotApplicable);
180
            }
180
            Ok(RuleEffect::pure(Expr::MinionReify(
180
                Metadata::new(),
180
                x.clone(),
180
                atom.clone(),
180
            )))
        }
630
        _ => Ok(RuleEffect::pure(Expr::Eq(
630
            Metadata::new(),
630
            x.clone(),
630
            y.clone(),
630
        ))),
    }
7204
}
#[cfg(test)]
mod tests {
    use super::*;
    use conjure_cp::ast::{DeclarationPtr, Domain};
    use conjure_cp::matrix_expr;
    use conjure_cp::rule_engine::{ApplicationError, get_rule_by_name};
    /// Builds a boolean decision-variable atomic expression.
10
    fn bool_atom(name: &str) -> Expr {
10
        Expr::Atomic(
10
            Metadata::new(),
10
            Atom::Reference(Reference::new(DeclarationPtr::new_find(
10
                Name::user(name),
10
                Domain::bool(),
10
            ))),
10
        )
10
    }
    /// Builds an integer decision-variable atomic expression.
10
    fn int_atom(name: &str) -> Expr {
10
        Expr::Atomic(
10
            Metadata::new(),
10
            Atom::Reference(Reference::new(DeclarationPtr::new_find(
10
                Name::user(name),
10
                Domain::int(vec![Range::Bounded(1, 5)]),
10
            ))),
10
        )
10
    }
    /// Atomic Boolean literal.
2
    fn bool_lit(value: bool) -> Expr {
2
        Expr::Atomic(Metadata::new(), Atom::Literal(Lit::Bool(value)))
2
    }
    #[test]
1
    fn introduce_lee_distance_atom_lowers_min_abs_complement() {
1
        let a = int_atom("a");
1
        let b = int_atom("b");
1
        let diff = Expr::Minus(Metadata::new(), Moo::new(a), Moo::new(b));
1
        let abs_arm = Expr::Abs(Metadata::new(), Moo::new(diff.clone()));
1
        let complement = Expr::Minus(
1
            Metadata::new(),
1
            Moo::new(Expr::Atomic(Metadata::new(), Atom::Literal(Lit::Int(4)))),
1
            Moo::new(Expr::Abs(Metadata::new(), Moo::new(diff))),
1
        );
1
        let expr = Expr::Min(Metadata::new(), Moo::new(matrix_expr![abs_arm, complement]));
1
        let rule = get_rule_by_name("introduce_lee_distance_atom").expect("rule registered");
1
        let result = rule
1
            .apply(&expr, &SymbolTable::new())
1
            .expect("Lee atom should lower in one step");
1
        assert!(
1
            matches!(result.new_expression, Expr::Atomic(_, _)),
            "Lee min must become an auxiliary atom"
        );
1
        assert!(
1
            result
1
                .new_top
1
                .iter()
3
                .any(|c| matches!(c, Expr::FlatAbsEq(_, _, _))),
            "must post FlatAbsEq for the shared absolute value"
        );
1
        assert!(
1
            result
1
                .new_top
1
                .iter()
6
                .any(|c| matches!(c, Expr::FlatMinEq(_, vars, _) if vars.len() == 2)),
            "must post FlatMinEq over abs and complement"
        );
1
        assert!(
1
            result
1
                .new_top
1
                .iter()
6
                .filter(|c| matches!(c, Expr::FlatSumLeq(_, vars, _) if vars.len() == 2))
                .count()
1
                == 1
1
                && result
1
                    .new_top
1
                    .iter()
6
                    .filter(|c| matches!(c, Expr::FlatSumGeq(_, vars, _) if vars.len() == 2))
                    .count()
1
                    == 1,
            "must channel abs + complement = alphabet size"
        );
1
        assert!(
1
            result.new_top.iter().any(|c| {
1
                matches!(
1
                    c,
                    Expr::FlatWeightedSumLeq(_, coeffs, vars, _)
                        | Expr::FlatWeightedSumGeq(_, coeffs, vars, _)
1
                        if coeffs.len() == 2 && vars.len() == 2
                )
1
            }),
            "atomic minus should channel through a weighted sum"
        );
1
    }
    #[test]
1
    fn introduce_lee_distance_atom_accepts_sum_complement_form() {
1
        let a = int_atom("a");
1
        let b = int_atom("b");
1
        let diff = Expr::Minus(Metadata::new(), Moo::new(a), Moo::new(b));
1
        let abs_arm = Expr::Abs(Metadata::new(), Moo::new(diff.clone()));
1
        let complement = Expr::Sum(
1
            Metadata::new(),
1
            Moo::new(matrix_expr![
1
                Expr::Atomic(Metadata::new(), Atom::Literal(Lit::Int(4))),
1
                Expr::Neg(
1
                    Metadata::new(),
1
                    Moo::new(Expr::Abs(Metadata::new(), Moo::new(diff))),
1
                ),
1
            ]),
1
        );
1
        let expr = Expr::Min(Metadata::new(), Moo::new(matrix_expr![abs_arm, complement]));
1
        let rule = get_rule_by_name("introduce_lee_distance_atom").expect("rule registered");
1
        rule.apply(&expr, &SymbolTable::new())
1
            .expect("sum-form Lee complement should also match");
1
    }
    #[test]
1
    fn introduce_lee_distance_atom_rejects_unrelated_min() {
1
        let expr = Expr::Min(
1
            Metadata::new(),
1
            Moo::new(matrix_expr![int_atom("a"), int_atom("b")]),
1
        );
1
        let rule = get_rule_by_name("introduce_lee_distance_atom").expect("rule registered");
1
        let err = rule.apply(&expr, &SymbolTable::new()).unwrap_err();
1
        assert!(matches!(err, ApplicationError::RuleNotApplicable));
1
    }
    #[test]
1
    fn introduce_mineq_from_min_emits_flat_min_eq() {
1
        let expr = Expr::Min(
1
            Metadata::new(),
1
            Moo::new(matrix_expr![int_atom("a"), int_atom("b")]),
1
        );
1
        let rule = get_rule_by_name("introduce_mineq_from_min").expect("rule registered");
1
        let result = rule
1
            .apply(&expr, &SymbolTable::new())
1
            .expect("min of atoms should lower to FlatMinEq");
1
        assert!(
1
            matches!(result.new_expression, Expr::Atomic(_, _)),
            "bare min must become an auxiliary atom"
        );
1
        assert!(
1
            result
1
                .new_top
1
                .iter()
1
                .any(|c| matches!(c, Expr::FlatMinEq(_, vars, _) if vars.len() == 2)),
            "must post FlatMinEq over the two atoms"
        );
1
    }
    #[test]
1
    fn introduce_mineq_from_aux_declaration() {
        let result_decl =
1
            DeclarationPtr::new_find(Name::user("r"), Domain::int(vec![Range::Bounded(1, 5)]));
1
        let expr = Expr::AuxDeclaration(
1
            Metadata::new(),
1
            Reference::new(result_decl.clone()),
1
            Moo::new(Expr::Min(
1
                Metadata::new(),
1
                Moo::new(matrix_expr![int_atom("a"), int_atom("b")]),
1
            )),
1
        );
1
        let rule = get_rule_by_name("introduce_mineq").expect("rule registered");
1
        let result = rule
1
            .apply(&expr, &SymbolTable::new())
1
            .expect("aux = min([...]) should become FlatMinEq");
1
        assert!(
1
            matches!(result.new_expression, Expr::FlatMinEq(_, vars, _) if vars.len() == 2),
            "auxiliary min must lower to FlatMinEq"
        );
1
    }
    #[test]
1
    fn introduce_weighted_sum_uses_bool_atom_without_to_int_aux() {
1
        let bool_var = bool_atom("b");
1
        let to_int = Expr::ToInt(Metadata::new(), Moo::new(bool_var.clone()));
1
        let expr = Expr::Eq(
1
            Metadata::new(),
1
            Moo::new(Expr::Sum(Metadata::new(), Moo::new(matrix_expr![to_int]))),
1
            Moo::new(Expr::Atomic(Metadata::new(), Atom::Literal(Lit::Int(1)))),
1
        );
1
        let rule = get_rule_by_name("introduce_weighted_sumleq_sumgeq").expect("rule registered");
1
        let result = rule
1
            .apply(&expr, &SymbolTable::new())
1
            .expect("sum of toInt(bool) should lower");
1
        assert!(
1
            result.new_top.is_empty(),
            "toInt(bool atom) must not create aux vars; got {:?}",
            result.new_top
        );
1
        match &result.new_expression {
            Expr::And(_, matrix) => {
1
                let list = matrix.as_ref().clone().unwrap_list().expect("and list");
1
                assert!(
1
                    list.iter().any(|c| matches!(
1
                        c,
                        Expr::FlatSumLeq(_, vars, _) | Expr::FlatSumGeq(_, vars, _)
                        if vars.len() == 1
                    )),
                    "expected FlatSum over the bool atom, got {:?}",
                    result.new_expression
                );
            }
            other => panic!("expected and of sumleq/sumgeq, got {other:?}"),
        }
1
    }
    #[test]
1
    fn introduce_weighted_sum_lowers_product_of_to_int_bools() {
        // bibd/opd: sum([product([toInt(a), toInt(b)]), ...]) <= k
        // Stripping toInt(bool) must not prevent FlatProductEq aux domain inference.
1
        let a = Expr::ToInt(Metadata::new(), Moo::new(bool_atom("a")));
1
        let b = Expr::ToInt(Metadata::new(), Moo::new(bool_atom("b")));
1
        let product = Expr::Product(Metadata::new(), Moo::new(matrix_expr![a, b]));
1
        let expr = Expr::Leq(
1
            Metadata::new(),
1
            Moo::new(Expr::Sum(Metadata::new(), Moo::new(matrix_expr![product]))),
1
            Moo::new(Expr::Atomic(Metadata::new(), Atom::Literal(Lit::Int(1)))),
1
        );
1
        let rule = get_rule_by_name("introduce_weighted_sumleq_sumgeq").expect("rule registered");
1
        let result = rule
1
            .apply(&expr, &SymbolTable::new())
1
            .expect("sum of product(toInt(bool), toInt(bool)) should lower");
1
        assert!(
1
            matches!(result.new_expression, Expr::FlatSumLeq(_, ref vars, _) if vars.len() == 1),
            "expected FlatSumLeq over product aux, got {:?}",
            result.new_expression
        );
1
        assert!(
1
            result
1
                .new_top
1
                .iter()
1
                .any(|c| matches!(c, Expr::FlatProductEq(_, _, _, _))),
            "must post FlatProductEq over the bool atoms; got {:?}",
            result.new_top
        );
1
        assert!(
1
            !result
1
                .new_top
1
                .iter()
1
                .any(|c| matches!(c, Expr::AuxDeclaration(_, _, e) if matches!(e.as_ref(), Expr::ToInt(_, _)))),
            "toInt(bool) factors must not create toInt aux vars; got {:?}",
            result.new_top
        );
1
    }
    #[test]
1
    fn eq_atom_literal_to_wliteral_lowers_forced_assignment() {
1
        let expr = Expr::Eq(
1
            Metadata::new(),
1
            Moo::new(bool_atom("x")),
1
            Moo::new(bool_lit(false)),
1
        );
1
        let rule = get_rule_by_name("eq_atom_literal_to_wliteral").expect("rule registered");
1
        let result = rule
1
            .apply(&expr, &SymbolTable::new())
1
            .expect("x = false should become w-literal");
1
        assert!(
1
            matches!(
1
                result.new_expression,
                Expr::FlatWatchedLiteral(_, _, Lit::Bool(false))
            ),
            "expected FlatWatchedLiteral(x, false), got {:?}",
            result.new_expression
        );
1
    }
    #[test]
1
    fn bool_eq_to_reify_refuses_atomic_false_equality() {
1
        let expr = Expr::Eq(
1
            Metadata::new(),
1
            Moo::new(bool_atom("x")),
1
            Moo::new(bool_lit(false)),
1
        );
1
        let rule = get_rule_by_name("bool_eq_to_reify").expect("rule registered");
1
        let err = rule.apply(&expr, &SymbolTable::new()).unwrap_err();
1
        assert!(
1
            matches!(err, ApplicationError::RuleNotApplicable),
            "x = false must not become reify(false, x)"
        );
1
    }
    #[test]
1
    fn bool_eq_to_reify_refuses_atomic_variable_equality() {
1
        let expr = Expr::Eq(
1
            Metadata::new(),
1
            Moo::new(bool_atom("x")),
1
            Moo::new(bool_atom("y")),
1
        );
1
        let rule = get_rule_by_name("bool_eq_to_reify").expect("rule registered");
1
        let err = rule.apply(&expr, &SymbolTable::new()).unwrap_err();
1
        assert!(
1
            matches!(err, ApplicationError::RuleNotApplicable),
            "x = y must stay as eq, not reify"
        );
1
    }
    #[test]
1
    fn bool_eq_to_reify_still_applies_to_constraint_equality() {
1
        let constraint = Expr::And(
1
            Metadata::new(),
1
            Moo::new(matrix_expr![bool_atom("a"), bool_atom("b")]),
1
        );
1
        let expr = Expr::Eq(
1
            Metadata::new(),
1
            Moo::new(bool_atom("r")),
1
            Moo::new(constraint),
1
        );
1
        let rule = get_rule_by_name("bool_eq_to_reify").expect("rule registered");
1
        let result = rule
1
            .apply(&expr, &SymbolTable::new())
1
            .expect("r = and(a,b) should reify");
1
        assert!(
1
            matches!(result.new_expression, Expr::MinionReify(_, _, _)),
            "non-atomic Boolean equality must still become MinionReify"
        );
1
    }
    /// Builds a tuple literal expression `(a, b)`.
5
    fn tuple_lit(a: i32, b: bool) -> Expr {
5
        Expr::Atomic(
5
            Metadata::new(),
5
            Atom::Literal(Lit::AbstractLiteral(AbstractLiteral::Tuple(vec![
5
                Lit::Int(a),
5
                Lit::Bool(b),
5
            ]))),
5
        )
5
    }
    /// Builds `[e1,...,en; int(1..n)]` as an `Expr`, matching the shape
    /// `FunctionAsRelation`/`FunctionExplicit`'s own `image()` rules build for
    /// `domain_values_matrix`.
2
    fn one_based_matrix(elems: Vec<Expr>) -> Expr {
2
        let n = elems.len() as i32;
2
        into_matrix_expr![elems; Domain::int(vec![Range::Bounded(1, n)])]
2
    }
    #[test]
1
    fn fold_constant_index_of_to_index_finds_a_compound_literal() {
        // Regression: indexOf([(7,false),(7,true),(8,false),(8,true)], (8,true)) used to only
        // resolve for a plain int search value (`expr_int_literal` failing outright for a
        // compound one), leaving the IndexOf node -- and eventually the raw tuple literal --
        // unresolved all the way to Minion.
1
        let matrix = one_based_matrix(vec![
1
            tuple_lit(7, false),
1
            tuple_lit(7, true),
1
            tuple_lit(8, false),
1
            tuple_lit(8, true),
1
        ]);
1
        let index_of = Expr::IndexOf(
1
            Metadata::new(),
1
            Moo::new(matrix),
1
            Moo::new(tuple_lit(8, true)),
1
        );
1
        let folded = fold_constant_index_of_to_index(&index_of).expect("should fold");
1
        assert_eq!(folded, Expr::from(4));
1
    }
    #[test]
1
    fn fold_constant_index_of_to_index_still_finds_a_plain_int() {
        // The pre-existing scalar case must keep working once the lookup is generalised.
1
        let matrix = one_based_matrix(vec![Expr::from(10), Expr::from(20), Expr::from(30)]);
1
        let index_of = Expr::IndexOf(Metadata::new(), Moo::new(matrix), Moo::new(Expr::from(20)));
1
        let folded = fold_constant_index_of_to_index(&index_of).expect("should fold");
1
        assert_eq!(folded, Expr::from(2));
1
    }
}