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, Moo, Name, Range, Reference, ReturnType, SetAttr, SubModel, SymbolTable,
26
    SymbolTablePtr, 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=SubModel)]
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 SubModel which contains a bunch of Rc 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
    // todo (gskorokhod): Same reason as for Comprehension
157
    #[polyquine_skip]
158
    Scope(Metadata, Moo<SubModel>),
159

            
160
    /// `|x|` - absolute value of `x`
161
    #[compatible(JsonInput, SMT)]
162
    Abs(Metadata, Moo<Expression>),
163

            
164
    /// `sum(<vec_expr>)`
165
    #[compatible(JsonInput, SMT)]
166
    Sum(Metadata, Moo<Expression>),
167

            
168
    /// `a * b * c * ...`
169
    #[compatible(JsonInput, SMT)]
170
    Product(Metadata, Moo<Expression>),
171

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

            
176
    /// `max(<vec_expr>)`
177
    #[compatible(JsonInput, SMT)]
178
    Max(Metadata, Moo<Expression>),
179

            
180
    /// `not(a)`
181
    #[compatible(JsonInput, SAT, SMT)]
182
    Not(Metadata, Moo<Expression>),
183

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

            
188
    /// `and(<vec_expr>)`
189
    #[compatible(JsonInput, SAT, SMT)]
190
    And(Metadata, Moo<Expression>),
191

            
192
    /// Ensures that `a->b` (material implication).
193
    #[compatible(JsonInput, SMT)]
194
    Imply(Metadata, Moo<Expression>, Moo<Expression>),
195

            
196
    /// `iff(a, b)` a <-> b
197
    #[compatible(JsonInput, SMT)]
198
    Iff(Metadata, Moo<Expression>, Moo<Expression>),
199

            
200
    #[compatible(JsonInput)]
201
    Union(Metadata, Moo<Expression>, Moo<Expression>),
202

            
203
    #[compatible(JsonInput)]
204
    In(Metadata, Moo<Expression>, Moo<Expression>),
205

            
206
    #[compatible(JsonInput)]
207
    Intersect(Metadata, Moo<Expression>, Moo<Expression>),
208

            
209
    #[compatible(JsonInput)]
210
    Supset(Metadata, Moo<Expression>, Moo<Expression>),
211

            
212
    #[compatible(JsonInput)]
213
    SupsetEq(Metadata, Moo<Expression>, Moo<Expression>),
214

            
215
    #[compatible(JsonInput)]
216
    Subset(Metadata, Moo<Expression>, Moo<Expression>),
217

            
218
    #[compatible(JsonInput)]
219
    SubsetEq(Metadata, Moo<Expression>, Moo<Expression>),
220

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

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

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

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

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

            
236
    #[compatible(JsonInput, SMT)]
237
    Lt(Metadata, Moo<Expression>, Moo<Expression>),
238

            
239
    /// Division after preventing division by zero, usually with a bubble
240
    #[compatible(SMT)]
241
    SafeDiv(Metadata, Moo<Expression>, Moo<Expression>),
242

            
243
    /// Division with a possibly undefined value (division by 0)
244
    #[compatible(JsonInput)]
245
    UnsafeDiv(Metadata, Moo<Expression>, Moo<Expression>),
246

            
247
    /// Modulo after preventing mod 0, usually with a bubble
248
    #[compatible(SMT)]
249
    SafeMod(Metadata, Moo<Expression>, Moo<Expression>),
250

            
251
    /// Modulo with a possibly undefined value (mod 0)
252
    #[compatible(JsonInput)]
253
    UnsafeMod(Metadata, Moo<Expression>, Moo<Expression>),
254

            
255
    /// Negation: `-x`
256
    #[compatible(JsonInput, SMT)]
257
    Neg(Metadata, Moo<Expression>),
258

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

            
263
    /// Set of codomain values function is defined for
264
    #[compatible(JsonInput)]
265
    Range(Metadata, Moo<Expression>),
266

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

            
273
    /// `UnsafePow` after preventing undefinedness
274
    SafePow(Metadata, Moo<Expression>, Moo<Expression>),
275

            
276
    /// Flatten matrix operator
277
    /// `flatten(M)` or `flatten(n, M)`
278
    /// where M is a matrix and n is an optional integer argument indicating depth of flattening
279
    Flatten(Metadata, Option<Moo<Expression>>, Moo<Expression>),
280

            
281
    /// `allDiff(<vec_expr>)`
282
    #[compatible(JsonInput)]
283
    AllDiff(Metadata, Moo<Expression>),
284

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
505
    /// 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.
506
    #[compatible(SAT)]
507
    SATInt(Metadata, SATIntEncoding, Moo<Expression>, (i32, i32)),
508

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

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

            
519
    #[compatible(JsonInput)]
520
    Image(Metadata, Moo<Expression>, Moo<Expression>),
521

            
522
    #[compatible(JsonInput)]
523
    ImageSet(Metadata, Moo<Expression>, Moo<Expression>),
524

            
525
    #[compatible(JsonInput)]
526
    PreImage(Metadata, Moo<Expression>, Moo<Expression>),
527

            
528
    #[compatible(JsonInput)]
529
    Inverse(Metadata, Moo<Expression>, Moo<Expression>),
530

            
531
    #[compatible(JsonInput)]
532
    Restrict(Metadata, Moo<Expression>, Moo<Expression>),
533

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

            
544
    /// Lexicographical <= between two matrices
545
    LexLeq(Metadata, Moo<Expression>, Moo<Expression>),
546

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

            
551
    /// Lexicographical >= between two matrices
552
    /// This is a parser-level construct, and is immediately normalised to LexLeq(b, a)
553
    LexGeq(Metadata, Moo<Expression>, Moo<Expression>),
554

            
555
    /// Low-level minion constraint. See Expression::LexLt
556
    FlatLexLt(Metadata, Vec<Atom>, Vec<Atom>),
557

            
558
    /// Low-level minion constraint. See Expression::LexLeq
559
    FlatLexLeq(Metadata, Vec<Atom>, Vec<Atom>),
560
}
561

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

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

            
590
8203
    let expr = exprs.pop()?;
591
8202
    let dom = expr.domain_of()?;
592
8202
    let Some(GroundDomain::Int(ranges)) = dom.as_ground() else {
593
1121
        return None;
594
    };
595

            
596
7081
    let (mut current_min, mut current_max) = range_vec_bounds_i32(ranges)?;
597

            
598
10101
    for expr in exprs {
599
10101
        let dom = expr.domain_of()?;
600
10101
        let Some(GroundDomain::Int(ranges)) = dom.as_ground() else {
601
            return None;
602
        };
603

            
604
10101
        let (min, max) = range_vec_bounds_i32(ranges)?;
605

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

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

            
623
7081
    if current_min == current_max {
624
41
        Some(Domain::int(vec![Range::Single(current_min)]))
625
    } else {
626
7040
        Some(Domain::int(vec![Range::Bounded(current_min, current_max)]))
627
    }
628
8563
}
629

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

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

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

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

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

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

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

            
718
                    // same as index
719
                    None => Some(elem_domain),
720
                }
721
            }
722
            Expression::InDomain(_, _, _) => Some(Domain::bool()),
723
53503
            Expression::Atomic(_, atom) => Some(atom.domain_of()),
724
            Expression::Scope(_, _) => Some(Domain::bool()),
725
6163
            Expression::Sum(_, e) => {
726
29284
                bounded_i32_domain_for_matrix_literal_monotonic(e, |x, y| Some(x + y))
727
            }
728
1560
            Expression::Product(_, e) => {
729
6400
                bounded_i32_domain_for_matrix_literal_monotonic(e, |x, y| Some(x * y))
730
            }
731
3280
            Expression::Min(_, e) => bounded_i32_domain_for_matrix_literal_monotonic(e, |x, y| {
732
3280
                Some(if x < y { x } else { y })
733
3280
            }),
734
1440
            Expression::Max(_, e) => bounded_i32_domain_for_matrix_literal_monotonic(e, |x, y| {
735
1440
                Some(if x > y { x } else { y })
736
1440
            }),
737
80
            Expression::UnsafeDiv(_, a, b) => a
738
80
                .domain_of()?
739
80
                .resolve()?
740
80
                .apply_i32(
741
                    // rust integer division is truncating; however, we want to always round down,
742
                    // including for negative numbers.
743
700
                    |x, y| {
744
700
                        if y != 0 {
745
600
                            Some((x as f32 / y as f32).floor() as i32)
746
                        } else {
747
100
                            None
748
                        }
749
700
                    },
750
80
                    b.domain_of()?.resolve()?.as_ref(),
751
                )
752
80
                .map(DomainPtr::from)
753
80
                .ok(),
754
1240
            Expression::SafeDiv(_, a, b) => {
755
                // rust integer division is truncating; however, we want to always round down
756
                // including for negative numbers.
757
1240
                let domain = a
758
1240
                    .domain_of()?
759
1240
                    .resolve()?
760
1240
                    .apply_i32(
761
37520
                        |x, y| {
762
37520
                            if y != 0 {
763
33860
                                Some((x as f32 / y as f32).floor() as i32)
764
                            } else {
765
3660
                                None
766
                            }
767
37520
                        },
768
1240
                        b.domain_of()?.resolve()?.as_ref(),
769
                    )
770
                    .unwrap_or_else(|err| bug!("Got {err} when computing domain of {self}"));
771

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

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

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

            
876
440
                ranges = ranges
877
440
                    .into_iter()
878
440
                    .map(|r| match r {
879
80
                        Range::Single(x) => Range::Single(-x),
880
360
                        Range::Bounded(x, y) => Range::Bounded(-y, -x),
881
                        Range::UnboundedR(i) => Range::UnboundedL(-i),
882
                        Range::UnboundedL(i) => Range::UnboundedR(-i),
883
                        Range::Unbounded => Range::Unbounded,
884
440
                    })
885
440
                    .collect();
886

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

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

            
948
    pub fn set_meta(&self, meta: Metadata) {
949
        self.transform_bi(&|_| meta.clone());
950
    }
951

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

            
976
    pub fn is_clean(&self) -> bool {
977
        let metadata = self.get_meta();
978
        metadata.clean
979
    }
980

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

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

            
992
    /// True if the expression is a matrix literal.
993
    ///
994
    /// This is true for both forms of matrix literals: those with elements of type [`Literal`] and
995
    /// [`Expression`].
996
1160
    pub fn is_matrix_literal(&self) -> bool {
997
        matches!(
998
1160
            self,
999
            Expression::AbstractLiteral(_, AbstractLiteral::Matrix(_, _))
                | Expression::Atomic(
                    _,
                    Atom::Literal(Literal::AbstractLiteral(AbstractLiteral::Matrix(_, _))),
                )
        )
1160
    }
    /// 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`.
10400
    pub fn identical_atom_to(&self, other: &Expression) -> bool {
10400
        let atom1: Result<&Atom, _> = self.try_into();
10400
        let atom2: Result<&Atom, _> = other.try_into();
10400
        if let (Ok(atom1), Ok(atom2)) = (atom1, atom2) {
1840
            atom2 == atom1
        } else {
8560
            false
        }
10400
    }
    /// 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.
485070
    pub fn unwrap_list(&self) -> Option<Vec<Expression>> {
287540
        match self {
287540
            Expression::AbstractLiteral(_, matrix @ AbstractLiteral::Matrix(_, _)) => {
287540
                matrix.unwrap_list().cloned()
            }
            Expression::Atomic(
                _,
1880
                Atom::Literal(Literal::AbstractLiteral(matrix @ AbstractLiteral::Matrix(_, _))),
1880
            ) => matrix.unwrap_list().map(|elems| {
400
                elems
400
                    .clone()
400
                    .into_iter()
1180
                    .map(|x: Literal| Expression::Atomic(Metadata::new(), Atom::Literal(x)))
400
                    .collect_vec()
400
            }),
195650
            _ => None,
        }
485070
    }
    /// 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.
508503
    pub fn unwrap_matrix_unchecked(self) -> Option<(Vec<Expression>, DomainPtr)> {
144863
        match self {
144863
            Expression::AbstractLiteral(_, AbstractLiteral::Matrix(elems, domain)) => {
144863
                Some((elems, domain))
            }
            Expression::Atomic(
                _,
6800
                Atom::Literal(Literal::AbstractLiteral(AbstractLiteral::Matrix(elems, domain))),
            ) => Some((
6800
                elems
6800
                    .into_iter()
14540
                    .map(|x: Literal| Expression::Atomic(Metadata::new(), Atom::Literal(x)))
6800
                    .collect_vec(),
6800
                domain.into(),
            )),
356840
            _ => None,
        }
508503
    }
    /// 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.
41820
    pub fn into_literal(self) -> Option<Literal> {
40380
        match self {
37960
            Expression::Atomic(_, Atom::Literal(lit)) => Some(lit),
            Expression::AbstractLiteral(_, abslit) => {
                Some(Literal::AbstractLiteral(abslit.into_literals()?))
            }
1220
            Expression::Neg(_, e) => {
1220
                let Literal::Int(i) = Moo::unwrap_or_clone(e).into_literal()? else {
                    bug!("negated literal should be an int");
                };
1220
                Some(Literal::Int(-i))
            }
2640
            _ => None,
        }
41820
    }
    /// If this expression is an associative-commutative operator, return its [ACOperatorKind].
237900
    pub fn to_ac_operator_kind(&self) -> Option<ACOperatorKind> {
237900
        TryFrom::try_from(self).ok()
237900
    }
    /// Returns the categories of all sub-expressions of self.
10640
    pub fn universe_categories(&self) -> HashSet<Category> {
10640
        self.universe()
10640
            .into_iter()
56080
            .map(|x| x.category_of())
10640
            .collect()
10640
    }
}
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 = ();
7980
    fn try_from(value: &Expression) -> Result<Self, Self::Error> {
7980
        let Expression::Atomic(_, atom) = value else {
3500
            return Err(());
        };
4480
        let Atom::Literal(lit) = atom else {
4480
            return Err(());
        };
        let Literal::Int(i) = lit else {
            return Err(());
        };
        Ok(*i)
7980
    }
}
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 {
1248
    fn from(i: i32) -> Self {
1248
        Expression::Atomic(Metadata::new(), Atom::Literal(Literal::Int(i)))
1248
    }
}
impl From<bool> for Expression {
1530
    fn from(b: bool) -> Self {
1530
        Expression::Atomic(Metadata::new(), Atom::Literal(Literal::Bool(b)))
1530
    }
}
impl From<Atom> for Expression {
1540
    fn from(value: Atom) -> Self {
1540
        Expression::Atomic(Metadata::new(), value)
1540
    }
}
impl From<Literal> for Expression {
2160
    fn from(value: Literal) -> Self {
2160
        Expression::Atomic(Metadata::new(), value.into())
2160
    }
}
impl From<Moo<Expression>> for Expression {
3920
    fn from(val: Moo<Expression>) -> Self {
3920
        val.as_ref().clone()
3920
    }
}
impl CategoryOf for Expression {
70400
    fn category_of(&self) -> Category {
        // take highest category of all the expressions children
180080
        let category = self.cata(&move |x,children| {
180080
            if let Some(max_category) = children.iter().max() {
                // if this expression contains subexpressions, return the maximum category of the
                // subexpressions
55360
                *max_category
            } else {
                // this expression has no children
124720
                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)
124720
                if !Biplate::<SubModel>::universe_bi(&x).is_empty() {
                    // assume that the category is decision
                    return Category::Decision;
124720
                }
                // if x contains atoms
126720
                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
124720
                && max_atom_category > max_category{
                    // update category 
124720
                    max_category = max_atom_category;
124720
                }
                // if x contains declarationPtrs
124720
                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
84800
                && max_declaration_category > max_category{
                    // update category 
                    max_category = max_declaration_category;
124720
                }
124720
                max_category
            }
180080
        });
70400
        if cfg!(debug_assertions) {
70400
            trace!(
                category= %category,
                expression= %self,
                "Called Expression::category_of()"
            );
        };
70400
        category
70400
    }
}
impl Display for Expression {
1562636
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1562636
        match &self {
240
            Expression::Union(_, box1, box2) => {
240
                write!(f, "({} union {})", box1.clone(), box2.clone())
            }
1640
            Expression::In(_, e1, e2) => {
1640
                write!(f, "{e1} in {e2}")
            }
240
            Expression::Intersect(_, box1, box2) => {
240
                write!(f, "({} intersect {})", box1.clone(), box2.clone())
            }
320
            Expression::Supset(_, box1, box2) => {
320
                write!(f, "({} supset {})", box1.clone(), box2.clone())
            }
320
            Expression::SupsetEq(_, box1, box2) => {
320
                write!(f, "({} supsetEq {})", box1.clone(), box2.clone())
            }
400
            Expression::Subset(_, box1, box2) => {
400
                write!(f, "({} subset {})", box1.clone(), box2.clone())
            }
800
            Expression::SubsetEq(_, box1, box2) => {
800
                write!(f, "({} subsetEq {})", box1.clone(), box2.clone())
            }
130060
            Expression::AbstractLiteral(_, l) => l.fmt(f),
8280
            Expression::Comprehension(_, c) => c.fmt(f),
80
            Expression::AbstractComprehension(_, c) => c.fmt(f),
115780
            Expression::UnsafeIndex(_, e1, e2) | Expression::SafeIndex(_, e1, e2) => {
148060
                write!(f, "{e1}{}", pretty_vec(e2))
            }
9480
            Expression::UnsafeSlice(_, e1, es) | Expression::SafeSlice(_, e1, es) => {
14000
                let args = es
14000
                    .iter()
27520
                    .map(|x| match x {
13520
                        Some(x) => format!("{x}"),
14000
                        None => "..".into(),
27520
                    })
14000
                    .join(",");
14000
                write!(f, "{e1}[{args}]")
            }
14000
            Expression::InDomain(_, e, domain) => {
14000
                write!(f, "__inDomain({e},{domain})")
            }
28252
            Expression::Root(_, exprs) => {
28252
                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}"),
775884
            Expression::Atomic(_, atom) => atom.fmt(f),
            Expression::Scope(_, submodel) => write!(f, "{{\n{submodel}\n}}"),
2380
            Expression::Abs(_, a) => write!(f, "|{a}|"),
47940
            Expression::Sum(_, e) => {
47940
                write!(f, "sum({e})")
            }
15560
            Expression::Product(_, e) => {
15560
                write!(f, "product({e})")
            }
1920
            Expression::Min(_, e) => {
1920
                write!(f, "min({e})")
            }
760
            Expression::Max(_, e) => {
760
                write!(f, "max({e})")
            }
3780
            Expression::Not(_, expr_box) => {
3780
                write!(f, "!({})", expr_box.clone())
            }
22160
            Expression::Or(_, e) => {
22160
                write!(f, "or({e})")
            }
36240
            Expression::And(_, e) => {
36240
                write!(f, "and({e})")
            }
6660
            Expression::Imply(_, box1, box2) => {
6660
                write!(f, "({box1}) -> ({box2})")
            }
760
            Expression::Iff(_, box1, box2) => {
760
                write!(f, "({box1}) <-> ({box2})")
            }
87540
            Expression::Eq(_, box1, box2) => {
87540
                write!(f, "({} = {})", box1.clone(), box2.clone())
            }
19520
            Expression::Neq(_, box1, box2) => {
19520
                write!(f, "({} != {})", box1.clone(), box2.clone())
            }
5240
            Expression::Geq(_, box1, box2) => {
5240
                write!(f, "({} >= {})", box1.clone(), box2.clone())
            }
10360
            Expression::Leq(_, box1, box2) => {
10360
                write!(f, "({} <= {})", box1.clone(), box2.clone())
            }
1280
            Expression::Gt(_, box1, box2) => {
1280
                write!(f, "({} > {})", box1.clone(), box2.clone())
            }
19960
            Expression::Lt(_, box1, box2) => {
19960
                write!(f, "({} < {})", box1.clone(), box2.clone())
            }
20000
            Expression::FlatSumGeq(_, box1, box2) => {
20000
                write!(f, "SumGeq({}, {})", pretty_vec(box1), box2.clone())
            }
18800
            Expression::FlatSumLeq(_, box1, box2) => {
18800
                write!(f, "SumLeq({}, {})", pretty_vec(box1), box2.clone())
            }
11540
            Expression::FlatIneq(_, box1, box2, box3) => write!(
11540
                f,
                "Ineq({}, {}, {})",
11540
                box1.clone(),
11540
                box2.clone(),
11540
                box3.clone()
            ),
1080
            Expression::Flatten(_, n, m) => {
1080
                if let Some(n) = n {
                    write!(f, "flatten({n}, {m})")
                } else {
1080
                    write!(f, "flatten({m})")
                }
            }
15520
            Expression::AllDiff(_, e) => {
15520
                write!(f, "allDiff({e})")
            }
13160
            Expression::Bubble(_, box1, box2) => {
13160
                write!(f, "{{{} @ {}}}", box1.clone(), box2.clone())
            }
10300
            Expression::SafeDiv(_, box1, box2) => {
10300
                write!(f, "SafeDiv({}, {})", box1.clone(), box2.clone())
            }
3280
            Expression::UnsafeDiv(_, box1, box2) => {
3280
                write!(f, "UnsafeDiv({}, {})", box1.clone(), box2.clone())
            }
2720
            Expression::UnsafePow(_, box1, box2) => {
2720
                write!(f, "UnsafePow({}, {})", box1.clone(), box2.clone())
            }
5840
            Expression::SafePow(_, box1, box2) => {
5840
                write!(f, "SafePow({}, {})", box1.clone(), box2.clone())
            }
1680
            Expression::MinionDivEqUndefZero(_, box1, box2, box3) => {
1680
                write!(
1680
                    f,
                    "DivEq({}, {}, {})",
1680
                    box1.clone(),
1680
                    box2.clone(),
1680
                    box3.clone()
                )
            }
680
            Expression::MinionModuloEqUndefZero(_, box1, box2, box3) => {
680
                write!(
680
                    f,
                    "ModEq({}, {}, {})",
680
                    box1.clone(),
680
                    box2.clone(),
680
                    box3.clone()
                )
            }
1400
            Expression::FlatWatchedLiteral(_, x, l) => {
1400
                write!(f, "WatchedLiteral({x},{l})")
            }
5240
            Expression::MinionReify(_, box1, box2) => {
5240
                write!(f, "Reify({}, {})", box1.clone(), box2.clone())
            }
1040
            Expression::MinionReifyImply(_, box1, box2) => {
1040
                write!(f, "ReifyImply({}, {})", box1.clone(), box2.clone())
            }
360
            Expression::MinionWInIntervalSet(_, atom, intervals) => {
360
                let intervals = intervals.iter().join(",");
360
                write!(f, "__minion_w_inintervalset({atom},[{intervals}])")
            }
320
            Expression::MinionWInSet(_, atom, values) => {
320
                let values = values.iter().join(",");
320
                write!(f, "__minion_w_inset({atom},[{values}])")
            }
11700
            Expression::AuxDeclaration(_, reference, e) => {
11700
                write!(f, "{} =aux {}", reference, e.clone())
            }
1440
            Expression::UnsafeMod(_, a, b) => {
1440
                write!(f, "{} % {}", a.clone(), b.clone())
            }
4360
            Expression::SafeMod(_, a, b) => {
4360
                write!(f, "SafeMod({},{})", a.clone(), b.clone())
            }
12000
            Expression::Neg(_, a) => {
12000
                write!(f, "-({})", a.clone())
            }
2560
            Expression::Minus(_, a, b) => {
2560
                write!(f, "({} - {})", a.clone(), b.clone())
            }
1360
            Expression::FlatAllDiff(_, es) => {
1360
                write!(f, "__flat_alldiff({})", pretty_vec(es))
            }
440
            Expression::FlatAbsEq(_, a, b) => {
440
                write!(f, "AbsEq({},{})", a.clone(), b.clone())
            }
400
            Expression::FlatMinusEq(_, a, b) => {
400
                write!(f, "MinusEq({},{})", a.clone(), b.clone())
            }
620
            Expression::FlatProductEq(_, a, b, c) => {
620
                write!(
620
                    f,
                    "FlatProductEq({},{},{})",
620
                    a.clone(),
620
                    b.clone(),
620
                    c.clone()
                )
            }
1960
            Expression::FlatWeightedSumLeq(_, cs, vs, total) => {
1960
                write!(
1960
                    f,
                    "FlatWeightedSumLeq({},{},{})",
1960
                    pretty_vec(cs),
1960
                    pretty_vec(vs),
1960
                    total.clone()
                )
            }
1960
            Expression::FlatWeightedSumGeq(_, cs, vs, total) => {
1960
                write!(
1960
                    f,
                    "FlatWeightedSumGeq({},{},{})",
1960
                    pretty_vec(cs),
1960
                    pretty_vec(vs),
1960
                    total.clone()
                )
            }
800
            Expression::MinionPow(_, atom, atom1, atom2) => {
800
                write!(f, "MinionPow({atom},{atom1},{atom2})")
            }
1160
            Expression::MinionElementOne(_, atoms, atom, atom1) => {
1160
                let atoms = atoms.iter().join(",");
1160
                write!(f, "__minion_element_one([{atoms}],{atom},{atom1})")
            }
480
            Expression::ToInt(_, expr) => {
480
                write!(f, "toInt({expr})")
            }
            Expression::SATInt(_, encoding, bits, (min, max)) => {
                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})"),
560
            Expression::LexLt(_, a, b) => write!(f, "({a} <lex {b})"),
2800
            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})"),
80
            Expression::FlatLexLt(_, a, b) => {
80
                write!(f, "FlatLexLt({}, {})", pretty_vec(a), pretty_vec(b))
            }
80
            Expression::FlatLexLeq(_, a, b) => {
80
                write!(f, "FlatLexLeq({}, {})", pretty_vec(a), pretty_vec(b))
            }
        }
1562636
    }
}
impl Typeable for Expression {
159300
    fn return_type(&self) -> ReturnType {
159300
        match self {
            Expression::Union(_, subject, _) => ReturnType::Set(Box::new(subject.return_type())),
            Expression::Intersect(_, subject, _) => {
                ReturnType::Set(Box::new(subject.return_type()))
            }
200
            Expression::In(_, _, _) => ReturnType::Bool,
            Expression::Supset(_, _, _) => ReturnType::Bool,
            Expression::SupsetEq(_, _, _) => ReturnType::Bool,
            Expression::Subset(_, _, _) => ReturnType::Bool,
            Expression::SubsetEq(_, _, _) => ReturnType::Bool,
6300
            Expression::AbstractLiteral(_, lit) => lit.return_type(),
21280
            Expression::UnsafeIndex(_, subject, idx) | Expression::SafeIndex(_, subject, idx) => {
29700
                let subject_ty = subject.return_type();
29700
                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
28140
                        let mut elem_typ = subject_ty;
28140
                        let mut idx_len = idx.len();
56400
                        while idx_len > 0
41680
                            && let ReturnType::Matrix(new_elem_typ) = &elem_typ
28260
                        {
28260
                            elem_typ = *new_elem_typ.clone();
28260
                            idx_len -= 1;
28260
                        }
28140
                        elem_typ
                    }
                    // TODO: We can implement indexing for these eventually
1560
                    ReturnType::Record(_) | ReturnType::Tuple(_) => ReturnType::Unknown,
                    _ => bug!(
                        "Invalid indexing operation: expected the operand to be a collection, got {self}: {subject_ty}"
                    ),
                }
            }
120
            Expression::UnsafeSlice(_, subject, _) | Expression::SafeSlice(_, subject, _) => {
200
                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,
90920
            Expression::Atomic(_, atom) => atom.return_type(),
            Expression::Scope(_, scope) => scope.return_type(),
220
            Expression::Abs(_, _) => ReturnType::Int,
10200
            Expression::Sum(_, _) => ReturnType::Int,
2880
            Expression::Product(_, _) => ReturnType::Int,
400
            Expression::Min(_, _) => ReturnType::Int,
260
            Expression::Max(_, _) => ReturnType::Int,
60
            Expression::Not(_, _) => ReturnType::Bool,
120
            Expression::Or(_, _) => ReturnType::Bool,
660
            Expression::Imply(_, _, _) => ReturnType::Bool,
            Expression::Iff(_, _, _) => ReturnType::Bool,
1560
            Expression::And(_, _) => ReturnType::Bool,
2880
            Expression::Eq(_, _, _) => ReturnType::Bool,
420
            Expression::Neq(_, _, _) => ReturnType::Bool,
40
            Expression::Geq(_, _, _) => ReturnType::Bool,
300
            Expression::Leq(_, _, _) => ReturnType::Bool,
40
            Expression::Gt(_, _, _) => ReturnType::Bool,
120
            Expression::Lt(_, _, _) => ReturnType::Bool,
3560
            Expression::SafeDiv(_, _, _) => ReturnType::Int,
580
            Expression::UnsafeDiv(_, _, _) => ReturnType::Int,
            Expression::FlatAllDiff(_, _) => ReturnType::Bool,
180
            Expression::FlatSumGeq(_, _, _) => ReturnType::Bool,
            Expression::FlatSumLeq(_, _, _) => ReturnType::Bool,
            Expression::MinionDivEqUndefZero(_, _, _, _) => ReturnType::Bool,
180
            Expression::FlatIneq(_, _, _, _) => ReturnType::Bool,
480
            Expression::Flatten(_, _, matrix) => {
480
                let matrix_type = matrix.return_type();
480
                match matrix_type {
                    ReturnType::Matrix(_) => {
                        // unwrap until we get to innermost element
480
                        let mut elem_type = matrix_type;
960
                        while let ReturnType::Matrix(new_elem_type) = &elem_type {
480
                            elem_type = *new_elem_type.clone();
480
                        }
480
                        ReturnType::Matrix(Box::new(elem_type))
                    }
                    _ => bug!(
                        "Invalid indexing operation: expected the operand to be a collection, got {self}: {matrix_type}"
                    ),
                }
            }
60
            Expression::AllDiff(_, _) => ReturnType::Bool,
840
            Expression::Bubble(_, inner, _) => inner.return_type(),
            Expression::FlatWatchedLiteral(_, _, _) => ReturnType::Bool,
            Expression::MinionReify(_, _, _) => ReturnType::Bool,
            Expression::MinionReifyImply(_, _, _) => ReturnType::Bool,
            Expression::MinionWInIntervalSet(_, _, _) => ReturnType::Bool,
            Expression::MinionWInSet(_, _, _) => ReturnType::Bool,
            Expression::MinionElementOne(_, _, _, _) => ReturnType::Bool,
            Expression::AuxDeclaration(_, _, _) => ReturnType::Bool,
400
            Expression::UnsafeMod(_, _, _) => ReturnType::Int,
1660
            Expression::SafeMod(_, _, _) => ReturnType::Int,
            Expression::MinionModuloEqUndefZero(_, _, _, _) => ReturnType::Bool,
1660
            Expression::Neg(_, _) => ReturnType::Int,
360
            Expression::UnsafePow(_, _, _) => ReturnType::Int,
1440
            Expression::SafePow(_, _, _) => ReturnType::Int,
160
            Expression::Minus(_, _, _) => ReturnType::Int,
            Expression::FlatAbsEq(_, _, _) => ReturnType::Bool,
            Expression::FlatMinusEq(_, _, _) => ReturnType::Bool,
100
            Expression::FlatProductEq(_, _, _, _) => ReturnType::Bool,
            Expression::FlatWeightedSumLeq(_, _, _, _) => ReturnType::Bool,
            Expression::FlatWeightedSumGeq(_, _, _, _) => ReturnType::Bool,
            Expression::MinionPow(_, _, _, _) => ReturnType::Bool,
80
            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,
80
            Expression::LexLeq(..) => ReturnType::Bool,
            Expression::LexGeq(..) => ReturnType::Bool,
            Expression::FlatLexLt(..) => ReturnType::Bool,
            Expression::FlatLexLeq(..) => ReturnType::Bool,
        }
159300
    }
}
#[cfg(test)]
mod tests {
    use crate::matrix_expr;
    use super::*;
    #[test]
1
    fn test_domain_of_constant_sum() {
1
        let c1 = Expression::Atomic(Metadata::new(), Atom::Literal(Literal::Int(1)));
1
        let c2 = Expression::Atomic(Metadata::new(), Atom::Literal(Literal::Int(2)));
1
        let sum = Expression::Sum(Metadata::new(), Moo::new(matrix_expr![c1, c2]));
1
        assert_eq!(sum.domain_of(), Some(Domain::int(vec![Range::Single(3)])));
1
    }
    #[test]
1
    fn test_domain_of_constant_invalid_type() {
1
        let c1 = Expression::Atomic(Metadata::new(), Atom::Literal(Literal::Int(1)));
1
        let c2 = Expression::Atomic(Metadata::new(), Atom::Literal(Literal::Bool(true)));
1
        let sum = Expression::Sum(Metadata::new(), Moo::new(matrix_expr![c1, c2]));
1
        assert_eq!(sum.domain_of(), None);
1
    }
    #[test]
1
    fn test_domain_of_empty_sum() {
1
        let sum = Expression::Sum(Metadata::new(), Moo::new(matrix_expr![]));
1
        assert_eq!(sum.domain_of(), None);
1
    }
}