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; 112], 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
    /// `table([x1, x2, ...], [[r11, r12, ...], [r21, r22, ...], ...])`
282
    ///
283
    /// Represents a positive table constraint: the tuple `[x1, x2, ...]` must match one of the
284
    /// allowed rows.
285
    #[compatible(JsonInput)]
286
    Table(Metadata, Moo<Expression>, Moo<Expression>),
287
    /// Binary subtraction operator
288
    ///
289
    /// This is a parser-level construct, and is immediately normalised to `Sum([a,-b])`.
290
    /// TODO: make this compatible with Set Difference calculations - need to change return type and domain for this expression and write a set comprehension rule.
291
    /// have already edited minus_to_sum to prevent this from applying to sets
292
    #[compatible(JsonInput)]
293
    Minus(Metadata, Moo<Expression>, Moo<Expression>),
294

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
530
    #[compatible(JsonInput)]
531
    Inverse(Metadata, Moo<Expression>, Moo<Expression>),
532

            
533
    #[compatible(JsonInput)]
534
    Restrict(Metadata, Moo<Expression>, Moo<Expression>),
535

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

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

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

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

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

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

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

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

            
592
274846
    let expr = exprs.pop()?;
593
274844
    let dom = expr.domain_of()?;
594
273524
    let resolved = dom.resolve()?;
595
273524
    let GroundDomain::Int(ranges) = resolved.as_ref() else {
596
2
        return None;
597
    };
598

            
599
273522
    let (mut current_min, mut current_max) = range_vec_bounds_i32(ranges)?;
600

            
601
318762
    for expr in exprs {
602
318762
        let dom = expr.domain_of()?;
603
318682
        let resolved = dom.resolve()?;
604
318682
        let GroundDomain::Int(ranges) = resolved.as_ref() else {
605
            return None;
606
        };
607

            
608
318682
        let (min, max) = range_vec_bounds_i32(ranges)?;
609

            
610
        // all the possible new values for current_min / current_max
611
318682
        let minmax = op(min, current_max)?;
612
318682
        let minmin = op(min, current_min)?;
613
318682
        let maxmin = op(max, current_min)?;
614
318682
        let maxmax = op(max, current_max)?;
615
318682
        let vals = [minmax, minmin, maxmin, maxmax];
616

            
617
318682
        current_min = *vals
618
318682
            .iter()
619
318682
            .min()
620
318682
            .expect("vals iterator should not be empty, and should have a minimum.");
621
318682
        current_max = *vals
622
318682
            .iter()
623
318682
            .max()
624
318682
            .expect("vals iterator should not be empty, and should have a maximum.");
625
    }
626

            
627
273442
    if current_min == current_max {
628
176202
        Some(Domain::int(vec![Range::Single(current_min)]))
629
    } else {
630
97240
        Some(Domain::int(vec![Range::Bounded(current_min, current_max)]))
631
    }
632
282566
}
633

            
634
// Returns none if unbounded
635
592204
fn range_vec_bounds_i32(ranges: &Vec<Range<i32>>) -> Option<(i32, i32)> {
636
592204
    let mut min = i32::MAX;
637
592204
    let mut max = i32::MIN;
638
598324
    for r in ranges {
639
598324
        match r {
640
380364
            Range::Single(i) => {
641
380364
                if *i < min {
642
374244
                    min = *i;
643
374244
                }
644
380364
                if *i > max {
645
380364
                    max = *i;
646
380364
                }
647
            }
648
217960
            Range::Bounded(i, j) => {
649
217960
                if *i < min {
650
217960
                    min = *i;
651
217960
                }
652
217960
                if *j > max {
653
217960
                    max = *j;
654
217960
                }
655
            }
656
            Range::UnboundedR(_) | Range::UnboundedL(_) | Range::Unbounded => return None,
657
        }
658
    }
659
592204
    Some((min, max))
660
592204
}
661

            
662
impl Expression {
663
    /// Returns the possible values of the expression, recursing to leaf expressions
664
1173286
    pub fn domain_of(&self) -> Option<DomainPtr> {
665
1173286
        match self {
666
            Expression::Union(_, a, b) => {
667
                // Ascertain range
668
                let (a_attr, _) = a.domain_of()?.as_set()?;
669
                let (b_attr, _) = b.domain_of()?.as_set()?;
670
                let a_range = a_attr.resolve()?.size;
671
                let b_range = b_attr.resolve()?.size;
672
                let new_range = Range::spanning(&[a_range, b_range]);
673

            
674
                // Create
675
                Some(Domain::set(
676
                    SetAttr::new(new_range),
677
                    a.domain_of()?.union(&b.domain_of()?).ok()?,
678
                ))
679
            }
680
            Expression::Intersect(_, a, b) => {
681
                // thinking about Range::overlaps?
682

            
683
                Some(Domain::set(
684
                    SetAttr::<IntVal>::default(),
685
                    a.domain_of()?.intersect(&b.domain_of()?).ok()?,
686
                ))
687
            }
688
            Expression::In(_, _, _) => Some(Domain::bool()),
689
            Expression::Supset(_, _, _) => Some(Domain::bool()),
690
            Expression::SupsetEq(_, _, _) => Some(Domain::bool()),
691
            Expression::Subset(_, _, _) => Some(Domain::bool()),
692
            Expression::SubsetEq(_, _, _) => Some(Domain::bool()),
693
16120
            Expression::AbstractLiteral(_, abslit) => abslit.domain_of(),
694
            Expression::DominanceRelation(_, _) => Some(Domain::bool()),
695
            Expression::FromSolution(_, expr) => Some(expr.domain_of()),
696
            Expression::Metavar(_, _) => None,
697
            Expression::Comprehension(_, comprehension) => comprehension.domain_of(),
698
            Expression::AbstractComprehension(_, comprehension) => comprehension.domain_of(),
699
87740
            Expression::UnsafeIndex(_, matrix, _) | Expression::SafeIndex(_, matrix, _) => {
700
94060
                let dom = matrix.domain_of()?;
701
94060
                if let Some((elem_domain, _)) = dom.as_matrix() {
702
94060
                    return Some(elem_domain);
703
                }
704

            
705
                // may actually use the value in the future
706
                #[allow(clippy::redundant_pattern_matching)]
707
                if let Some(_) = dom.as_tuple() {
708
                    // TODO: We can implement proper indexing for tuples
709
                    return None;
710
                }
711

            
712
                // may actually use the value in the future
713
                #[allow(clippy::redundant_pattern_matching)]
714
                if let Some(_) = dom.as_record() {
715
                    // TODO: We can implement proper indexing for records
716
                    return None;
717
                }
718

            
719
                bug!("subject of an index operation should support indexing")
720
            }
721
            Expression::UnsafeSlice(_, matrix, indices)
722
160
            | Expression::SafeSlice(_, matrix, indices) => {
723
160
                let sliced_dimension = indices.iter().position(Option::is_none);
724

            
725
160
                let dom = matrix.domain_of()?;
726
160
                let Some((elem_domain, index_domains)) = dom.as_matrix() else {
727
                    bug!("subject of an index operation should be a matrix");
728
                };
729

            
730
160
                match sliced_dimension {
731
160
                    Some(dimension) => Some(Domain::matrix(
732
160
                        elem_domain,
733
160
                        vec![index_domains[dimension].clone()],
734
160
                    )),
735

            
736
                    // same as index
737
                    None => Some(elem_domain),
738
                }
739
            }
740
            Expression::InDomain(_, _, _) => Some(Domain::bool()),
741
781563
            Expression::Atomic(_, atom) => Some(atom.domain_of()),
742
36483
            Expression::Sum(_, e) => {
743
216644
                bounded_i32_domain_for_matrix_literal_monotonic(e, |x, y| Some(x + y))
744
            }
745
103360
            Expression::Product(_, e) => {
746
413600
                bounded_i32_domain_for_matrix_literal_monotonic(e, |x, y| Some(x * y))
747
            }
748
4240
            Expression::Min(_, e) => bounded_i32_domain_for_matrix_literal_monotonic(e, |x, y| {
749
4240
                Some(if x < y { x } else { y })
750
4240
            }),
751
2880
            Expression::Max(_, e) => bounded_i32_domain_for_matrix_literal_monotonic(e, |x, y| {
752
2880
                Some(if x > y { x } else { y })
753
2880
            }),
754
43960
            Expression::UnsafeDiv(_, a, b) => a
755
43960
                .domain_of()?
756
43960
                .resolve()?
757
43960
                .apply_i32(
758
                    // rust integer division is truncating; however, we want to always round down,
759
                    // including for negative numbers.
760
44580
                    |x, y| {
761
44580
                        if y != 0 {
762
44480
                            Some((x as f32 / y as f32).floor() as i32)
763
                        } else {
764
100
                            None
765
                        }
766
44580
                    },
767
43960
                    b.domain_of()?.resolve()?.as_ref(),
768
                )
769
43960
                .map(DomainPtr::from)
770
43960
                .ok(),
771
1380
            Expression::SafeDiv(_, a, b) => {
772
                // rust integer division is truncating; however, we want to always round down
773
                // including for negative numbers.
774
1380
                let domain = a
775
1380
                    .domain_of()?
776
1380
                    .resolve()?
777
1380
                    .apply_i32(
778
37940
                        |x, y| {
779
37940
                            if y != 0 {
780
34280
                                Some((x as f32 / y as f32).floor() as i32)
781
                            } else {
782
3660
                                None
783
                            }
784
37940
                        },
785
1380
                        b.domain_of()?.resolve()?.as_ref(),
786
                    )
787
                    .unwrap_or_else(|err| bug!("Got {err} when computing domain of {self}"));
788

            
789
1380
                if let GroundDomain::Int(ranges) = domain {
790
1380
                    let mut ranges = ranges;
791
1380
                    ranges.push(Range::Single(0));
792
1380
                    Some(Domain::int(ranges))
793
                } else {
794
                    bug!("Domain of {self} was not integer")
795
                }
796
            }
797
            Expression::UnsafeMod(_, a, b) => a
798
                .domain_of()?
799
                .resolve()?
800
                .apply_i32(
801
                    |x, y| if y != 0 { Some(x % y) } else { None },
802
                    b.domain_of()?.resolve()?.as_ref(),
803
                )
804
                .map(DomainPtr::from)
805
                .ok(),
806
440
            Expression::SafeMod(_, a, b) => {
807
440
                let domain = a
808
440
                    .domain_of()?
809
440
                    .resolve()?
810
440
                    .apply_i32(
811
12020
                        |x, y| if y != 0 { Some(x % y) } else { None },
812
440
                        b.domain_of()?.resolve()?.as_ref(),
813
                    )
814
                    .unwrap_or_else(|err| bug!("Got {err} when computing domain of {self}"));
815

            
816
440
                if let GroundDomain::Int(ranges) = domain {
817
440
                    let mut ranges = ranges;
818
440
                    ranges.push(Range::Single(0));
819
440
                    Some(Domain::int(ranges))
820
                } else {
821
                    bug!("Domain of {self} was not integer")
822
                }
823
            }
824
400
            Expression::SafePow(_, a, b) | Expression::UnsafePow(_, a, b) => a
825
400
                .domain_of()?
826
400
                .resolve()?
827
400
                .apply_i32(
828
10360
                    |x, y| {
829
10360
                        if (x != 0 || y != 0) && y >= 0 {
830
9960
                            Some(x.pow(y as u32))
831
                        } else {
832
400
                            None
833
                        }
834
10360
                    },
835
400
                    b.domain_of()?.resolve()?.as_ref(),
836
                )
837
400
                .map(DomainPtr::from)
838
400
                .ok(),
839
            Expression::Root(_, _) => None,
840
100
            Expression::Bubble(_, inner, _) => inner.domain_of(),
841
            Expression::AuxDeclaration(_, _, _) => Some(Domain::bool()),
842
1040
            Expression::And(_, _) => Some(Domain::bool()),
843
240
            Expression::Not(_, _) => Some(Domain::bool()),
844
20
            Expression::Or(_, _) => Some(Domain::bool()),
845
100
            Expression::Imply(_, _, _) => Some(Domain::bool()),
846
            Expression::Iff(_, _, _) => Some(Domain::bool()),
847
600
            Expression::Eq(_, _, _) => Some(Domain::bool()),
848
            Expression::Neq(_, _, _) => Some(Domain::bool()),
849
20
            Expression::Geq(_, _, _) => Some(Domain::bool()),
850
520
            Expression::Leq(_, _, _) => Some(Domain::bool()),
851
120
            Expression::Gt(_, _, _) => Some(Domain::bool()),
852
            Expression::Lt(_, _, _) => Some(Domain::bool()),
853
            Expression::FlatAbsEq(_, _, _) => Some(Domain::bool()),
854
20
            Expression::FlatSumGeq(_, _, _) => Some(Domain::bool()),
855
            Expression::FlatSumLeq(_, _, _) => Some(Domain::bool()),
856
            Expression::MinionDivEqUndefZero(_, _, _, _) => Some(Domain::bool()),
857
            Expression::MinionModuloEqUndefZero(_, _, _, _) => Some(Domain::bool()),
858
40
            Expression::FlatIneq(_, _, _, _) => Some(Domain::bool()),
859
200
            Expression::Flatten(_, n, m) => {
860
200
                if let Some(expr) = n {
861
                    if expr.return_type() == ReturnType::Int {
862
                        // TODO: handle flatten with depth argument
863
                        return None;
864
                    }
865
                } else {
866
                    // TODO: currently only works for matrices
867
200
                    let dom = m.domain_of()?.resolve()?;
868
200
                    let (val_dom, idx_doms) = match dom.as_ref() {
869
200
                        GroundDomain::Matrix(val, idx) => (val, idx),
870
                        _ => return None,
871
                    };
872
200
                    let num_elems = matrix::num_elements(idx_doms).ok()? as i32;
873

            
874
200
                    let new_index_domain = Domain::int(vec![Range::Bounded(1, num_elems)]);
875
200
                    return Some(Domain::matrix(
876
200
                        val_dom.clone().into(),
877
200
                        vec![new_index_domain],
878
200
                    ));
879
                }
880
                None
881
            }
882
            Expression::AllDiff(_, _) => Some(Domain::bool()),
883
            Expression::Table(_, _, _) => Some(Domain::bool()),
884
            Expression::FlatWatchedLiteral(_, _, _) => Some(Domain::bool()),
885
            Expression::MinionReify(_, _, _) => Some(Domain::bool()),
886
20
            Expression::MinionReifyImply(_, _, _) => Some(Domain::bool()),
887
            Expression::MinionWInIntervalSet(_, _, _) => Some(Domain::bool()),
888
            Expression::MinionWInSet(_, _, _) => Some(Domain::bool()),
889
            Expression::MinionElementOne(_, _, _, _) => Some(Domain::bool()),
890
1220
            Expression::Neg(_, x) => {
891
1220
                let dom = x.domain_of()?;
892
1220
                let mut ranges = dom.as_int()?;
893

            
894
520
                ranges = ranges
895
520
                    .into_iter()
896
520
                    .map(|r| match r {
897
80
                        Range::Single(x) => Range::Single(-x),
898
440
                        Range::Bounded(x, y) => Range::Bounded(-y, -x),
899
                        Range::UnboundedR(i) => Range::UnboundedL(-i),
900
                        Range::UnboundedL(i) => Range::UnboundedR(-i),
901
                        Range::Unbounded => Range::Unbounded,
902
520
                    })
903
520
                    .collect();
904

            
905
520
                Some(Domain::int(ranges))
906
            }
907
87860
            Expression::Minus(_, a, b) => a
908
87860
                .domain_of()?
909
87860
                .resolve()?
910
96000
                .apply_i32(|x, y| Some(x - y), b.domain_of()?.resolve()?.as_ref())
911
87860
                .map(DomainPtr::from)
912
87860
                .ok(),
913
            Expression::FlatAllDiff(_, _) => Some(Domain::bool()),
914
            Expression::FlatMinusEq(_, _, _) => Some(Domain::bool()),
915
            Expression::FlatProductEq(_, _, _, _) => Some(Domain::bool()),
916
            Expression::FlatWeightedSumLeq(_, _, _, _) => Some(Domain::bool()),
917
            Expression::FlatWeightedSumGeq(_, _, _, _) => Some(Domain::bool()),
918
580
            Expression::Abs(_, a) => a
919
580
                .domain_of()?
920
580
                .resolve()?
921
96860
                .apply_i32(|a, _| Some(a.abs()), a.domain_of()?.resolve()?.as_ref())
922
580
                .map(DomainPtr::from)
923
580
                .ok(),
924
            Expression::MinionPow(_, _, _, _) => Some(Domain::bool()),
925
420
            Expression::ToInt(_, _) => Some(Domain::int(vec![Range::Bounded(0, 1)])),
926
800
            Expression::SATInt(_, _, _, (low, high)) => {
927
800
                Some(Domain::int_ground(vec![Range::Bounded(*low, *high)]))
928
            }
929
            Expression::PairwiseSum(_, a, b) => a
930
                .domain_of()?
931
                .resolve()?
932
                .apply_i32(|a, b| Some(a + b), b.domain_of()?.resolve()?.as_ref())
933
                .map(DomainPtr::from)
934
                .ok(),
935
            Expression::PairwiseProduct(_, a, b) => a
936
                .domain_of()?
937
                .resolve()?
938
                .apply_i32(|a, b| Some(a * b), b.domain_of()?.resolve()?.as_ref())
939
                .map(DomainPtr::from)
940
                .ok(),
941
            Expression::Defined(_, function) => get_function_domain(function),
942
            Expression::Range(_, function) => get_function_codomain(function),
943
            Expression::Image(_, function, _) => get_function_codomain(function),
944
            Expression::ImageSet(_, function, _) => get_function_codomain(function),
945
            Expression::PreImage(_, function, _) => get_function_domain(function),
946
            Expression::Restrict(_, function, new_domain) => {
947
                let (attrs, _, codom) = function.domain_of()?.as_function()?;
948
                let new_dom = new_domain.domain_of()?;
949
                Some(Domain::function(attrs, new_dom, codom))
950
            }
951
            Expression::Inverse(..) => Some(Domain::bool()),
952
            Expression::LexLt(..) => Some(Domain::bool()),
953
            Expression::LexLeq(..) => Some(Domain::bool()),
954
            Expression::LexGt(..) => Some(Domain::bool()),
955
            Expression::LexGeq(..) => Some(Domain::bool()),
956
            Expression::FlatLexLt(..) => Some(Domain::bool()),
957
            Expression::FlatLexLeq(..) => Some(Domain::bool()),
958
        }
959
1173286
    }
960

            
961
    pub fn get_meta(&self) -> Metadata {
962
        let metas: VecDeque<Metadata> = self.children_bi();
963
        metas[0].clone()
964
    }
965

            
966
    pub fn set_meta(&self, meta: Metadata) {
967
        self.transform_bi(&|_| meta.clone());
968
    }
969

            
970
    /// Checks whether this expression is safe.
971
    ///
972
    /// An expression is unsafe if can be undefined, or if any of its children can be undefined.
973
    ///
974
    /// Unsafe expressions are (typically) prefixed with Unsafe in our AST, and can be made
975
    /// safe through the use of bubble rules.
976
31380
    pub fn is_safe(&self) -> bool {
977
        // TODO: memoise in Metadata
978
270300
        for expr in self.universe() {
979
270300
            match expr {
980
                Expression::UnsafeDiv(_, _, _)
981
                | Expression::UnsafeMod(_, _, _)
982
                | Expression::UnsafePow(_, _, _)
983
                | Expression::UnsafeIndex(_, _, _)
984
                | Expression::Bubble(_, _, _)
985
                | Expression::UnsafeSlice(_, _, _) => {
986
860
                    return false;
987
                }
988
269440
                _ => {}
989
            }
990
        }
991
30520
        true
992
31380
    }
993

            
994
    pub fn is_clean(&self) -> bool {
995
        let metadata = self.get_meta();
996
        metadata.clean
997
    }
998

            
999
    pub fn set_clean(&mut self, bool_value: bool) {
        let mut metadata = self.get_meta();
        metadata.clean = bool_value;
        self.set_meta(metadata);
    }
    /// True if the expression is an associative and commutative operator
2993200
    pub fn is_associative_commutative_operator(&self) -> bool {
2993200
        TryInto::<ACOperatorKind>::try_into(self).is_ok()
2993200
    }
    /// True if the expression is a matrix literal.
    ///
    /// This is true for both forms of matrix literals: those with elements of type [`Literal`] and
    /// [`Expression`].
3000
    pub fn is_matrix_literal(&self) -> bool {
        matches!(
3000
            self,
            Expression::AbstractLiteral(_, AbstractLiteral::Matrix(_, _))
                | Expression::Atomic(
                    _,
                    Atom::Literal(Literal::AbstractLiteral(AbstractLiteral::Matrix(_, _))),
                )
        )
3000
    }
    /// 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`.
25960
    pub fn identical_atom_to(&self, other: &Expression) -> bool {
25960
        let atom1: Result<&Atom, _> = self.try_into();
25960
        let atom2: Result<&Atom, _> = other.try_into();
25960
        if let (Ok(atom1), Ok(atom2)) = (atom1, atom2) {
1840
            atom2 == atom1
        } else {
24120
            false
        }
25960
    }
    /// 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.
1515710
    pub fn unwrap_list(&self) -> Option<Vec<Expression>> {
1194500
        match self {
1194500
            Expression::AbstractLiteral(_, matrix @ AbstractLiteral::Matrix(_, _)) => {
1194500
                matrix.unwrap_list().cloned()
            }
            Expression::Atomic(
                _,
5460
                Atom::Literal(Literal::AbstractLiteral(matrix @ AbstractLiteral::Matrix(_, _))),
5460
            ) => matrix.unwrap_list().map(|elems| {
3860
                elems
3860
                    .clone()
3860
                    .into_iter()
12280
                    .map(|x: Literal| Expression::Atomic(Metadata::new(), Atom::Literal(x)))
3860
                    .collect_vec()
3860
            }),
315750
            _ => None,
        }
1515710
    }
    /// 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.
1640963
    pub fn unwrap_matrix_unchecked(self) -> Option<(Vec<Expression>, DomainPtr)> {
847343
        match self {
847343
            Expression::AbstractLiteral(_, AbstractLiteral::Matrix(elems, domain)) => {
847343
                Some((elems, domain))
            }
            Expression::Atomic(
                _,
134280
                Atom::Literal(Literal::AbstractLiteral(AbstractLiteral::Matrix(elems, domain))),
            ) => Some((
134280
                elems
134280
                    .into_iter()
266200
                    .map(|x: Literal| Expression::Atomic(Metadata::new(), Atom::Literal(x)))
134280
                    .collect_vec(),
134280
                domain.into(),
            )),
659340
            _ => None,
        }
1640963
    }
    /// 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.
62524
    pub fn into_literal(self) -> Option<Literal> {
58684
        match self {
54464
            Expression::Atomic(_, Atom::Literal(lit)) => Some(lit),
            Expression::AbstractLiteral(_, abslit) => {
                Some(Literal::AbstractLiteral(abslit.into_literals()?))
            }
1820
            Expression::Neg(_, e) => {
1820
                let Literal::Int(i) = Moo::unwrap_or_clone(e).into_literal()? else {
                    bug!("negated literal should be an int");
                };
1820
                Some(Literal::Int(-i))
            }
6240
            _ => None,
        }
62524
    }
    /// If this expression is an associative-commutative operator, return its [ACOperatorKind].
3378320
    pub fn to_ac_operator_kind(&self) -> Option<ACOperatorKind> {
3378320
        TryFrom::try_from(self).ok()
3378320
    }
    /// Returns the categories of all sub-expressions of self.
22300
    pub fn universe_categories(&self) -> HashSet<Category> {
22300
        self.universe()
22300
            .into_iter()
220360
            .map(|x| x.category_of())
22300
            .collect()
22300
    }
}
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 = ();
95720
    fn try_from(value: &Expression) -> Result<Self, Self::Error> {
95720
        let Expression::Atomic(_, atom) = value else {
63320
            return Err(());
        };
32400
        let Atom::Literal(lit) = atom else {
32400
            return Err(());
        };
        let Literal::Int(i) = lit else {
            return Err(());
        };
        Ok(*i)
95720
    }
}
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 {
12008
    fn from(i: i32) -> Self {
12008
        Expression::Atomic(Metadata::new(), Atom::Literal(Literal::Int(i)))
12008
    }
}
impl From<bool> for Expression {
6370
    fn from(b: bool) -> Self {
6370
        Expression::Atomic(Metadata::new(), Atom::Literal(Literal::Bool(b)))
6370
    }
}
impl From<Atom> for Expression {
1180
    fn from(value: Atom) -> Self {
1180
        Expression::Atomic(Metadata::new(), value)
1180
    }
}
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 {
16340
    fn from(val: Moo<Expression>) -> Self {
16340
        val.as_ref().clone()
16340
    }
}
impl CategoryOf for Expression {
284960
    fn category_of(&self) -> Category {
        // take highest category of all the expressions children
1155980
        let category = self.cata(&move |x,children| {
1155980
            if let Some(max_category) = children.iter().max() {
                // if this expression contains subexpressions, return the maximum category of the
                // subexpressions
351080
                *max_category
            } else {
                // this expression has no children
804900
                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)
804900
                if !Biplate::<Model>::universe_bi(&x).is_empty() {
                    // assume that the category is decision
                    return Category::Decision;
804900
                }
                // if x contains atoms
805660
                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
804900
                && max_atom_category > max_category{
                    // update category
804900
                    max_category = max_atom_category;
804900
                }
                // if x contains declarationPtrs
804900
                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
611920
                && max_declaration_category > max_category{
                    // update category
                    max_category = max_declaration_category;
804900
                }
804900
                max_category
            }
1155980
        });
284960
        if cfg!(debug_assertions) {
284960
            trace!(
                category= %category,
                expression= %self,
                "Called Expression::category_of()"
            );
        };
284960
        category
284960
    }
}
impl Display for Expression {
9923552
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
9923552
        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())
            }
639160
            Expression::AbstractLiteral(_, l) => l.fmt(f),
24100
            Expression::Comprehension(_, c) => c.fmt(f),
80
            Expression::AbstractComprehension(_, c) => c.fmt(f),
268320
            Expression::UnsafeIndex(_, e1, e2) | Expression::SafeIndex(_, e1, e2) => {
395960
                write!(f, "{e1}{}", pretty_vec(e2))
            }
24880
            Expression::UnsafeSlice(_, e1, es) | Expression::SafeSlice(_, e1, es) => {
46080
                let args = es
46080
                    .iter()
91240
                    .map(|x| match x {
45160
                        Some(x) => format!("{x}"),
46080
                        None => "..".into(),
91240
                    })
46080
                    .join(",");
46080
                write!(f, "{e1}[{args}]")
            }
37600
            Expression::InDomain(_, e, domain) => {
37600
                write!(f, "__inDomain({e},{domain})")
            }
94124
            Expression::Root(_, exprs) => {
94124
                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}"),
7226828
            Expression::Atomic(_, atom) => atom.fmt(f),
2700
            Expression::Abs(_, a) => write!(f, "|{a}|"),
232720
            Expression::Sum(_, e) => {
232720
                write!(f, "sum({e})")
            }
61060
            Expression::Product(_, e) => {
61060
                write!(f, "product({e})")
            }
6300
            Expression::Min(_, e) => {
6300
                write!(f, "min({e})")
            }
5560
            Expression::Max(_, e) => {
5560
                write!(f, "max({e})")
            }
5980
            Expression::Not(_, expr_box) => {
5980
                write!(f, "!({})", expr_box.clone())
            }
46060
            Expression::Or(_, e) => {
46060
                write!(f, "or({e})")
            }
115980
            Expression::And(_, e) => {
115980
                write!(f, "and({e})")
            }
17800
            Expression::Imply(_, box1, box2) => {
17800
                write!(f, "({box1}) -> ({box2})")
            }
760
            Expression::Iff(_, box1, box2) => {
760
                write!(f, "({box1}) <-> ({box2})")
            }
204000
            Expression::Eq(_, box1, box2) => {
204000
                write!(f, "({} = {})", box1.clone(), box2.clone())
            }
57080
            Expression::Neq(_, box1, box2) => {
57080
                write!(f, "({} != {})", box1.clone(), box2.clone())
            }
43280
            Expression::Geq(_, box1, box2) => {
43280
                write!(f, "({} >= {})", box1.clone(), box2.clone())
            }
69400
            Expression::Leq(_, box1, box2) => {
69400
                write!(f, "({} <= {})", box1.clone(), box2.clone())
            }
2960
            Expression::Gt(_, box1, box2) => {
2960
                write!(f, "({} > {})", box1.clone(), box2.clone())
            }
24440
            Expression::Lt(_, box1, box2) => {
24440
                write!(f, "({} < {})", box1.clone(), box2.clone())
            }
46260
            Expression::FlatSumGeq(_, box1, box2) => {
46260
                write!(f, "SumGeq({}, {})", pretty_vec(box1), box2.clone())
            }
45040
            Expression::FlatSumLeq(_, box1, box2) => {
45040
                write!(f, "SumLeq({}, {})", pretty_vec(box1), box2.clone())
            }
15440
            Expression::FlatIneq(_, box1, box2, box3) => write!(
15440
                f,
                "Ineq({}, {}, {})",
15440
                box1.clone(),
15440
                box2.clone(),
15440
                box3.clone()
            ),
2080
            Expression::Flatten(_, n, m) => {
2080
                if let Some(n) = n {
                    write!(f, "flatten({n}, {m})")
                } else {
2080
                    write!(f, "flatten({m})")
                }
            }
17760
            Expression::AllDiff(_, e) => {
17760
                write!(f, "allDiff({e})")
            }
480
            Expression::Table(_, tuple_expr, rows_expr) => {
480
                write!(f, "table({tuple_expr}, {rows_expr})")
            }
27120
            Expression::Bubble(_, box1, box2) => {
27120
                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())
            }
2240
            Expression::UnsafePow(_, box1, box2) => {
2240
                write!(f, "UnsafePow({}, {})", box1.clone(), box2.clone())
            }
2900
            Expression::SafePow(_, box1, box2) => {
2900
                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()
                )
            }
720
            Expression::MinionModuloEqUndefZero(_, box1, box2, box3) => {
720
                write!(
720
                    f,
                    "ModEq({}, {}, {})",
720
                    box1.clone(),
720
                    box2.clone(),
720
                    box3.clone()
                )
            }
1520
            Expression::FlatWatchedLiteral(_, x, l) => {
1520
                write!(f, "WatchedLiteral({x},{l})")
            }
14240
            Expression::MinionReify(_, box1, box2) => {
14240
                write!(f, "Reify({}, {})", box1.clone(), box2.clone())
            }
3420
            Expression::MinionReifyImply(_, box1, box2) => {
3420
                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}])")
            }
35160
            Expression::AuxDeclaration(_, reference, e) => {
35160
                write!(f, "{} =aux {}", reference, e.clone())
            }
1680
            Expression::UnsafeMod(_, a, b) => {
1680
                write!(f, "{} % {}", a.clone(), b.clone())
            }
4440
            Expression::SafeMod(_, a, b) => {
4440
                write!(f, "SafeMod({},{})", a.clone(), b.clone())
            }
24240
            Expression::Neg(_, a) => {
24240
                write!(f, "-({})", a.clone())
            }
65140
            Expression::Minus(_, a, b) => {
65140
                write!(f, "({} - {})", a.clone(), b.clone())
            }
8320
            Expression::FlatAllDiff(_, es) => {
8320
                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())
            }
740
            Expression::FlatProductEq(_, a, b, c) => {
740
                write!(
740
                    f,
                    "FlatProductEq({},{},{})",
740
                    a.clone(),
740
                    b.clone(),
740
                    c.clone()
                )
            }
9120
            Expression::FlatWeightedSumLeq(_, cs, vs, total) => {
9120
                write!(
9120
                    f,
                    "FlatWeightedSumLeq({},{},{})",
9120
                    pretty_vec(cs),
9120
                    pretty_vec(vs),
9120
                    total.clone()
                )
            }
9340
            Expression::FlatWeightedSumGeq(_, cs, vs, total) => {
9340
                write!(
9340
                    f,
                    "FlatWeightedSumGeq({},{},{})",
9340
                    pretty_vec(cs),
9340
                    pretty_vec(vs),
9340
                    total.clone()
                )
            }
640
            Expression::MinionPow(_, atom, atom1, atom2) => {
640
                write!(f, "MinionPow({atom},{atom1},{atom2})")
            }
7400
            Expression::MinionElementOne(_, atoms, atom, atom1) => {
7400
                let atoms = atoms.iter().join(",");
7400
                write!(f, "__minion_element_one([{atoms}],{atom},{atom1})")
            }
480
            Expression::ToInt(_, expr) => {
480
                write!(f, "toInt({expr})")
            }
178260
            Expression::SATInt(_, encoding, bits, (min, max)) => {
178260
                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})"),
17540
            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))
            }
160
            Expression::FlatLexLeq(_, a, b) => {
160
                write!(f, "FlatLexLeq({}, {})", pretty_vec(a), pretty_vec(b))
            }
        }
9923552
    }
}
impl Typeable for Expression {
357520
    fn return_type(&self) -> ReturnType {
357520
        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,
12360
            Expression::AbstractLiteral(_, lit) => lit.return_type(),
34740
            Expression::UnsafeIndex(_, subject, idx) | Expression::SafeIndex(_, subject, idx) => {
61340
                let subject_ty = subject.return_type();
61340
                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
59780
                        let mut elem_typ = subject_ty;
59780
                        let mut idx_len = idx.len();
119680
                        while idx_len > 0
71300
                            && let ReturnType::Matrix(new_elem_typ) = &elem_typ
59900
                        {
59900
                            elem_typ = *new_elem_typ.clone();
59900
                            idx_len -= 1;
59900
                        }
59780
                        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}"
                    ),
                }
            }
960
            Expression::UnsafeSlice(_, subject, _) | Expression::SafeSlice(_, subject, _) => {
960
                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,
215800
            Expression::Atomic(_, atom) => atom.return_type(),
220
            Expression::Abs(_, _) => ReturnType::Int,
41380
            Expression::Sum(_, _) => ReturnType::Int,
3360
            Expression::Product(_, _) => ReturnType::Int,
440
            Expression::Min(_, _) => ReturnType::Int,
420
            Expression::Max(_, _) => ReturnType::Int,
60
            Expression::Not(_, _) => ReturnType::Bool,
180
            Expression::Or(_, _) => ReturnType::Bool,
440
            Expression::Imply(_, _, _) => ReturnType::Bool,
            Expression::Iff(_, _, _) => ReturnType::Bool,
1220
            Expression::And(_, _) => ReturnType::Bool,
3120
            Expression::Eq(_, _, _) => ReturnType::Bool,
180
            Expression::Neq(_, _, _) => ReturnType::Bool,
40
            Expression::Geq(_, _, _) => ReturnType::Bool,
960
            Expression::Leq(_, _, _) => ReturnType::Bool,
40
            Expression::Gt(_, _, _) => ReturnType::Bool,
            Expression::Lt(_, _, _) => ReturnType::Bool,
3560
            Expression::SafeDiv(_, _, _) => ReturnType::Int,
580
            Expression::UnsafeDiv(_, _, _) => ReturnType::Int,
            Expression::FlatAllDiff(_, _) => ReturnType::Bool,
20
            Expression::FlatSumGeq(_, _, _) => ReturnType::Bool,
            Expression::FlatSumLeq(_, _, _) => ReturnType::Bool,
            Expression::MinionDivEqUndefZero(_, _, _, _) => ReturnType::Bool,
40
            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}"
                    ),
                }
            }
100
            Expression::AllDiff(_, _) => ReturnType::Bool,
            Expression::Table(_, _, _) => ReturnType::Bool,
760
            Expression::Bubble(_, inner, _) => inner.return_type(),
            Expression::FlatWatchedLiteral(_, _, _) => ReturnType::Bool,
            Expression::MinionReify(_, _, _) => ReturnType::Bool,
20
            Expression::MinionReifyImply(_, _, _) => ReturnType::Bool,
            Expression::MinionWInIntervalSet(_, _, _) => ReturnType::Bool,
            Expression::MinionWInSet(_, _, _) => ReturnType::Bool,
            Expression::MinionElementOne(_, _, _, _) => ReturnType::Bool,
            Expression::AuxDeclaration(_, _, _) => ReturnType::Bool,
420
            Expression::UnsafeMod(_, _, _) => ReturnType::Int,
1700
            Expression::SafeMod(_, _, _) => ReturnType::Int,
            Expression::MinionModuloEqUndefZero(_, _, _, _) => ReturnType::Bool,
1940
            Expression::Neg(_, _) => ReturnType::Int,
240
            Expression::UnsafePow(_, _, _) => ReturnType::Int,
1360
            Expression::SafePow(_, _, _) => ReturnType::Int,
380
            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,
80
            Expression::ToInt(_, _) => ReturnType::Int,
2200
            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,
920
            Expression::LexLeq(..) => ReturnType::Bool,
            Expression::LexGeq(..) => ReturnType::Bool,
            Expression::FlatLexLt(..) => ReturnType::Bool,
            Expression::FlatLexLeq(..) => ReturnType::Bool,
        }
357520
    }
}
#[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
    }
}