1
use std::collections::{HashSet, VecDeque};
2
use std::fmt::{Display, Formatter};
3
use tracing::trace;
4

            
5
use conjure_cp_enum_compatibility_macro::document_compatibility;
6
use itertools::Itertools;
7
use serde::{Deserialize, Serialize};
8
use ustr::Ustr;
9

            
10
use polyquine::Quine;
11
use uniplate::{Biplate, Uniplate};
12

            
13
use crate::bug;
14

            
15
use super::abstract_comprehension::AbstractComprehension;
16
use super::ac_operators::ACOperatorKind;
17
use super::categories::{Category, CategoryOf};
18
use super::comprehension::Comprehension;
19
use super::domains::HasDomain as _;
20
use super::pretty::{pretty_expressions_as_top_level, pretty_vec};
21
use super::records::RecordValue;
22
use super::sat_encoding::SATIntEncoding;
23
use super::{
24
    AbstractLiteral, Atom, DeclarationPtr, Domain, DomainPtr, GroundDomain, IntVal, Literal,
25
    Metadata, Model, Moo, Name, Range, Reference, ReturnType, SetAttr, SymbolTable, SymbolTablePtr,
26
    Typeable, UnresolvedDomain, matrix,
27
};
28

            
29
// Ensure that this type doesn't get too big
30
//
31
// If you triggered this assertion, you either made a variant of this enum that is too big, or you
32
// made Name,Literal,AbstractLiteral,Atom bigger, which made this bigger! To fix this, put some
33
// stuff in boxes.
34
//
35
// Enums take the size of their largest variant, so an enum with mostly small variants and a few
36
// large ones wastes memory... A larger Expression type also slows down Oxide.
37
//
38
// For more information, and more details on type sizes and how to measure them, see the commit
39
// message for 6012de809 (perf: reduce size of AST types, 2025-06-18).
40
//
41
// You can also see type sizes in the rustdoc documentation, generated by ./tools/gen_docs.sh
42
//
43
// https://github.com/conjure-cp/conjure-oxide/commit/6012de8096ca491ded91ecec61352fdf4e994f2e
44

            
45
// TODO: box all usages of Metadata to bring this down a bit more - I have added variants to
46
// ReturnType, and Metadata contains ReturnType, so Metadata has got bigger. Metadata will get a
47
// lot bigger still when we start using it for memoisation, so it should really be
48
// boxed ~niklasdewally
49

            
50
// expect size of Expression to be 112 bytes
51
static_assertions::assert_eq_size!([u8; 104], Expression);
52

            
53
/// Represents different types of expressions used to define rules and constraints in the model.
54
///
55
/// The `Expression` enum includes operations, constants, and variable references
56
/// used to build rules and conditions for the model.
57
#[document_compatibility]
58
#[derive(Clone, Debug, Hash, PartialEq, Eq, Serialize, Deserialize, Uniplate, Quine)]
59
#[biplate(to=AbstractComprehension)]
60
#[biplate(to=AbstractLiteral<Expression>)]
61
#[biplate(to=AbstractLiteral<Literal>)]
62
#[biplate(to=Atom)]
63
#[biplate(to=Comprehension)]
64
#[biplate(to=DeclarationPtr)]
65
#[biplate(to=DomainPtr)]
66
#[biplate(to=Literal)]
67
#[biplate(to=Metadata)]
68
#[biplate(to=Name)]
69
#[biplate(to=Option<Expression>)]
70
#[biplate(to=RecordValue<Expression>)]
71
#[biplate(to=RecordValue<Literal>)]
72
#[biplate(to=Reference)]
73
#[biplate(to=Model)]
74
#[biplate(to=SymbolTable)]
75
#[biplate(to=SymbolTablePtr)]
76
#[biplate(to=Vec<Expression>)]
77
#[path_prefix(conjure_cp::ast)]
78
pub enum Expression {
79
    AbstractLiteral(Metadata, AbstractLiteral<Expression>),
80
    /// The top of the model
81
    Root(Metadata, Vec<Expression>),
82

            
83
    /// An expression representing "A is valid as long as B is true"
84
    /// Turns into a conjunction when it reaches a boolean context
85
    Bubble(Metadata, Moo<Expression>, Moo<Expression>),
86

            
87
    /// A comprehension.
88
    ///
89
    /// The inside of the comprehension opens a new scope.
90
    // todo (gskorokhod): Comprehension contains a symbol table which contains a bunch of pointers.
91
    // This makes implementing Quine tricky (it doesnt support Rc, by design). Skip it for now.
92
    #[polyquine_skip]
93
    Comprehension(Metadata, Moo<Comprehension>),
94

            
95
    /// Higher-level abstract comprehension
96
    #[polyquine_skip] // no idea what this is lol but it stops rustc screaming at me
97
    AbstractComprehension(Metadata, Moo<AbstractComprehension>),
98

            
99
    /// Defines dominance ("Solution A is preferred over Solution B")
100
    DominanceRelation(Metadata, Moo<Expression>),
101
    /// `fromSolution(name)` - Used in dominance relation definitions
102
    FromSolution(Metadata, Moo<Atom>),
103

            
104
    #[polyquine_with(arm = (_, name) => {
105
        let ident = proc_macro2::Ident::new(name.as_str(), proc_macro2::Span::call_site());
106
        quote::quote! { #ident.clone().into() }
107
    })]
108
    Metavar(Metadata, Ustr),
109

            
110
    Atomic(Metadata, Atom),
111

            
112
    /// A matrix index.
113
    ///
114
    /// Defined iff the indices are within their respective index domains.
115
    #[compatible(JsonInput)]
116
    UnsafeIndex(Metadata, Moo<Expression>, Vec<Expression>),
117

            
118
    /// A safe matrix index.
119
    ///
120
    /// See [`Expression::UnsafeIndex`]
121
    #[compatible(SMT)]
122
    SafeIndex(Metadata, Moo<Expression>, Vec<Expression>),
123

            
124
    /// A matrix slice: `a[indices]`.
125
    ///
126
    /// One of the indicies may be `None`, representing the dimension of the matrix we want to take
127
    /// a slice of. For example, for some 3d matrix a, `a[1,..,2]` has the indices
128
    /// `Some(1),None,Some(2)`.
129
    ///
130
    /// It is assumed that the slice only has one "wild-card" dimension and thus is 1 dimensional.
131
    ///
132
    /// Defined iff the defined indices are within their respective index domains.
133
    #[compatible(JsonInput)]
134
    UnsafeSlice(Metadata, Moo<Expression>, Vec<Option<Expression>>),
135

            
136
    /// A safe matrix slice: `a[indices]`.
137
    ///
138
    /// See [`Expression::UnsafeSlice`].
139
    SafeSlice(Metadata, Moo<Expression>, Vec<Option<Expression>>),
140

            
141
    /// `inDomain(x,domain)` iff `x` is in the domain `domain`.
142
    ///
143
    /// This cannot be constructed from Essence input, nor passed to a solver: this expression is
144
    /// mainly used during the conversion of `UnsafeIndex` and `UnsafeSlice` to `SafeIndex` and
145
    /// `SafeSlice` respectively.
146
    InDomain(Metadata, Moo<Expression>, DomainPtr),
147

            
148
    /// `toInt(b)` casts boolean expression b to an integer.
149
    ///
150
    /// - If b is false, then `toInt(b) == 0`
151
    ///
152
    /// - If b is true, then `toInt(b) == 1`
153
    #[compatible(SMT)]
154
    ToInt(Metadata, Moo<Expression>),
155

            
156
    /// `|x|` - absolute value of `x`
157
    #[compatible(JsonInput, SMT)]
158
    Abs(Metadata, Moo<Expression>),
159

            
160
    /// `sum(<vec_expr>)`
161
    #[compatible(JsonInput, SMT)]
162
    Sum(Metadata, Moo<Expression>),
163

            
164
    /// `a * b * c * ...`
165
    #[compatible(JsonInput, SMT)]
166
    Product(Metadata, Moo<Expression>),
167

            
168
    /// `min(<vec_expr>)`
169
    #[compatible(JsonInput, SMT)]
170
    Min(Metadata, Moo<Expression>),
171

            
172
    /// `max(<vec_expr>)`
173
    #[compatible(JsonInput, SMT)]
174
    Max(Metadata, Moo<Expression>),
175

            
176
    /// `not(a)`
177
    #[compatible(JsonInput, SAT, SMT)]
178
    Not(Metadata, Moo<Expression>),
179

            
180
    /// `or(<vec_expr>)`
181
    #[compatible(JsonInput, SAT, SMT)]
182
    Or(Metadata, Moo<Expression>),
183

            
184
    /// `and(<vec_expr>)`
185
    #[compatible(JsonInput, SAT, SMT)]
186
    And(Metadata, Moo<Expression>),
187

            
188
    /// Ensures that `a->b` (material implication).
189
    #[compatible(JsonInput, SMT)]
190
    Imply(Metadata, Moo<Expression>, Moo<Expression>),
191

            
192
    /// `iff(a, b)` a <-> b
193
    #[compatible(JsonInput, SMT)]
194
    Iff(Metadata, Moo<Expression>, Moo<Expression>),
195

            
196
    #[compatible(JsonInput)]
197
    Union(Metadata, Moo<Expression>, Moo<Expression>),
198

            
199
    #[compatible(JsonInput)]
200
    In(Metadata, Moo<Expression>, Moo<Expression>),
201

            
202
    #[compatible(JsonInput)]
203
    Intersect(Metadata, Moo<Expression>, Moo<Expression>),
204

            
205
    #[compatible(JsonInput)]
206
    Supset(Metadata, Moo<Expression>, Moo<Expression>),
207

            
208
    #[compatible(JsonInput)]
209
    SupsetEq(Metadata, Moo<Expression>, Moo<Expression>),
210

            
211
    #[compatible(JsonInput)]
212
    Subset(Metadata, Moo<Expression>, Moo<Expression>),
213

            
214
    #[compatible(JsonInput)]
215
    SubsetEq(Metadata, Moo<Expression>, Moo<Expression>),
216

            
217
    #[compatible(JsonInput, SMT)]
218
    Eq(Metadata, Moo<Expression>, Moo<Expression>),
219

            
220
    #[compatible(JsonInput, SMT)]
221
    Neq(Metadata, Moo<Expression>, Moo<Expression>),
222

            
223
    #[compatible(JsonInput, SMT)]
224
    Geq(Metadata, Moo<Expression>, Moo<Expression>),
225

            
226
    #[compatible(JsonInput, SMT)]
227
    Leq(Metadata, Moo<Expression>, Moo<Expression>),
228

            
229
    #[compatible(JsonInput, SMT)]
230
    Gt(Metadata, Moo<Expression>, Moo<Expression>),
231

            
232
    #[compatible(JsonInput, SMT)]
233
    Lt(Metadata, Moo<Expression>, Moo<Expression>),
234

            
235
    /// Division after preventing division by zero, usually with a bubble
236
    #[compatible(SMT)]
237
    SafeDiv(Metadata, Moo<Expression>, Moo<Expression>),
238

            
239
    /// Division with a possibly undefined value (division by 0)
240
    #[compatible(JsonInput)]
241
    UnsafeDiv(Metadata, Moo<Expression>, Moo<Expression>),
242

            
243
    /// Modulo after preventing mod 0, usually with a bubble
244
    #[compatible(SMT)]
245
    SafeMod(Metadata, Moo<Expression>, Moo<Expression>),
246

            
247
    /// Modulo with a possibly undefined value (mod 0)
248
    #[compatible(JsonInput)]
249
    UnsafeMod(Metadata, Moo<Expression>, Moo<Expression>),
250

            
251
    /// Negation: `-x`
252
    #[compatible(JsonInput, SMT)]
253
    Neg(Metadata, Moo<Expression>),
254

            
255
    /// Set of domain values function is defined for
256
    #[compatible(JsonInput)]
257
    Defined(Metadata, Moo<Expression>),
258

            
259
    /// Set of codomain values function is defined for
260
    #[compatible(JsonInput)]
261
    Range(Metadata, Moo<Expression>),
262

            
263
    /// Unsafe power`x**y` (possibly undefined)
264
    ///
265
    /// Defined when (X!=0 \\/ Y!=0) /\ Y>=0
266
    #[compatible(JsonInput)]
267
    UnsafePow(Metadata, Moo<Expression>, Moo<Expression>),
268

            
269
    /// `UnsafePow` after preventing undefinedness
270
    SafePow(Metadata, Moo<Expression>, Moo<Expression>),
271

            
272
    /// Flatten matrix operator
273
    /// `flatten(M)` or `flatten(n, M)`
274
    /// where M is a matrix and n is an optional integer argument indicating depth of flattening
275
    Flatten(Metadata, Option<Moo<Expression>>, Moo<Expression>),
276

            
277
    /// `allDiff(<vec_expr>)`
278
    #[compatible(JsonInput)]
279
    AllDiff(Metadata, Moo<Expression>),
280

            
281
    /// Binary subtraction operator
282
    ///
283
    /// This is a parser-level construct, and is immediately normalised to `Sum([a,-b])`.
284
    /// TODO: make this compatible with Set Difference calculations - need to change return type and domain for this expression and write a set comprehension rule.
285
    /// have already edited minus_to_sum to prevent this from applying to sets
286
    #[compatible(JsonInput)]
287
    Minus(Metadata, Moo<Expression>, Moo<Expression>),
288

            
289
    /// Ensures that x=|y| i.e. x is the absolute value of y.
290
    ///
291
    /// Low-level Minion constraint.
292
    ///
293
    /// # See also
294
    ///
295
    /// + [Minion documentation](https://minion-solver.readthedocs.io/en/stable/usage/constraints.html#abs)
296
    #[compatible(Minion)]
297
    FlatAbsEq(Metadata, Moo<Atom>, Moo<Atom>),
298

            
299
    /// Ensures that `alldiff([a,b,...])`.
300
    ///
301
    /// Low-level Minion constraint.
302
    ///
303
    /// # See also
304
    ///
305
    /// + [Minion documentation](https://minion-solver.readthedocs.io/en/stable/usage/constraints.html#alldiff)
306
    #[compatible(Minion)]
307
    FlatAllDiff(Metadata, Vec<Atom>),
308

            
309
    /// Ensures that sum(vec) >= x.
310
    ///
311
    /// Low-level Minion constraint.
312
    ///
313
    /// # See also
314
    ///
315
    /// + [Minion documentation](https://minion-solver.readthedocs.io/en/stable/usage/constraints.html#sumgeq)
316
    #[compatible(Minion)]
317
    FlatSumGeq(Metadata, Vec<Atom>, Atom),
318

            
319
    /// Ensures that sum(vec) <= x.
320
    ///
321
    /// Low-level Minion constraint.
322
    ///
323
    /// # See also
324
    ///
325
    /// + [Minion documentation](https://minion-solver.readthedocs.io/en/stable/usage/constraints.html#sumleq)
326
    #[compatible(Minion)]
327
    FlatSumLeq(Metadata, Vec<Atom>, Atom),
328

            
329
    /// `ineq(x,y,k)` ensures that x <= y + k.
330
    ///
331
    /// Low-level Minion constraint.
332
    ///
333
    /// # See also
334
    ///
335
    /// + [Minion documentation](https://minion-solver.readthedocs.io/en/stable/usage/constraints.html#ineq)
336
    #[compatible(Minion)]
337
    FlatIneq(Metadata, Moo<Atom>, Moo<Atom>, Box<Literal>),
338

            
339
    /// `w-literal(x,k)` ensures that x == k, where x is a variable and k a constant.
340
    ///
341
    /// Low-level Minion constraint.
342
    ///
343
    /// This is a low-level Minion constraint and you should probably use Eq instead. The main use
344
    /// of w-literal is to convert boolean variables to constraints so that they can be used inside
345
    /// watched-and and watched-or.
346
    ///
347
    /// # See also
348
    ///
349
    /// + [Minion documentation](https://minion-solver.readthedocs.io/en/stable/usage/constraints.html#minuseq)
350
    /// + `rules::minion::boolean_literal_to_wliteral`.
351
    #[compatible(Minion)]
352
    #[polyquine_skip]
353
    FlatWatchedLiteral(Metadata, Reference, Literal),
354

            
355
    /// `weightedsumleq(cs,xs,total)` ensures that cs.xs <= total, where cs.xs is the scalar dot
356
    /// product of cs and xs.
357
    ///
358
    /// Low-level Minion constraint.
359
    ///
360
    /// Represents a weighted sum of the form `ax + by + cz + ...`
361
    ///
362
    /// # See also
363
    ///
364
    /// + [Minion
365
    /// documentation](https://minion-solver.readthedocs.io/en/stable/usage/constraints.html#weightedsumleq)
366
    FlatWeightedSumLeq(Metadata, Vec<Literal>, Vec<Atom>, Moo<Atom>),
367

            
368
    /// `weightedsumgeq(cs,xs,total)` ensures that cs.xs >= total, where cs.xs is the scalar dot
369
    /// product of cs and xs.
370
    ///
371
    /// Low-level Minion constraint.
372
    ///
373
    /// Represents a weighted sum of the form `ax + by + cz + ...`
374
    ///
375
    /// # See also
376
    ///
377
    /// + [Minion
378
    /// documentation](https://minion-solver.readthedocs.io/en/stable/usage/constraints.html#weightedsumleq)
379
    FlatWeightedSumGeq(Metadata, Vec<Literal>, Vec<Atom>, Moo<Atom>),
380

            
381
    /// Ensures that x =-y, where x and y are atoms.
382
    ///
383
    /// Low-level Minion constraint.
384
    ///
385
    /// # See also
386
    ///
387
    /// + [Minion documentation](https://minion-solver.readthedocs.io/en/stable/usage/constraints.html#minuseq)
388
    #[compatible(Minion)]
389
    FlatMinusEq(Metadata, Moo<Atom>, Moo<Atom>),
390

            
391
    /// Ensures that x*y=z.
392
    ///
393
    /// Low-level Minion constraint.
394
    ///
395
    /// # See also
396
    ///
397
    /// + [Minion documentation](https://minion-solver.readthedocs.io/en/stable/usage/constraints.html#product)
398
    #[compatible(Minion)]
399
    FlatProductEq(Metadata, Moo<Atom>, Moo<Atom>, Moo<Atom>),
400

            
401
    /// Ensures that floor(x/y)=z. Always true when y=0.
402
    ///
403
    /// Low-level Minion constraint.
404
    ///
405
    /// # See also
406
    ///
407
    /// + [Minion documentation](https://minion-solver.readthedocs.io/en/stable/usage/constraints.html#div_undefzero)
408
    #[compatible(Minion)]
409
    MinionDivEqUndefZero(Metadata, Moo<Atom>, Moo<Atom>, Moo<Atom>),
410

            
411
    /// Ensures that x%y=z. Always true when y=0.
412
    ///
413
    /// Low-level Minion constraint.
414
    ///
415
    /// # See also
416
    ///
417
    /// + [Minion documentation](https://minion-solver.readthedocs.io/en/stable/usage/constraints.html#mod_undefzero)
418
    #[compatible(Minion)]
419
    MinionModuloEqUndefZero(Metadata, Moo<Atom>, Moo<Atom>, Moo<Atom>),
420

            
421
    /// Ensures that `x**y = z`.
422
    ///
423
    /// Low-level Minion constraint.
424
    ///
425
    /// This constraint is false when `y<0` except for `1**y=1` and `(-1)**y=z` (where z is 1 if y
426
    /// is odd and z is -1 if y is even).
427
    ///
428
    /// # See also
429
    ///
430
    /// + [Github comment about `pow` semantics](https://github.com/minion/minion/issues/40#issuecomment-2595914891)
431
    /// + [Minion documentation](https://minion-solver.readthedocs.io/en/stable/usage/constraints.html#pow)
432
    MinionPow(Metadata, Moo<Atom>, Moo<Atom>, Moo<Atom>),
433

            
434
    /// `reify(constraint,r)` ensures that r=1 iff `constraint` is satisfied, where r is a 0/1
435
    /// variable.
436
    ///
437
    /// Low-level Minion constraint.
438
    ///
439
    /// # See also
440
    ///
441
    ///  + [Minion documentation](https://minion-solver.readthedocs.io/en/stable/usage/constraints.html#reify)
442
    #[compatible(Minion)]
443
    MinionReify(Metadata, Moo<Expression>, Atom),
444

            
445
    /// `reifyimply(constraint,r)` ensures that `r->constraint`, where r is a 0/1 variable.
446
    /// variable.
447
    ///
448
    /// Low-level Minion constraint.
449
    ///
450
    /// # See also
451
    ///
452
    ///  + [Minion documentation](https://minion-solver.readthedocs.io/en/stable/usage/constraints.html#reifyimply)
453
    #[compatible(Minion)]
454
    MinionReifyImply(Metadata, Moo<Expression>, Atom),
455

            
456
    /// `w-inintervalset(x, [a1,a2, b1,b2, … ])` ensures that the value of x belongs to one of the
457
    /// intervals {a1,…,a2}, {b1,…,b2} etc.
458
    ///
459
    /// The list of intervals must be given in numerical order.
460
    ///
461
    /// Low-level Minion constraint.
462
    ///
463
    /// # See also
464
    ///>
465
    ///  + [Minion documentation](https://minion-solver.readthedocs.io/en/stable/usage/constraints.html#w-inintervalset)
466
    #[compatible(Minion)]
467
    MinionWInIntervalSet(Metadata, Atom, Vec<i32>),
468

            
469
    /// `w-inset(x, [v1, v2, … ])` ensures that the value of `x` is one of the explicitly given values `v1`, `v2`, etc.
470
    ///
471
    /// This constraint enforces membership in a specific set of discrete values rather than intervals.
472
    ///
473
    /// The list of values must be given in numerical order.
474
    ///
475
    /// Low-level Minion constraint.
476
    ///
477
    /// # See also
478
    ///
479
    ///  + [Minion documentation](https://minion-solver.readthedocs.io/en/stable/usage/constraints.html#w-inset)
480
    #[compatible(Minion)]
481
    MinionWInSet(Metadata, Atom, Vec<i32>),
482

            
483
    /// `element_one(vec, i, e)` specifies that `vec[i] = e`. This implies that i is
484
    /// in the range `[1..len(vec)]`.
485
    ///
486
    /// Low-level Minion constraint.
487
    ///
488
    /// # See also
489
    ///
490
    ///  + [Minion documentation](https://minion-solver.readthedocs.io/en/stable/usage/constraints.html#element_one)
491
    #[compatible(Minion)]
492
    MinionElementOne(Metadata, Vec<Atom>, Moo<Atom>, Moo<Atom>),
493

            
494
    /// Declaration of an auxiliary variable.
495
    ///
496
    /// As with Savile Row, we semantically distinguish this from `Eq`.
497
    #[compatible(Minion)]
498
    #[polyquine_skip]
499
    AuxDeclaration(Metadata, Reference, Moo<Expression>),
500

            
501
    /// This expression is for encoding ints for the SAT solver, it stores the encoding type, the vector of booleans and the min/max for the int.
502
    #[compatible(SAT)]
503
    SATInt(Metadata, SATIntEncoding, Moo<Expression>, (i32, i32)),
504

            
505
    /// Addition over a pair of expressions (i.e. a + b) rather than a vec-expr like Expression::Sum.
506
    /// This is for compatibility with backends that do not support addition over vectors.
507
    #[compatible(SMT)]
508
    PairwiseSum(Metadata, Moo<Expression>, Moo<Expression>),
509

            
510
    /// Multiplication over a pair of expressions (i.e. a * b) rather than a vec-expr like Expression::Product.
511
    /// This is for compatibility with backends that do not support multiplication over vectors.
512
    #[compatible(SMT)]
513
    PairwiseProduct(Metadata, Moo<Expression>, Moo<Expression>),
514

            
515
    #[compatible(JsonInput)]
516
    Image(Metadata, Moo<Expression>, Moo<Expression>),
517

            
518
    #[compatible(JsonInput)]
519
    ImageSet(Metadata, Moo<Expression>, Moo<Expression>),
520

            
521
    #[compatible(JsonInput)]
522
    PreImage(Metadata, Moo<Expression>, Moo<Expression>),
523

            
524
    #[compatible(JsonInput)]
525
    Inverse(Metadata, Moo<Expression>, Moo<Expression>),
526

            
527
    #[compatible(JsonInput)]
528
    Restrict(Metadata, Moo<Expression>, Moo<Expression>),
529

            
530
    /// Lexicographical < between two matrices.
531
    ///
532
    /// A <lex B iff: A[i] < B[i] for some i /\ (A[j] > B[j] for some j -> i < j)
533
    /// I.e. A must be less than B at some index i, and if it is greater than B at another index j,
534
    /// then j comes after i.
535
    /// I.e. A must be greater than B at the first index where they differ.
536
    ///
537
    /// E.g. [1, 1] <lex [2, 1] and [1, 1] <lex [1, 2]
538
    LexLt(Metadata, Moo<Expression>, Moo<Expression>),
539

            
540
    /// Lexicographical <= between two matrices
541
    LexLeq(Metadata, Moo<Expression>, Moo<Expression>),
542

            
543
    /// Lexicographical > between two matrices
544
    /// This is a parser-level construct, and is immediately normalised to LexLt(b, a)
545
    LexGt(Metadata, Moo<Expression>, Moo<Expression>),
546

            
547
    /// Lexicographical >= between two matrices
548
    /// This is a parser-level construct, and is immediately normalised to LexLeq(b, a)
549
    LexGeq(Metadata, Moo<Expression>, Moo<Expression>),
550

            
551
    /// Low-level minion constraint. See Expression::LexLt
552
    FlatLexLt(Metadata, Vec<Atom>, Vec<Atom>),
553

            
554
    /// Low-level minion constraint. See Expression::LexLeq
555
    FlatLexLeq(Metadata, Vec<Atom>, Vec<Atom>),
556
}
557

            
558
// for the given matrix literal, return a bounded domain from the min to max of applying op to each
559
// child expression.
560
//
561
// Op must be monotonic.
562
//
563
// Returns none if unbounded
564
151014
fn bounded_i32_domain_for_matrix_literal_monotonic(
565
151014
    e: &Expression,
566
151014
    op: fn(i32, i32) -> Option<i32>,
567
151014
) -> Option<DomainPtr> {
568
    // only care about the elements, not the indices
569
151014
    let (mut exprs, _) = e.clone().unwrap_matrix_unchecked()?;
570

            
571
    // fold each element's domain into one using op.
572
    //
573
    // here, I assume that op is monotone. This means that the bounds of op([a1,a2],[b1,b2])  for
574
    // the ranges [a1,a2], [b1,b2] will be
575
    // [min(op(a1,b1),op(a2,b1),op(a1,b2),op(a2,b2)),max(op(a1,b1),op(a2,b1),op(a1,b2),op(a2,b2))].
576
    //
577
    // We used to not assume this, and work out the bounds by applying op on the Cartesian product
578
    // of A and B; however, this caused a combinatorial explosion and my computer to run out of
579
    // memory (on the hakank_eprime_xkcd test)...
580
    //Int
581
    // For example, to find the bounds of the intervals [1,4], [1,5] combined using op, we used to do
582
    //  [min(op(1,1), op(1,2),op(1,3),op(1,4),op(1,5),op(2,1)..
583
    //
584
    // +,-,/,* are all monotone, so this assumption should be fine for now...
585

            
586
142785
    let expr = exprs.pop()?;
587
142783
    let dom = expr.domain_of()?;
588
141301
    let resolved = dom.resolve()?;
589
141301
    let GroundDomain::Int(ranges) = resolved.as_ref() else {
590
2
        return None;
591
    };
592

            
593
141299
    let (mut current_min, mut current_max) = range_vec_bounds_i32(ranges)?;
594

            
595
189698
    for expr in exprs {
596
189698
        let dom = expr.domain_of()?;
597
188918
        let resolved = dom.resolve()?;
598
188918
        let GroundDomain::Int(ranges) = resolved.as_ref() else {
599
            return None;
600
        };
601

            
602
188918
        let (min, max) = range_vec_bounds_i32(ranges)?;
603

            
604
        // all the possible new values for current_min / current_max
605
188918
        let minmax = op(min, current_max)?;
606
188918
        let minmin = op(min, current_min)?;
607
188918
        let maxmin = op(max, current_min)?;
608
188918
        let maxmax = op(max, current_max)?;
609
188918
        let vals = [minmax, minmin, maxmin, maxmax];
610

            
611
188918
        current_min = *vals
612
188918
            .iter()
613
188918
            .min()
614
188918
            .expect("vals iterator should not be empty, and should have a minimum.");
615
188918
        current_max = *vals
616
188918
            .iter()
617
188918
            .max()
618
188918
            .expect("vals iterator should not be empty, and should have a maximum.");
619
    }
620

            
621
140519
    if current_min == current_max {
622
14861
        Some(Domain::int(vec![Range::Single(current_min)]))
623
    } else {
624
125658
        Some(Domain::int(vec![Range::Bounded(current_min, current_max)]))
625
    }
626
151014
}
627

            
628
// Returns none if unbounded
629
330217
fn range_vec_bounds_i32(ranges: &Vec<Range<i32>>) -> Option<(i32, i32)> {
630
330217
    let mut min = i32::MAX;
631
330217
    let mut max = i32::MIN;
632
336184
    for r in ranges {
633
336184
        match r {
634
73441
            Range::Single(i) => {
635
73441
                if *i < min {
636
67474
                    min = *i;
637
67474
                }
638
73441
                if *i > max {
639
73441
                    max = *i;
640
73441
                }
641
            }
642
262743
            Range::Bounded(i, j) => {
643
262743
                if *i < min {
644
262743
                    min = *i;
645
262743
                }
646
262743
                if *j > max {
647
262743
                    max = *j;
648
262743
                }
649
            }
650
            Range::UnboundedR(_) | Range::UnboundedL(_) | Range::Unbounded => return None,
651
        }
652
    }
653
330217
    Some((min, max))
654
330217
}
655

            
656
impl Expression {
657
    /// Returns the possible values of the expression, recursing to leaf expressions
658
1182157
    pub fn domain_of(&self) -> Option<DomainPtr> {
659
1182157
        match self {
660
            Expression::Union(_, a, b) => Some(Domain::set(
661
                SetAttr::<IntVal>::default(),
662
                a.domain_of()?.union(&b.domain_of()?).ok()?,
663
            )),
664
            Expression::Intersect(_, a, b) => Some(Domain::set(
665
                SetAttr::<IntVal>::default(),
666
                a.domain_of()?.intersect(&b.domain_of()?).ok()?,
667
            )),
668
            Expression::In(_, _, _) => Some(Domain::bool()),
669
            Expression::Supset(_, _, _) => Some(Domain::bool()),
670
            Expression::SupsetEq(_, _, _) => Some(Domain::bool()),
671
            Expression::Subset(_, _, _) => Some(Domain::bool()),
672
            Expression::SubsetEq(_, _, _) => Some(Domain::bool()),
673
39415
            Expression::AbstractLiteral(_, abslit) => abslit.domain_of(),
674
            Expression::DominanceRelation(_, _) => Some(Domain::bool()),
675
            Expression::FromSolution(_, expr) => Some(expr.domain_of()),
676
            Expression::Metavar(_, _) => None,
677
            Expression::Comprehension(_, comprehension) => comprehension.domain_of(),
678
            Expression::AbstractComprehension(_, comprehension) => comprehension.domain_of(),
679
186888
            Expression::UnsafeIndex(_, matrix, _) | Expression::SafeIndex(_, matrix, _) => {
680
199212
                let dom = matrix.domain_of()?;
681
199212
                if let Some((elem_domain, _)) = dom.as_matrix() {
682
199212
                    return Some(elem_domain);
683
                }
684

            
685
                // may actually use the value in the future
686
                #[allow(clippy::redundant_pattern_matching)]
687
                if let Some(_) = dom.as_tuple() {
688
                    // TODO: We can implement proper indexing for tuples
689
                    return None;
690
                }
691

            
692
                // may actually use the value in the future
693
                #[allow(clippy::redundant_pattern_matching)]
694
                if let Some(_) = dom.as_record() {
695
                    // TODO: We can implement proper indexing for records
696
                    return None;
697
                }
698

            
699
                bug!("subject of an index operation should support indexing")
700
            }
701
            Expression::UnsafeSlice(_, matrix, indices)
702
312
            | Expression::SafeSlice(_, matrix, indices) => {
703
312
                let sliced_dimension = indices.iter().position(Option::is_none);
704

            
705
312
                let dom = matrix.domain_of()?;
706
312
                let Some((elem_domain, index_domains)) = dom.as_matrix() else {
707
                    bug!("subject of an index operation should be a matrix");
708
                };
709

            
710
312
                match sliced_dimension {
711
312
                    Some(dimension) => Some(Domain::matrix(
712
312
                        elem_domain,
713
312
                        vec![index_domains[dimension].clone()],
714
312
                    )),
715

            
716
                    // same as index
717
                    None => Some(elem_domain),
718
                }
719
            }
720
            Expression::InDomain(_, _, _) => Some(Domain::bool()),
721
753751
            Expression::Atomic(_, atom) => Some(atom.domain_of()),
722
91305
            Expression::Sum(_, e) => {
723
513872
                bounded_i32_domain_for_matrix_literal_monotonic(e, |x, y| Some(x + y))
724
            }
725
58071
            Expression::Product(_, e) => {
726
232596
                bounded_i32_domain_for_matrix_literal_monotonic(e, |x, y| Some(x * y))
727
            }
728
6396
            Expression::Min(_, e) => bounded_i32_domain_for_matrix_literal_monotonic(e, |x, y| {
729
6396
                Some(if x < y { x } else { y })
730
6396
            }),
731
2808
            Expression::Max(_, e) => bounded_i32_domain_for_matrix_literal_monotonic(e, |x, y| {
732
2808
                Some(if x > y { x } else { y })
733
2808
            }),
734
7410
            Expression::UnsafeDiv(_, a, b) => a
735
7410
                .domain_of()?
736
7410
                .resolve()?
737
7410
                .apply_i32(
738
                    // rust integer division is truncating; however, we want to always round down,
739
                    // including for negative numbers.
740
8619
                    |x, y| {
741
8619
                        if y != 0 {
742
8424
                            Some((x as f32 / y as f32).floor() as i32)
743
                        } else {
744
195
                            None
745
                        }
746
8619
                    },
747
7410
                    b.domain_of()?.resolve()?.as_ref(),
748
                )
749
7410
                .map(DomainPtr::from)
750
7410
                .ok(),
751
2418
            Expression::SafeDiv(_, a, b) => {
752
                // rust integer division is truncating; however, we want to always round down
753
                // including for negative numbers.
754
2418
                let domain = a
755
2418
                    .domain_of()?
756
2418
                    .resolve()?
757
2418
                    .apply_i32(
758
73164
                        |x, y| {
759
73164
                            if y != 0 {
760
66027
                                Some((x as f32 / y as f32).floor() as i32)
761
                            } else {
762
7137
                                None
763
                            }
764
73164
                        },
765
2418
                        b.domain_of()?.resolve()?.as_ref(),
766
                    )
767
                    .unwrap_or_else(|err| bug!("Got {err} when computing domain of {self}"));
768

            
769
2418
                if let GroundDomain::Int(ranges) = domain {
770
2418
                    let mut ranges = ranges;
771
2418
                    ranges.push(Range::Single(0));
772
2418
                    Some(Domain::int(ranges))
773
                } else {
774
                    bug!("Domain of {self} was not integer")
775
                }
776
            }
777
            Expression::UnsafeMod(_, a, b) => a
778
                .domain_of()?
779
                .resolve()?
780
                .apply_i32(
781
                    |x, y| if y != 0 { Some(x % y) } else { None },
782
                    b.domain_of()?.resolve()?.as_ref(),
783
                )
784
                .map(DomainPtr::from)
785
                .ok(),
786
858
            Expression::SafeMod(_, a, b) => {
787
858
                let domain = a
788
858
                    .domain_of()?
789
858
                    .resolve()?
790
858
                    .apply_i32(
791
23439
                        |x, y| if y != 0 { Some(x % y) } else { None },
792
858
                        b.domain_of()?.resolve()?.as_ref(),
793
                    )
794
                    .unwrap_or_else(|err| bug!("Got {err} when computing domain of {self}"));
795

            
796
858
                if let GroundDomain::Int(ranges) = domain {
797
858
                    let mut ranges = ranges;
798
858
                    ranges.push(Range::Single(0));
799
858
                    Some(Domain::int(ranges))
800
                } else {
801
                    bug!("Domain of {self} was not integer")
802
                }
803
            }
804
780
            Expression::SafePow(_, a, b) | Expression::UnsafePow(_, a, b) => a
805
780
                .domain_of()?
806
780
                .resolve()?
807
780
                .apply_i32(
808
20202
                    |x, y| {
809
20202
                        if (x != 0 || y != 0) && y >= 0 {
810
19422
                            Some(x.pow(y as u32))
811
                        } else {
812
780
                            None
813
                        }
814
20202
                    },
815
780
                    b.domain_of()?.resolve()?.as_ref(),
816
                )
817
780
                .map(DomainPtr::from)
818
780
                .ok(),
819
            Expression::Root(_, _) => None,
820
195
            Expression::Bubble(_, inner, _) => inner.domain_of(),
821
            Expression::AuxDeclaration(_, _, _) => Some(Domain::bool()),
822
2924
            Expression::And(_, _) => Some(Domain::bool()),
823
273
            Expression::Not(_, _) => Some(Domain::bool()),
824
39
            Expression::Or(_, _) => Some(Domain::bool()),
825
312
            Expression::Imply(_, _, _) => Some(Domain::bool()),
826
            Expression::Iff(_, _, _) => Some(Domain::bool()),
827
1170
            Expression::Eq(_, _, _) => Some(Domain::bool()),
828
            Expression::Neq(_, _, _) => Some(Domain::bool()),
829
39
            Expression::Geq(_, _, _) => Some(Domain::bool()),
830
1053
            Expression::Leq(_, _, _) => Some(Domain::bool()),
831
78
            Expression::Gt(_, _, _) => Some(Domain::bool()),
832
            Expression::Lt(_, _, _) => Some(Domain::bool()),
833
            Expression::FlatAbsEq(_, _, _) => Some(Domain::bool()),
834
351
            Expression::FlatSumGeq(_, _, _) => Some(Domain::bool()),
835
            Expression::FlatSumLeq(_, _, _) => Some(Domain::bool()),
836
            Expression::MinionDivEqUndefZero(_, _, _, _) => Some(Domain::bool()),
837
            Expression::MinionModuloEqUndefZero(_, _, _, _) => Some(Domain::bool()),
838
78
            Expression::FlatIneq(_, _, _, _) => Some(Domain::bool()),
839
390
            Expression::Flatten(_, n, m) => {
840
390
                if let Some(expr) = n {
841
                    if expr.return_type() == ReturnType::Int {
842
                        // TODO: handle flatten with depth argument
843
                        return None;
844
                    }
845
                } else {
846
                    // TODO: currently only works for matrices
847
390
                    let dom = m.domain_of()?.resolve()?;
848
390
                    let (val_dom, idx_doms) = match dom.as_ref() {
849
390
                        GroundDomain::Matrix(val, idx) => (val, idx),
850
                        _ => return None,
851
                    };
852
390
                    let num_elems = matrix::num_elements(idx_doms).ok()? as i32;
853

            
854
390
                    let new_index_domain = Domain::int(vec![Range::Bounded(1, num_elems)]);
855
390
                    return Some(Domain::matrix(
856
390
                        val_dom.clone().into(),
857
390
                        vec![new_index_domain],
858
390
                    ));
859
                }
860
                None
861
            }
862
            Expression::AllDiff(_, _) => Some(Domain::bool()),
863
            Expression::FlatWatchedLiteral(_, _, _) => Some(Domain::bool()),
864
            Expression::MinionReify(_, _, _) => Some(Domain::bool()),
865
351
            Expression::MinionReifyImply(_, _, _) => Some(Domain::bool()),
866
            Expression::MinionWInIntervalSet(_, _, _) => Some(Domain::bool()),
867
            Expression::MinionWInSet(_, _, _) => Some(Domain::bool()),
868
            Expression::MinionElementOne(_, _, _, _) => Some(Domain::bool()),
869
3393
            Expression::Neg(_, x) => {
870
3393
                let dom = x.domain_of()?;
871
3393
                let mut ranges = dom.as_int()?;
872

            
873
1131
                ranges = ranges
874
1131
                    .into_iter()
875
1131
                    .map(|r| match r {
876
156
                        Range::Single(x) => Range::Single(-x),
877
975
                        Range::Bounded(x, y) => Range::Bounded(-y, -x),
878
                        Range::UnboundedR(i) => Range::UnboundedL(-i),
879
                        Range::UnboundedL(i) => Range::UnboundedR(-i),
880
                        Range::Unbounded => Range::Unbounded,
881
1131
                    })
882
1131
                    .collect();
883

            
884
1131
                Some(Domain::int(ranges))
885
            }
886
14547
            Expression::Minus(_, a, b) => a
887
14547
                .domain_of()?
888
14547
                .resolve()?
889
30108
                .apply_i32(|x, y| Some(x - y), b.domain_of()?.resolve()?.as_ref())
890
14547
                .map(DomainPtr::from)
891
14547
                .ok(),
892
            Expression::FlatAllDiff(_, _) => Some(Domain::bool()),
893
            Expression::FlatMinusEq(_, _, _) => Some(Domain::bool()),
894
            Expression::FlatProductEq(_, _, _, _) => Some(Domain::bool()),
895
            Expression::FlatWeightedSumLeq(_, _, _, _) => Some(Domain::bool()),
896
            Expression::FlatWeightedSumGeq(_, _, _, _) => Some(Domain::bool()),
897
975
            Expression::Abs(_, a) => a
898
975
                .domain_of()?
899
975
                .resolve()?
900
188721
                .apply_i32(|a, _| Some(a.abs()), a.domain_of()?.resolve()?.as_ref())
901
975
                .map(DomainPtr::from)
902
975
                .ok(),
903
            Expression::MinionPow(_, _, _, _) => Some(Domain::bool()),
904
819
            Expression::ToInt(_, _) => Some(Domain::int(vec![Range::Bounded(0, 1)])),
905
            Expression::SATInt(_, _, _, (low, high)) => {
906
                Some(Domain::int_ground(vec![Range::Bounded(*low, *high)]))
907
            }
908
            Expression::PairwiseSum(_, a, b) => a
909
                .domain_of()?
910
                .resolve()?
911
                .apply_i32(|a, b| Some(a + b), b.domain_of()?.resolve()?.as_ref())
912
                .map(DomainPtr::from)
913
                .ok(),
914
            Expression::PairwiseProduct(_, a, b) => a
915
                .domain_of()?
916
                .resolve()?
917
                .apply_i32(|a, b| Some(a * b), b.domain_of()?.resolve()?.as_ref())
918
                .map(DomainPtr::from)
919
                .ok(),
920
            Expression::Defined(_, function) => get_function_domain(function),
921
            Expression::Range(_, function) => get_function_codomain(function),
922
            Expression::Image(_, function, _) => get_function_codomain(function),
923
            Expression::ImageSet(_, function, _) => get_function_codomain(function),
924
            Expression::PreImage(_, function, _) => get_function_domain(function),
925
            Expression::Restrict(_, function, new_domain) => {
926
                let (attrs, _, codom) = function.domain_of()?.as_function()?;
927
                let new_dom = new_domain.domain_of()?;
928
                Some(Domain::function(attrs, new_dom, codom))
929
            }
930
            Expression::Inverse(..) => Some(Domain::bool()),
931
            Expression::LexLt(..) => Some(Domain::bool()),
932
            Expression::LexLeq(..) => Some(Domain::bool()),
933
            Expression::LexGt(..) => Some(Domain::bool()),
934
            Expression::LexGeq(..) => Some(Domain::bool()),
935
            Expression::FlatLexLt(..) => Some(Domain::bool()),
936
            Expression::FlatLexLeq(..) => Some(Domain::bool()),
937
        }
938
1182157
    }
939

            
940
    pub fn get_meta(&self) -> Metadata {
941
        let metas: VecDeque<Metadata> = self.children_bi();
942
        metas[0].clone()
943
    }
944

            
945
    pub fn set_meta(&self, meta: Metadata) {
946
        self.transform_bi(&|_| meta.clone());
947
    }
948

            
949
    /// Checks whether this expression is safe.
950
    ///
951
    /// An expression is unsafe if can be undefined, or if any of its children can be undefined.
952
    ///
953
    /// Unsafe expressions are (typically) prefixed with Unsafe in our AST, and can be made
954
    /// safe through the use of bubble rules.
955
119378
    pub fn is_safe(&self) -> bool {
956
        // TODO: memoise in Metadata
957
1509959
        for expr in self.universe() {
958
1509959
            match expr {
959
                Expression::UnsafeDiv(_, _, _)
960
                | Expression::UnsafeMod(_, _, _)
961
                | Expression::UnsafePow(_, _, _)
962
                | Expression::UnsafeIndex(_, _, _)
963
                | Expression::Bubble(_, _, _)
964
                | Expression::UnsafeSlice(_, _, _) => {
965
3237
                    return false;
966
                }
967
1506722
                _ => {}
968
            }
969
        }
970
116141
        true
971
119378
    }
972

            
973
    pub fn is_clean(&self) -> bool {
974
        let metadata = self.get_meta();
975
        metadata.clean
976
    }
977

            
978
    pub fn set_clean(&mut self, bool_value: bool) {
979
        let mut metadata = self.get_meta();
980
        metadata.clean = bool_value;
981
        self.set_meta(metadata);
982
    }
983

            
984
    /// True if the expression is an associative and commutative operator
985
8775931
    pub fn is_associative_commutative_operator(&self) -> bool {
986
8775931
        TryInto::<ACOperatorKind>::try_into(self).is_ok()
987
8775931
    }
988

            
989
    /// True if the expression is a matrix literal.
990
    ///
991
    /// This is true for both forms of matrix literals: those with elements of type [`Literal`] and
992
    /// [`Expression`].
993
18603
    pub fn is_matrix_literal(&self) -> bool {
994
        matches!(
995
18603
            self,
996
            Expression::AbstractLiteral(_, AbstractLiteral::Matrix(_, _))
997
                | Expression::Atomic(
998
                    _,
999
                    Atom::Literal(Literal::AbstractLiteral(AbstractLiteral::Matrix(_, _))),
                )
        )
18603
    }
    /// True iff self and other are both atomic and identical.
    ///
    /// This method is useful to cheaply check equivalence. Assuming CSE is enabled, any unifiable
    /// expressions will be rewritten to a common variable. This is much cheaper than checking the
    /// entire subtrees of `self` and `other`.
53196
    pub fn identical_atom_to(&self, other: &Expression) -> bool {
53196
        let atom1: Result<&Atom, _> = self.try_into();
53196
        let atom2: Result<&Atom, _> = other.try_into();
53196
        if let (Ok(atom1), Ok(atom2)) = (atom1, atom2) {
2886
            atom2 == atom1
        } else {
50310
            false
        }
53196
    }
    /// If the expression is a list, returns a *copied* vector of the inner expressions.
    ///
    /// A list is any a matrix with the domain `int(1..)`. This includes matrix literals without
    /// any explicitly specified domain.
4755451
    pub fn unwrap_list(&self) -> Option<Vec<Expression>> {
3968920
        match self {
3968920
            Expression::AbstractLiteral(_, matrix @ AbstractLiteral::Matrix(_, _)) => {
3968920
                matrix.unwrap_list().cloned()
            }
            Expression::Atomic(
                _,
3857
                Atom::Literal(Literal::AbstractLiteral(matrix @ AbstractLiteral::Matrix(_, _))),
3857
            ) => matrix.unwrap_list().map(|elems| {
971
                elems
971
                    .clone()
971
                    .into_iter()
3046
                    .map(|x: Literal| Expression::Atomic(Metadata::new(), Atom::Literal(x)))
971
                    .collect_vec()
971
            }),
782674
            _ => None,
        }
4755451
    }
    /// If the expression is a matrix, gets it elements and index domain.
    ///
    /// **Consider using the safer [`Expression::unwrap_list`] instead.**
    ///
    /// It is generally undefined to edit the length of a matrix unless it is a list (as defined by
    /// [`Expression::unwrap_list`]). Users of this function should ensure that, if the matrix is
    /// reconstructed, the index domain and the number of elements in the matrix remain the same.
5430718
    pub fn unwrap_matrix_unchecked(self) -> Option<(Vec<Expression>, DomainPtr)> {
3499553
        match self {
3499553
            Expression::AbstractLiteral(_, AbstractLiteral::Matrix(elems, domain)) => {
3499553
                Some((elems, domain))
            }
            Expression::Atomic(
                _,
269412
                Atom::Literal(Literal::AbstractLiteral(AbstractLiteral::Matrix(elems, domain))),
            ) => Some((
269412
                elems
269412
                    .into_iter()
532623
                    .map(|x: Literal| Expression::Atomic(Metadata::new(), Atom::Literal(x)))
269412
                    .collect_vec(),
269412
                domain.into(),
            )),
1661753
            _ => None,
        }
5430718
    }
    /// For a Root expression, extends the inner vec with the given vec.
    ///
    /// # Panics
    /// Panics if the expression is not Root.
    pub fn extend_root(self, exprs: Vec<Expression>) -> Expression {
        match self {
            Expression::Root(meta, mut children) => {
                children.extend(exprs);
                Expression::Root(meta, children)
            }
            _ => panic!("extend_root called on a non-Root expression"),
        }
    }
    /// Converts the expression to a literal, if possible.
109970
    pub fn into_literal(self) -> Option<Literal> {
100886
        match self {
84584
            Expression::Atomic(_, Atom::Literal(lit)) => Some(lit),
            Expression::AbstractLiteral(_, abslit) => {
                Some(Literal::AbstractLiteral(abslit.into_literals()?))
            }
2493
            Expression::Neg(_, e) => {
2493
                let Literal::Int(i) = Moo::unwrap_or_clone(e).into_literal()? else {
                    bug!("negated literal should be an int");
                };
2493
                Some(Literal::Int(-i))
            }
22893
            _ => None,
        }
109970
    }
    /// If this expression is an associative-commutative operator, return its [ACOperatorKind].
9846233
    pub fn to_ac_operator_kind(&self) -> Option<ACOperatorKind> {
9846233
        TryFrom::try_from(self).ok()
9846233
    }
    /// Returns the categories of all sub-expressions of self.
71135
    pub fn universe_categories(&self) -> HashSet<Category> {
71135
        self.universe()
71135
            .into_iter()
1123079
            .map(|x| x.category_of())
71135
            .collect()
71135
    }
}
pub fn get_function_domain(function: &Moo<Expression>) -> Option<DomainPtr> {
    let function_domain = function.domain_of()?;
    match function_domain.resolve().as_ref() {
        Some(d) => {
            match d.as_ref() {
                GroundDomain::Function(_, domain, _) => Some(domain.clone().into()),
                // Not defined for anything other than a function
                _ => None,
            }
        }
        None => {
            match function_domain.as_unresolved()? {
                UnresolvedDomain::Function(_, domain, _) => Some(domain.clone()),
                // Not defined for anything other than a function
                _ => None,
            }
        }
    }
}
pub fn get_function_codomain(function: &Moo<Expression>) -> Option<DomainPtr> {
    let function_domain = function.domain_of()?;
    match function_domain.resolve().as_ref() {
        Some(d) => {
            match d.as_ref() {
                GroundDomain::Function(_, _, codomain) => Some(codomain.clone().into()),
                // Not defined for anything other than a function
                _ => None,
            }
        }
        None => {
            match function_domain.as_unresolved()? {
                UnresolvedDomain::Function(_, _, codomain) => Some(codomain.clone()),
                // Not defined for anything other than a function
                _ => None,
            }
        }
    }
}
impl TryFrom<&Expression> for i32 {
    type Error = ();
576459
    fn try_from(value: &Expression) -> Result<Self, Self::Error> {
576459
        let Expression::Atomic(_, atom) = value else {
414960
            return Err(());
        };
161499
        let Atom::Literal(lit) = atom else {
161499
            return Err(());
        };
        let Literal::Int(i) = lit else {
            return Err(());
        };
        Ok(*i)
576459
    }
}
impl TryFrom<Expression> for i32 {
    type Error = ();
    fn try_from(value: Expression) -> Result<Self, Self::Error> {
        TryFrom::<&Expression>::try_from(&value)
    }
}
impl From<i32> for Expression {
33113
    fn from(i: i32) -> Self {
33113
        Expression::Atomic(Metadata::new(), Atom::Literal(Literal::Int(i)))
33113
    }
}
impl From<bool> for Expression {
5044
    fn from(b: bool) -> Self {
5044
        Expression::Atomic(Metadata::new(), Atom::Literal(Literal::Bool(b)))
5044
    }
}
impl From<Atom> for Expression {
2301
    fn from(value: Atom) -> Self {
2301
        Expression::Atomic(Metadata::new(), value)
2301
    }
}
impl From<Literal> for Expression {
4212
    fn from(value: Literal) -> Self {
4212
        Expression::Atomic(Metadata::new(), value.into())
4212
    }
}
impl From<Moo<Expression>> for Expression {
41646
    fn from(val: Moo<Expression>) -> Self {
41646
        val.as_ref().clone()
41646
    }
}
impl CategoryOf for Expression {
1561088
    fn category_of(&self) -> Category {
        // take highest category of all the expressions children
8681469
        let category = self.cata(&move |x,children| {
8681469
            if let Some(max_category) = children.iter().max() {
                // if this expression contains subexpressions, return the maximum category of the
                // subexpressions
2695365
                *max_category
            } else {
                // this expression has no children
5986104
                let mut max_category = Category::Bottom;
                // calculate the category by looking at all atoms, submodels, comprehensions, and
                // declarationptrs inside this expression
                // this should generically cover all leaf types we currently have in oxide.
                // if x contains submodels (including comprehensions)
5986104
                if !Biplate::<Model>::universe_bi(&x).is_empty() {
                    // assume that the category is decision
                    return Category::Decision;
5986104
                }
                // if x contains atoms
5987730
                if let Some(max_atom_category) = Biplate::<Atom>::universe_bi(&x).iter().map(|x| x.category_of()).max()
                // and those atoms have a higher category than we already know about
5986104
                && max_atom_category > max_category{
                    // update category 
5986104
                    max_category = max_atom_category;
5986104
                }
                // if x contains declarationPtrs
5986104
                if let Some(max_declaration_category) = Biplate::<DeclarationPtr>::universe_bi(&x).iter().map(|x| x.category_of()).max()
                // and those pointers have a higher category than we already know about
4832367
                && max_declaration_category > max_category{
                    // update category 
                    max_category = max_declaration_category;
5986104
                }
5986104
                max_category
            }
8681469
        });
1561088
        if cfg!(debug_assertions) {
1561088
            trace!(
                category= %category,
                expression= %self,
                "Called Expression::category_of()"
            );
        };
1561088
        category
1561088
    }
}
impl Display for Expression {
15632006
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
15632006
        match &self {
468
            Expression::Union(_, box1, box2) => {
468
                write!(f, "({} union {})", box1.clone(), box2.clone())
            }
3122
            Expression::In(_, e1, e2) => {
3122
                write!(f, "{e1} in {e2}")
            }
468
            Expression::Intersect(_, box1, box2) => {
468
                write!(f, "({} intersect {})", box1.clone(), box2.clone())
            }
624
            Expression::Supset(_, box1, box2) => {
624
                write!(f, "({} supset {})", box1.clone(), box2.clone())
            }
624
            Expression::SupsetEq(_, box1, box2) => {
624
                write!(f, "({} supsetEq {})", box1.clone(), box2.clone())
            }
780
            Expression::Subset(_, box1, box2) => {
780
                write!(f, "({} subset {})", box1.clone(), box2.clone())
            }
1560
            Expression::SubsetEq(_, box1, box2) => {
1560
                write!(f, "({} subsetEq {})", box1.clone(), box2.clone())
            }
1924635
            Expression::AbstractLiteral(_, l) => l.fmt(f),
49637
            Expression::Comprehension(_, c) => c.fmt(f),
156
            Expression::AbstractComprehension(_, c) => c.fmt(f),
782184
            Expression::UnsafeIndex(_, e1, e2) | Expression::SafeIndex(_, e1, e2) => {
1081470
                write!(f, "{e1}{}", pretty_vec(e2))
            }
82212
            Expression::UnsafeSlice(_, e1, es) | Expression::SafeSlice(_, e1, es) => {
131352
                let args = es
131352
                    .iter()
260910
                    .map(|x| match x {
129558
                        Some(x) => format!("{x}"),
131352
                        None => "..".into(),
260910
                    })
131352
                    .join(",");
131352
                write!(f, "{e1}[{args}]")
            }
121602
            Expression::InDomain(_, e, domain) => {
121602
                write!(f, "__inDomain({e},{domain})")
            }
217228
            Expression::Root(_, exprs) => {
217228
                write!(f, "{}", pretty_expressions_as_top_level(exprs))
            }
            Expression::DominanceRelation(_, expr) => write!(f, "DominanceRelation({expr})"),
            Expression::FromSolution(_, expr) => write!(f, "FromSolution({expr})"),
            Expression::Metavar(_, name) => write!(f, "&{name}"),
8435627
            Expression::Atomic(_, atom) => atom.fmt(f),
4603
            Expression::Abs(_, a) => write!(f, "|{a}|"),
898242
            Expression::Sum(_, e) => {
898242
                write!(f, "sum({e})")
            }
421551
            Expression::Product(_, e) => {
421551
                write!(f, "product({e})")
            }
3744
            Expression::Min(_, e) => {
3744
                write!(f, "min({e})")
            }
1482
            Expression::Max(_, e) => {
1482
                write!(f, "max({e})")
            }
10491
            Expression::Not(_, expr_box) => {
10491
                write!(f, "!({})", expr_box.clone())
            }
56844
            Expression::Or(_, e) => {
56844
                write!(f, "or({e})")
            }
232814
            Expression::And(_, e) => {
232814
                write!(f, "and({e})")
            }
36855
            Expression::Imply(_, box1, box2) => {
36855
                write!(f, "({box1}) -> ({box2})")
            }
1482
            Expression::Iff(_, box1, box2) => {
1482
                write!(f, "({box1}) <-> ({box2})")
            }
422816
            Expression::Eq(_, box1, box2) => {
422816
                write!(f, "({} = {})", box1.clone(), box2.clone())
            }
198620
            Expression::Neq(_, box1, box2) => {
198620
                write!(f, "({} != {})", box1.clone(), box2.clone())
            }
19451
            Expression::Geq(_, box1, box2) => {
19451
                write!(f, "({} >= {})", box1.clone(), box2.clone())
            }
62817
            Expression::Leq(_, box1, box2) => {
62817
                write!(f, "({} <= {})", box1.clone(), box2.clone())
            }
5068
            Expression::Gt(_, box1, box2) => {
5068
                write!(f, "({} > {})", box1.clone(), box2.clone())
            }
46289
            Expression::Lt(_, box1, box2) => {
46289
                write!(f, "({} < {})", box1.clone(), box2.clone())
            }
158977
            Expression::FlatSumGeq(_, box1, box2) => {
158977
                write!(f, "SumGeq({}, {})", pretty_vec(box1), box2.clone())
            }
125086
            Expression::FlatSumLeq(_, box1, box2) => {
125086
                write!(f, "SumLeq({}, {})", pretty_vec(box1), box2.clone())
            }
29016
            Expression::FlatIneq(_, box1, box2, box3) => write!(
29016
                f,
                "Ineq({}, {}, {})",
29016
                box1.clone(),
29016
                box2.clone(),
29016
                box3.clone()
            ),
4056
            Expression::Flatten(_, n, m) => {
4056
                if let Some(n) = n {
                    write!(f, "flatten({n}, {m})")
                } else {
4056
                    write!(f, "flatten({m})")
                }
            }
34632
            Expression::AllDiff(_, e) => {
34632
                write!(f, "allDiff({e})")
            }
72618
            Expression::Bubble(_, box1, box2) => {
72618
                write!(f, "{{{} @ {}}}", box1.clone(), box2.clone())
            }
20085
            Expression::SafeDiv(_, box1, box2) => {
20085
                write!(f, "SafeDiv({}, {})", box1.clone(), box2.clone())
            }
6396
            Expression::UnsafeDiv(_, box1, box2) => {
6396
                write!(f, "UnsafeDiv({}, {})", box1.clone(), box2.clone())
            }
4368
            Expression::UnsafePow(_, box1, box2) => {
4368
                write!(f, "UnsafePow({}, {})", box1.clone(), box2.clone())
            }
5655
            Expression::SafePow(_, box1, box2) => {
5655
                write!(f, "SafePow({}, {})", box1.clone(), box2.clone())
            }
3276
            Expression::MinionDivEqUndefZero(_, box1, box2, box3) => {
3276
                write!(
3276
                    f,
                    "DivEq({}, {}, {})",
3276
                    box1.clone(),
3276
                    box2.clone(),
3276
                    box3.clone()
                )
            }
1404
            Expression::MinionModuloEqUndefZero(_, box1, box2, box3) => {
1404
                write!(
1404
                    f,
                    "ModEq({}, {}, {})",
1404
                    box1.clone(),
1404
                    box2.clone(),
1404
                    box3.clone()
                )
            }
2964
            Expression::FlatWatchedLiteral(_, x, l) => {
2964
                write!(f, "WatchedLiteral({x},{l})")
            }
69808
            Expression::MinionReify(_, box1, box2) => {
69808
                write!(f, "Reify({}, {})", box1.clone(), box2.clone())
            }
32487
            Expression::MinionReifyImply(_, box1, box2) => {
32487
                write!(f, "ReifyImply({}, {})", box1.clone(), box2.clone())
            }
702
            Expression::MinionWInIntervalSet(_, atom, intervals) => {
702
                let intervals = intervals.iter().join(",");
702
                write!(f, "__minion_w_inintervalset({atom},[{intervals}])")
            }
624
            Expression::MinionWInSet(_, atom, values) => {
624
                let values = values.iter().join(",");
624
                write!(f, "__minion_w_inset({atom},[{values}])")
            }
109080
            Expression::AuxDeclaration(_, reference, e) => {
109080
                write!(f, "{} =aux {}", reference, e.clone())
            }
3276
            Expression::UnsafeMod(_, a, b) => {
3276
                write!(f, "{} % {}", a.clone(), b.clone())
            }
8658
            Expression::SafeMod(_, a, b) => {
8658
                write!(f, "SafeMod({},{})", a.clone(), b.clone())
            }
82252
            Expression::Neg(_, a) => {
82252
                write!(f, "-({})", a.clone())
            }
242843
            Expression::Minus(_, a, b) => {
242843
                write!(f, "({} - {})", a.clone(), b.clone())
            }
16224
            Expression::FlatAllDiff(_, es) => {
16224
                write!(f, "__flat_alldiff({})", pretty_vec(es))
            }
858
            Expression::FlatAbsEq(_, a, b) => {
858
                write!(f, "AbsEq({},{})", a.clone(), b.clone())
            }
780
            Expression::FlatMinusEq(_, a, b) => {
780
                write!(f, "MinusEq({},{})", a.clone(), b.clone())
            }
819
            Expression::FlatProductEq(_, a, b, c) => {
819
                write!(
819
                    f,
                    "FlatProductEq({},{},{})",
819
                    a.clone(),
819
                    b.clone(),
819
                    c.clone()
                )
            }
66768
            Expression::FlatWeightedSumLeq(_, cs, vs, total) => {
66768
                write!(
66768
                    f,
                    "FlatWeightedSumLeq({},{},{})",
66768
                    pretty_vec(cs),
66768
                    pretty_vec(vs),
66768
                    total.clone()
                )
            }
67197
            Expression::FlatWeightedSumGeq(_, cs, vs, total) => {
67197
                write!(
67197
                    f,
                    "FlatWeightedSumGeq({},{},{})",
67197
                    pretty_vec(cs),
67197
                    pretty_vec(vs),
67197
                    total.clone()
                )
            }
1248
            Expression::MinionPow(_, atom, atom1, atom2) => {
1248
                write!(f, "MinionPow({atom},{atom1},{atom2})")
            }
2808
            Expression::MinionElementOne(_, atoms, atom, atom1) => {
2808
                let atoms = atoms.iter().join(",");
2808
                write!(f, "__minion_element_one([{atoms}],{atom},{atom1})")
            }
936
            Expression::ToInt(_, expr) => {
936
                write!(f, "toInt({expr})")
            }
8664
            Expression::SATInt(_, encoding, bits, (min, max)) => {
8664
                write!(f, "SATInt({encoding:?}, {bits} [{min}, {max}])")
            }
            Expression::PairwiseSum(_, a, b) => write!(f, "PairwiseSum({a}, {b})"),
            Expression::PairwiseProduct(_, a, b) => write!(f, "PairwiseProduct({a}, {b})"),
40
            Expression::Defined(_, function) => write!(f, "defined({function})"),
40
            Expression::Range(_, function) => write!(f, "range({function})"),
40
            Expression::Image(_, function, elems) => write!(f, "image({function},{elems})"),
40
            Expression::ImageSet(_, function, elems) => write!(f, "imageSet({function},{elems})"),
40
            Expression::PreImage(_, function, elems) => write!(f, "preImage({function},{elems})"),
40
            Expression::Inverse(_, a, b) => write!(f, "inverse({a},{b})"),
40
            Expression::Restrict(_, function, domain) => write!(f, "restrict({function},{domain})"),
1092
            Expression::LexLt(_, a, b) => write!(f, "({a} <lex {b})"),
53079
            Expression::LexLeq(_, a, b) => write!(f, "({a} <=lex {b})"),
            Expression::LexGt(_, a, b) => write!(f, "({a} >lex {b})"),
            Expression::LexGeq(_, a, b) => write!(f, "({a} >=lex {b})"),
156
            Expression::FlatLexLt(_, a, b) => {
156
                write!(f, "FlatLexLt({}, {})", pretty_vec(a), pretty_vec(b))
            }
312
            Expression::FlatLexLeq(_, a, b) => {
312
                write!(f, "FlatLexLeq({}, {})", pretty_vec(a), pretty_vec(b))
            }
        }
15632006
    }
}
impl Typeable for Expression {
771481
    fn return_type(&self) -> ReturnType {
771481
        match self {
            Expression::Union(_, subject, _) => ReturnType::Set(Box::new(subject.return_type())),
            Expression::Intersect(_, subject, _) => {
                ReturnType::Set(Box::new(subject.return_type()))
            }
390
            Expression::In(_, _, _) => ReturnType::Bool,
            Expression::Supset(_, _, _) => ReturnType::Bool,
            Expression::SupsetEq(_, _, _) => ReturnType::Bool,
            Expression::Subset(_, _, _) => ReturnType::Bool,
            Expression::SubsetEq(_, _, _) => ReturnType::Bool,
21488
            Expression::AbstractLiteral(_, lit) => lit.return_type(),
67080
            Expression::UnsafeIndex(_, subject, idx) | Expression::SafeIndex(_, subject, idx) => {
117819
                let subject_ty = subject.return_type();
117819
                match subject_ty {
                    ReturnType::Matrix(_) => {
                        // For n-dimensional matrices, unwrap the element type until
                        // we either get to the innermost element type or the last index
114777
                        let mut elem_typ = subject_ty;
114777
                        let mut idx_len = idx.len();
229788
                        while idx_len > 0
136734
                            && let ReturnType::Matrix(new_elem_typ) = &elem_typ
115011
                        {
115011
                            elem_typ = *new_elem_typ.clone();
115011
                            idx_len -= 1;
115011
                        }
114777
                        elem_typ
                    }
                    // TODO: We can implement indexing for these eventually
3042
                    ReturnType::Record(_) | ReturnType::Tuple(_) => ReturnType::Unknown,
                    _ => bug!(
                        "Invalid indexing operation: expected the operand to be a collection, got {self}: {subject_ty}"
                    ),
                }
            }
3744
            Expression::UnsafeSlice(_, subject, _) | Expression::SafeSlice(_, subject, _) => {
3744
                ReturnType::Matrix(Box::new(subject.return_type()))
            }
            Expression::InDomain(_, _, _) => ReturnType::Bool,
            Expression::Comprehension(_, comp) => comp.return_type(),
            Expression::AbstractComprehension(_, comp) => comp.return_type(),
            Expression::Root(_, _) => ReturnType::Bool,
            Expression::DominanceRelation(_, _) => ReturnType::Bool,
            Expression::FromSolution(_, expr) => expr.return_type(),
            Expression::Metavar(_, _) => ReturnType::Unknown,
463472
            Expression::Atomic(_, atom) => atom.return_type(),
429
            Expression::Abs(_, _) => ReturnType::Int,
114228
            Expression::Sum(_, _) => ReturnType::Int,
9516
            Expression::Product(_, _) => ReturnType::Int,
780
            Expression::Min(_, _) => ReturnType::Int,
507
            Expression::Max(_, _) => ReturnType::Int,
39
            Expression::Not(_, _) => ReturnType::Bool,
351
            Expression::Or(_, _) => ReturnType::Bool,
1248
            Expression::Imply(_, _, _) => ReturnType::Bool,
            Expression::Iff(_, _, _) => ReturnType::Bool,
3080
            Expression::And(_, _) => ReturnType::Bool,
5179
            Expression::Eq(_, _, _) => ReturnType::Bool,
702
            Expression::Neq(_, _, _) => ReturnType::Bool,
78
            Expression::Geq(_, _, _) => ReturnType::Bool,
1911
            Expression::Leq(_, _, _) => ReturnType::Bool,
78
            Expression::Gt(_, _, _) => ReturnType::Bool,
            Expression::Lt(_, _, _) => ReturnType::Bool,
6942
            Expression::SafeDiv(_, _, _) => ReturnType::Int,
1131
            Expression::UnsafeDiv(_, _, _) => ReturnType::Int,
            Expression::FlatAllDiff(_, _) => ReturnType::Bool,
351
            Expression::FlatSumGeq(_, _, _) => ReturnType::Bool,
            Expression::FlatSumLeq(_, _, _) => ReturnType::Bool,
            Expression::MinionDivEqUndefZero(_, _, _, _) => ReturnType::Bool,
78
            Expression::FlatIneq(_, _, _, _) => ReturnType::Bool,
936
            Expression::Flatten(_, _, matrix) => {
936
                let matrix_type = matrix.return_type();
936
                match matrix_type {
                    ReturnType::Matrix(_) => {
                        // unwrap until we get to innermost element
936
                        let mut elem_type = matrix_type;
1872
                        while let ReturnType::Matrix(new_elem_type) = &elem_type {
936
                            elem_type = *new_elem_type.clone();
936
                        }
936
                        ReturnType::Matrix(Box::new(elem_type))
                    }
                    _ => bug!(
                        "Invalid indexing operation: expected the operand to be a collection, got {self}: {matrix_type}"
                    ),
                }
            }
195
            Expression::AllDiff(_, _) => ReturnType::Bool,
1482
            Expression::Bubble(_, inner, _) => inner.return_type(),
            Expression::FlatWatchedLiteral(_, _, _) => ReturnType::Bool,
            Expression::MinionReify(_, _, _) => ReturnType::Bool,
351
            Expression::MinionReifyImply(_, _, _) => ReturnType::Bool,
            Expression::MinionWInIntervalSet(_, _, _) => ReturnType::Bool,
            Expression::MinionWInSet(_, _, _) => ReturnType::Bool,
            Expression::MinionElementOne(_, _, _, _) => ReturnType::Bool,
            Expression::AuxDeclaration(_, _, _) => ReturnType::Bool,
819
            Expression::UnsafeMod(_, _, _) => ReturnType::Int,
3315
            Expression::SafeMod(_, _, _) => ReturnType::Int,
            Expression::MinionModuloEqUndefZero(_, _, _, _) => ReturnType::Bool,
3237
            Expression::Neg(_, _) => ReturnType::Int,
468
            Expression::UnsafePow(_, _, _) => ReturnType::Int,
2652
            Expression::SafePow(_, _, _) => ReturnType::Int,
663
            Expression::Minus(_, _, _) => ReturnType::Int,
            Expression::FlatAbsEq(_, _, _) => ReturnType::Bool,
            Expression::FlatMinusEq(_, _, _) => ReturnType::Bool,
            Expression::FlatProductEq(_, _, _, _) => ReturnType::Bool,
            Expression::FlatWeightedSumLeq(_, _, _, _) => ReturnType::Bool,
            Expression::FlatWeightedSumGeq(_, _, _, _) => ReturnType::Bool,
            Expression::MinionPow(_, _, _, _) => ReturnType::Bool,
156
            Expression::ToInt(_, _) => ReturnType::Int,
            Expression::SATInt(..) => ReturnType::Int,
            Expression::PairwiseSum(_, _, _) => ReturnType::Int,
            Expression::PairwiseProduct(_, _, _) => ReturnType::Int,
            Expression::Defined(_, function) => {
                let subject = function.return_type();
                match subject {
                    ReturnType::Function(domain, _) => *domain,
                    _ => bug!(
                        "Invalid defined operation: expected the operand to be a function, got {self}: {subject}"
                    ),
                }
            }
            Expression::Range(_, function) => {
                let subject = function.return_type();
                match subject {
                    ReturnType::Function(_, codomain) => *codomain,
                    _ => bug!(
                        "Invalid range operation: expected the operand to be a function, got {self}: {subject}"
                    ),
                }
            }
            Expression::Image(_, function, _) => {
                let subject = function.return_type();
                match subject {
                    ReturnType::Function(_, codomain) => *codomain,
                    _ => bug!(
                        "Invalid image operation: expected the operand to be a function, got {self}: {subject}"
                    ),
                }
            }
            Expression::ImageSet(_, function, _) => {
                let subject = function.return_type();
                match subject {
                    ReturnType::Function(_, codomain) => *codomain,
                    _ => bug!(
                        "Invalid imageSet operation: expected the operand to be a function, got {self}: {subject}"
                    ),
                }
            }
            Expression::PreImage(_, function, _) => {
                let subject = function.return_type();
                match subject {
                    ReturnType::Function(domain, _) => *domain,
                    _ => bug!(
                        "Invalid preImage operation: expected the operand to be a function, got {self}: {subject}"
                    ),
                }
            }
            Expression::Restrict(_, function, new_domain) => {
                let subject = function.return_type();
                match subject {
                    ReturnType::Function(_, codomain) => {
                        ReturnType::Function(Box::new(new_domain.return_type()), codomain)
                    }
                    _ => bug!(
                        "Invalid preImage operation: expected the operand to be a function, got {self}: {subject}"
                    ),
                }
            }
            Expression::Inverse(..) => ReturnType::Bool,
            Expression::LexLt(..) => ReturnType::Bool,
            Expression::LexGt(..) => ReturnType::Bool,
3666
            Expression::LexLeq(..) => ReturnType::Bool,
            Expression::LexGeq(..) => ReturnType::Bool,
            Expression::FlatLexLt(..) => ReturnType::Bool,
            Expression::FlatLexLeq(..) => ReturnType::Bool,
        }
771481
    }
}
#[cfg(test)]
mod tests {
    use crate::matrix_expr;
    use super::*;
    #[test]
2
    fn test_domain_of_constant_sum() {
2
        let c1 = Expression::Atomic(Metadata::new(), Atom::Literal(Literal::Int(1)));
2
        let c2 = Expression::Atomic(Metadata::new(), Atom::Literal(Literal::Int(2)));
2
        let sum = Expression::Sum(Metadata::new(), Moo::new(matrix_expr![c1, c2]));
2
        assert_eq!(sum.domain_of(), Some(Domain::int(vec![Range::Single(3)])));
2
    }
    #[test]
2
    fn test_domain_of_constant_invalid_type() {
2
        let c1 = Expression::Atomic(Metadata::new(), Atom::Literal(Literal::Int(1)));
2
        let c2 = Expression::Atomic(Metadata::new(), Atom::Literal(Literal::Bool(true)));
2
        let sum = Expression::Sum(Metadata::new(), Moo::new(matrix_expr![c1, c2]));
2
        assert_eq!(sum.domain_of(), None);
2
    }
    #[test]
2
    fn test_domain_of_empty_sum() {
2
        let sum = Expression::Sum(Metadata::new(), Moo::new(matrix_expr![]));
2
        assert_eq!(sum.domain_of(), None);
2
    }
}