1
use funcmap::FuncMap;
2
use itertools::Itertools;
3
use serde::{Deserialize, Serialize};
4
use std::cmp::Ordering;
5
use std::fmt::{Debug, Display, Formatter};
6
use std::hash::Hash;
7
use ustr::Ustr;
8

            
9
use super::collection_domains::{SizeBounds, bounded_set};
10
use super::eval::eval_constant;
11

            
12
use super::{
13
    Atom, Domain, DomainPtr, Expression, GroundDomain, Moo, PartitionAttr, PermutationAttr, Range,
14
    ReturnType, SetAttr, Typeable, domains::HasDomain, domains::Int, records::Field,
15
};
16
use crate::ast::domains::{MSetAttr, SequenceAttr};
17
use crate::ast::enumerated::EnumVariant;
18
use crate::ast::pretty::pretty_vec;
19
use crate::bug;
20
use crate::bug_assert;
21
use polyquine::Quine;
22
use uniplate::{Biplate, Tree, Uniplate};
23

            
24
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Uniplate, Hash, Quine)]
25
#[uniplate(walk_into=[AbstractLiteral<Literal>])]
26
#[biplate(to=Atom)]
27
#[biplate(to=AbstractLiteral<Literal>)]
28
#[biplate(to=AbstractLiteral<Expression>)]
29
#[biplate(to=Field<Literal>)]
30
#[biplate(to=Field<Expression>)]
31
#[biplate(to=Expression)]
32
#[path_prefix(conjure_cp::ast)]
33
/// A literal value, equivalent to constants in Conjure.
34
pub enum Literal {
35
    Int(i32),
36
    Bool(bool),
37
    EnumVariant(EnumVariant),
38
    Unnamed(crate::ast::unnamed::UnnamedValue),
39
    //abstract literal variant ends in Literal, but that's ok
40
    #[allow(clippy::enum_variant_names)]
41
    AbstractLiteral(AbstractLiteral<Literal>),
42
}
43

            
44
impl HasDomain for Literal {
45
39676811
    fn domain_of(&self) -> DomainPtr {
46
39676811
        match self {
47
36704608
            Literal::Int(i) => Domain::int(vec![Range::Single(*i)]),
48
1210715
            Literal::Bool(_) => Domain::bool(),
49
            Literal::EnumVariant(ev) => {
50
474
                Domain::enumerated_ground(ev.ty.clone(), vec![Range::Single(ev.variant)])
51
            }
52
            Literal::Unnamed(value) => {
53
                Moo::new(crate::ast::GroundDomain::UnnamedType(value.ty.clone())).into()
54
            }
55
1761014
            Literal::AbstractLiteral(abstract_literal) => abstract_literal.domain_of(),
56
        }
57
39676811
    }
58
}
59

            
60
impl Literal {
61
    /// Compare values using Essence-aware value ordering.
62
    ///
63
    /// Booleans and integers use their natural order, tuple-like values use
64
    /// lexicographic order, and sets use lexicographic occurrence order over
65
    /// ascending element values (`false < true`).
66
771555928
    pub fn essence_cmp(&self, other: &Self) -> Ordering {
67
771555928
        match (self, other) {
68
            (Literal::Unnamed(lhs), Literal::Unnamed(rhs)) => {
69
30
                (&lhs.ty.name, lhs.ty.size, lhs.value).cmp(&(&rhs.ty.name, rhs.ty.size, rhs.value))
70
            }
71
44548637
            (Literal::Bool(lhs), Literal::Bool(rhs)) => lhs.cmp(rhs),
72
569665222
            (Literal::Int(lhs), Literal::Int(rhs)) => lhs.cmp(rhs),
73
6
            (Literal::EnumVariant(lhs), Literal::EnumVariant(rhs)) => (
74
6
                &lhs.ty.name,
75
6
                &lhs.ty.variants,
76
6
                lhs.variant,
77
6
            )
78
6
                .cmp(&(&rhs.ty.name, &rhs.ty.variants, rhs.variant)),
79
            (Literal::AbstractLiteral(lhs), Literal::AbstractLiteral(rhs)) => {
80
157342033
                abstract_literal_essence_cmp(lhs, rhs)
81
            }
82
            _ => literal_kind(self).cmp(&literal_kind(other)),
83
        }
84
771555928
    }
85
}
86

            
87
fn literal_kind(literal: &Literal) -> u8 {
88
    match literal {
89
        Literal::Bool(_) => 0,
90
        Literal::Int(_) => 1,
91
        Literal::AbstractLiteral(_) => 2,
92
        Literal::EnumVariant(_) => 3,
93
        Literal::Unnamed(_) => 4,
94
    }
95
}
96

            
97
157342033
fn abstract_literal_essence_cmp(
98
157342033
    lhs: &AbstractLiteral<Literal>,
99
157342033
    rhs: &AbstractLiteral<Literal>,
100
157342033
) -> Ordering {
101
157342033
    match (lhs, rhs) {
102
22603875
        (AbstractLiteral::Set(lhs), AbstractLiteral::Set(rhs)) => set_essence_cmp(lhs, rhs),
103
4200686
        (AbstractLiteral::MSet(lhs), AbstractLiteral::MSet(rhs)) => sorted_literals_cmp(lhs, rhs),
104
        (AbstractLiteral::Matrix(lhs, _), AbstractLiteral::Matrix(rhs, _))
105
        | (AbstractLiteral::Tuple(lhs), AbstractLiteral::Tuple(rhs))
106
        | (AbstractLiteral::Sequence(lhs), AbstractLiteral::Sequence(rhs)) => {
107
119243304
            literal_slice_cmp(lhs, rhs)
108
        }
109
3950268
        (AbstractLiteral::Record(lhs), AbstractLiteral::Record(rhs)) => lhs
110
3950268
            .iter()
111
3950268
            .zip(rhs)
112
6386248
            .find_map(|(lhs, rhs)| {
113
6386248
                let ordering = lhs.name.to_string().cmp(&rhs.name.to_string());
114
6386248
                (ordering != Ordering::Equal)
115
6386248
                    .then_some(ordering)
116
6386248
                    .or_else(|| {
117
6386248
                        let ordering = lhs.value.essence_cmp(&rhs.value);
118
6386248
                        (ordering != Ordering::Equal).then_some(ordering)
119
6386248
                    })
120
6386248
            })
121
1564105
            .unwrap_or_else(|| lhs.len().cmp(&rhs.len())),
122
406038
        (AbstractLiteral::Function(lhs), AbstractLiteral::Function(rhs)) => lhs
123
406038
            .iter()
124
406038
            .zip(rhs)
125
680791
            .find_map(|((lhs_from, lhs_to), (rhs_from, rhs_to))| {
126
680791
                let ordering = lhs_from.essence_cmp(rhs_from);
127
680791
                (ordering != Ordering::Equal)
128
680791
                    .then_some(ordering)
129
651434
                    .or_else(|| {
130
651434
                        let ordering = lhs_to.essence_cmp(rhs_to);
131
651434
                        (ordering != Ordering::Equal).then_some(ordering)
132
651434
                    })
133
680791
            })
134
149048
            .unwrap_or_else(|| lhs.len().cmp(&rhs.len())),
135
6534180
        (AbstractLiteral::Variant(lhs), AbstractLiteral::Variant(rhs)) => lhs
136
6534180
            .name
137
6534180
            .to_string()
138
6534180
            .cmp(&rhs.name.to_string())
139
3583321
            .then_with(|| lhs.value.essence_cmp(&rhs.value)),
140
        (AbstractLiteral::Partition(lhs), AbstractLiteral::Partition(rhs))
141
        | (AbstractLiteral::Relation(lhs), AbstractLiteral::Relation(rhs))
142
403682
        | (AbstractLiteral::Permutation(lhs), AbstractLiteral::Permutation(rhs)) => lhs
143
403682
            .iter()
144
403682
            .zip(rhs)
145
562092
            .find_map(|(lhs, rhs)| {
146
562092
                let ordering = literal_slice_cmp(lhs, rhs);
147
562092
                (ordering != Ordering::Equal).then_some(ordering)
148
562092
            })
149
13516
            .unwrap_or_else(|| lhs.len().cmp(&rhs.len())),
150
        _ => abstract_literal_kind(lhs).cmp(&abstract_literal_kind(rhs)),
151
    }
152
157342033
}
153

            
154
fn abstract_literal_kind(literal: &AbstractLiteral<Literal>) -> u8 {
155
    match literal {
156
        AbstractLiteral::Set(_) => 0,
157
        AbstractLiteral::MSet(_) => 1,
158
        AbstractLiteral::Matrix(..) => 2,
159
        AbstractLiteral::Tuple(_) => 3,
160
        AbstractLiteral::Record(_) => 4,
161
        AbstractLiteral::Sequence(_) => 5,
162
        AbstractLiteral::Function(_) => 6,
163
        AbstractLiteral::Variant(_) => 7,
164
        AbstractLiteral::Partition(_) => 8,
165
        AbstractLiteral::Relation(_) => 9,
166
        AbstractLiteral::Permutation(_) => 10,
167
    }
168
}
169

            
170
119805396
fn literal_slice_cmp(lhs: &[Literal], rhs: &[Literal]) -> Ordering {
171
119805396
    lhs.iter()
172
119805396
        .zip(rhs)
173
220258267
        .find_map(|(lhs, rhs)| {
174
220258267
            let ordering = lhs.essence_cmp(rhs);
175
220258267
            (ordering != Ordering::Equal).then_some(ordering)
176
220258267
        })
177
27433701
        .unwrap_or_else(|| lhs.len().cmp(&rhs.len()))
178
119805396
}
179

            
180
4200686
fn sorted_literals_cmp(lhs: &[Literal], rhs: &[Literal]) -> Ordering {
181
4200686
    let mut lhs = lhs.iter().collect::<Vec<_>>();
182
4200686
    let mut rhs = rhs.iter().collect::<Vec<_>>();
183
7300004
    lhs.sort_by(|lhs, rhs| lhs.essence_cmp(rhs));
184
7834320
    rhs.sort_by(|lhs, rhs| lhs.essence_cmp(rhs));
185
4200686
    lhs.iter()
186
4200686
        .zip(&rhs)
187
6555477
        .find_map(|(lhs, rhs)| {
188
6555477
            let ordering = lhs.essence_cmp(rhs);
189
6555477
            (ordering != Ordering::Equal).then_some(ordering)
190
6555477
        })
191
1485644
        .unwrap_or_else(|| lhs.len().cmp(&rhs.len()))
192
4200686
}
193

            
194
/// Compare sets as occurrence vectors over the ordered union of their elements.
195
22603875
fn set_essence_cmp(lhs: &[Literal], rhs: &[Literal]) -> Ordering {
196
22603875
    let mut lhs = lhs.iter().collect::<Vec<_>>();
197
22603875
    let mut rhs = rhs.iter().collect::<Vec<_>>();
198
22603875
    lhs.sort_by(|lhs, rhs| lhs.essence_cmp(rhs));
199
22603875
    rhs.sort_by(|lhs, rhs| lhs.essence_cmp(rhs));
200

            
201
22603875
    let (mut lhs_index, mut rhs_index) = (0, 0);
202
33525275
    while lhs_index < lhs.len() && rhs_index < rhs.len() {
203
25320686
        match lhs[lhs_index].essence_cmp(rhs[rhs_index]) {
204
            Ordering::Equal => {
205
10921400
                lhs_index += 1;
206
10921400
                rhs_index += 1;
207
            }
208
            // `lhs` contains the least differing element and `rhs` does not.
209
7605106
            Ordering::Less => return Ordering::Greater,
210
            // `rhs` contains the least differing element and `lhs` does not.
211
6794180
            Ordering::Greater => return Ordering::Less,
212
        }
213
    }
214
8204589
    match (lhs_index < lhs.len(), rhs_index < rhs.len()) {
215
2898377
        (false, false) => Ordering::Equal,
216
3561838
        (true, false) => Ordering::Greater,
217
1744374
        (false, true) => Ordering::Less,
218
        (true, true) => unreachable!(),
219
    }
220
22603875
}
221

            
222
// make possible values of an AbstractLiteral a closed world to make the trait bounds more sane (particularly in Uniplate instances!!)
223
pub trait AbstractLiteralValue:
224
    Clone + Eq + PartialEq + Display + Uniplate + Biplate<Field<Self>> + 'static
225
{
226
    type Dom: Clone
227
        + Eq
228
        + PartialEq
229
        + Debug
230
        + Display
231
        + Quine
232
        + From<GroundDomain>
233
        + Into<DomainPtr>;
234

            
235
    /// Returns whether `domain` is the implicit one-based list index domain.
236
    fn has_implied_list_domain(domain: &Self::Dom) -> bool;
237
}
238
impl AbstractLiteralValue for Expression {
239
    type Dom = DomainPtr;
240

            
241
587845017
    fn has_implied_list_domain(domain: &Self::Dom) -> bool {
242
587845017
        let Domain::Ground(domain) = domain.as_ref() else {
243
            return false;
244
        };
245
587845017
        matches!(domain.as_ref(), GroundDomain::Int(ranges, _) if ranges.as_slice() == [Range::UnboundedR(1)])
246
587845017
    }
247
}
248
impl AbstractLiteralValue for Literal {
249
    type Dom = Moo<GroundDomain>;
250

            
251
3394112
    fn has_implied_list_domain(domain: &Self::Dom) -> bool {
252
3394112
        matches!(domain.as_ref(), GroundDomain::Int(ranges, _) if ranges.as_slice() == [Range::UnboundedR(1)])
253
3394112
    }
254
}
255

            
256
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Quine)]
257
#[path_prefix(conjure_cp::ast)]
258
pub enum AbstractLiteral<T: AbstractLiteralValue> {
259
    Set(Vec<T>),
260

            
261
    MSet(Vec<T>),
262

            
263
    /// A 1 dimensional matrix slice with an index domain.
264
    Matrix(Vec<T>, T::Dom),
265

            
266
    // a tuple of literals
267
    Tuple(Vec<T>),
268

            
269
    Record(Vec<Field<T>>),
270

            
271
    Sequence(Vec<T>),
272

            
273
    Function(Vec<(T, T)>),
274

            
275
    // Variants only contain one of their name-domain pairs
276
    Variant(Moo<Field<T>>),
277

            
278
    // A list of partitions, each part has a set of values
279
    Partition(Vec<Vec<T>>),
280
    Relation(Vec<Vec<T>>),
281

            
282
    /// Cycle notation for a permutation: each inner vec is one cycle. Unlike `Partition`, this is
283
    /// *sparse* -- any element of the permutation's domain not mentioned in any cycle is an
284
    /// implicit fixed point (maps to itself), rather than every element needing to be covered.
285
    Permutation(Vec<Vec<T>>),
286
}
287

            
288
// TODO: use HasDomain instead once Expression::domain_of returns Domain not Option<Domain>
289
1142397
fn union_item_domains(item_domains: Vec<DomainPtr>, literal_kind: &str) -> Option<DomainPtr> {
290
1142397
    let mut item_domain_iter = item_domains.into_iter();
291
1142397
    let first_item = item_domain_iter.next()?;
292

            
293
    Some(
294
1072461
        item_domain_iter
295
2715174
            .try_fold(first_item, |x, y| x.union(&y))
296
            .unwrap_or_else(|error| {
297
                bug!(
298
                    "taking the union of all item domains of a {literal_kind} literal should succeed: {error}"
299
                )
300
            }),
301
    )
302
1142397
}
303

            
304
impl AbstractLiteral<Expression> {
305
1479283
    pub fn domain_of(&self) -> Option<DomainPtr> {
306
1479283
        match self {
307
            AbstractLiteral::Set(items) => {
308
243301
                if items.is_empty() {
309
1
                    return Some(Domain::set(
310
1
                        SetAttr::new_size(0),
311
1
                        Domain::empty(ReturnType::Unknown),
312
1
                    ));
313
243300
                }
314
                // ensure that all items have a domain, or return None
315
243300
                let item_domains: Vec<DomainPtr> = items
316
243300
                    .iter()
317
671980
                    .map(|x| x.domain_of())
318
                    .collect::<Option<Vec<DomainPtr>>>()?;
319

            
320
                // union all item domains together
321
243300
                let item_domain = union_item_domains(item_domains, "set")?;
322

            
323
243300
                let values = items.iter().map(eval_constant).collect::<Option<Vec<_>>>();
324
243300
                let high = i64::try_from(items.len()).ok()?;
325
243300
                let bounds = match values {
326
                    Some(values) => {
327
243238
                        let n = i64::try_from(distinct_literal_count(&values)).ok()?;
328
243238
                        SizeBounds::new(n, Some(n))
329
                    }
330
62
                    None => SizeBounds::new(1, Some(high)),
331
                };
332
243300
                Some(bounded_set(bounds, item_domain))
333
            }
334

            
335
            AbstractLiteral::MSet(items) => {
336
33050
                if items.is_empty() {
337
10976
                    return Some(Domain::mset(
338
10976
                        MSetAttr::new(Range::Single(0), Range::Single(0)),
339
10976
                        Domain::empty(ReturnType::Unknown),
340
10976
                    ));
341
22074
                }
342
22074
                let cardinality = i32::try_from(items.len()).ok()?;
343
                // ensure that all items have a domain, or return None
344
22074
                let item_domains: Vec<DomainPtr> = items
345
22074
                    .iter()
346
44210
                    .map(|x| x.domain_of())
347
                    .collect::<Option<Vec<DomainPtr>>>()?;
348

            
349
                // union all item domains together
350
22074
                let item_domain = union_item_domains(item_domains, "mset")?;
351

            
352
22074
                let occurrence = if cardinality == 0 {
353
                    Range::Single(0)
354
                } else {
355
22074
                    Range::Bounded(1, cardinality)
356
                };
357
22074
                Some(Domain::mset(
358
22074
                    MSetAttr::new(Range::Single(cardinality), occurrence),
359
22074
                    item_domain,
360
22074
                ))
361
            }
362

            
363
            AbstractLiteral::Sequence(elems) => {
364
90024
                let item_domains: Vec<DomainPtr> = elems
365
90024
                    .iter()
366
41819
                    .map(|x| x.domain_of())
367
                    .collect::<Option<Vec<DomainPtr>>>()?;
368

            
369
                // Get the union of all domains in the sequence.
370
                // i.e. if <(1..3), (1..3), (5), (8..9)> then seq dom is (1..3, 5, 8..9)
371
90024
                let item_domain = union_item_domains(item_domains, "sequence")?;
372

            
373
                // The literal's own length is its size: without it nothing downstream can tell
374
                // how many positions the sequence has.
375
20460
                let size = Range::Single(i32::try_from(elems.len()).ok()?);
376
20460
                Some(Domain::sequence(
377
20460
                    SequenceAttr::<Int> {
378
20460
                        size,
379
20460
                        ..SequenceAttr::default()
380
20460
                    },
381
20460
                    item_domain,
382
20460
                ))
383
            }
384

            
385
            AbstractLiteral::Partition(items) => {
386
                // Flatten the Vec<Vec< into a single vec
387
                // ensure that all elemes in each part have a domain, or return None
388

            
389
434
                let item_domains: Vec<DomainPtr> = items
390
434
                    .iter()
391
434
                    .flatten()
392
775
                    .map(|x| x.domain_of())
393
                    .collect::<Option<Vec<DomainPtr>>>()?;
394

            
395
                // union all item domains together
396
434
                let item_domain = union_item_domains(item_domains, "partition")?;
397

            
398
403
                Some(Domain::partition(
399
403
                    PartitionAttr::<Int>::default(),
400
403
                    item_domain,
401
403
                ))
402
            }
403

            
404
            AbstractLiteral::Permutation(cycles) => {
405
                // Flatten the Vec<Vec< into a single vec; unlike partition, elements not
406
                // mentioned in any cycle are implicit fixed points, so an empty literal (or one
407
                // with no domain-bearing elements) has no way to infer an inner domain.
408
22227
                let item_domains: Vec<DomainPtr> = cycles
409
22227
                    .iter()
410
22227
                    .flatten()
411
66836
                    .map(|x| x.domain_of())
412
                    .collect::<Option<Vec<DomainPtr>>>()?;
413

            
414
22227
                let item_domain = union_item_domains(item_domains, "permutation")?;
415

            
416
22165
                Some(Domain::permutation(
417
22165
                    PermutationAttr::<Int>::default(),
418
22165
                    item_domain,
419
22165
                ))
420
            }
421

            
422
            AbstractLiteral::Matrix(items, _) => {
423
764400
                let item_domains = items
424
764400
                    .iter()
425
2962077
                    .map(|x| x.domain_of())
426
62
                    .collect::<Option<Vec<DomainPtr>>>()?;
427

            
428
                // union all item domains together
429
764338
                let mut item_domain = union_item_domains(item_domains, "matrix")?;
430

            
431
764059
                let mut new_index_domain = vec![];
432

            
433
                // flatten index domains of n-d matrix into list
434
764059
                let mut matrix = self;
435
840285
                while let AbstractLiteral::Matrix(elems, idx) = matrix {
436
                    bug_assert!(
437
840285
                        idx.as_matrix().is_none(),
438
                        "n-dimensional matrix literals should be represented as a matrix inside a matrix, got {idx}"
439
                    );
440
840285
                    new_index_domain.push(idx.clone());
441
                    let Some(Expression::AbstractLiteral(_, inner @ AbstractLiteral::Matrix(..))) =
442
840285
                        elems.first()
443
                    else {
444
764059
                        break;
445
                    };
446
76226
                    matrix = inner;
447
                }
448
                // Each flattened literal dimension has already contributed to the row domain.
449
                // Peel those dimensions so they are not represented twice. Matrix-valued
450
                // expression leaves retain their own domains.
451
764059
                let mut remaining = new_index_domain.len() - 1;
452
840285
                while remaining > 0 {
453
76226
                    let (inner, indices) = item_domain.as_matrix()?;
454
76226
                    if indices.is_empty() {
455
                        return None;
456
76226
                    }
457
76226
                    remaining = remaining.checked_sub(indices.len())?;
458
76226
                    item_domain = inner;
459
                }
460
764059
                Some(Domain::matrix(item_domain, new_index_domain))
461
            }
462
286446
            AbstractLiteral::Tuple(items) => Some(Domain::tuple(
463
286446
                items
464
286446
                    .iter()
465
286446
                    .map(Expression::domain_of)
466
286446
                    .collect::<Option<Vec<_>>>()?,
467
            )),
468
9114
            AbstractLiteral::Record(items) => Some(Domain::record(
469
9114
                items
470
9114
                    .iter()
471
18228
                    .map(|field| {
472
                        Some(super::Field {
473
18228
                            name: field.name.clone(),
474
18228
                            value: field.value.domain_of()?,
475
                        })
476
18228
                    })
477
                    .collect::<Option<Vec<_>>>()?,
478
            )),
479
25575
            AbstractLiteral::Function(_) => None,
480
62
            AbstractLiteral::Variant(_) => None,
481
4650
            AbstractLiteral::Relation(_) => None,
482
        }
483
1479283
    }
484
}
485

            
486
5092930
pub(super) fn distinct_literal_count(items: &[Literal]) -> usize {
487
5092930
    let mut sorted = items.iter().collect::<Vec<_>>();
488
11187530
    sorted.sort_by(|a, b| a.essence_cmp(b));
489
10468609
    sorted.dedup_by(|a, b| a.essence_cmp(b).is_eq());
490
5092930
    sorted.len()
491
5092930
}
492

            
493
impl HasDomain for AbstractLiteral<Literal> {
494
1761014
    fn domain_of(&self) -> DomainPtr {
495
1761014
        let domain = Domain::from_literal_vec(&[Literal::AbstractLiteral(self.clone())])
496
1761014
            .expect("abstract literals should be correctly typed");
497
1761014
        match self {
498
            AbstractLiteral::Set(items) => {
499
146625
                let (_, inner) = domain.as_set().expect("set literal domain");
500
                let n =
501
146625
                    i64::try_from(distinct_literal_count(items)).expect("literal fits in memory");
502
146625
                bounded_set(SizeBounds::new(n, Some(n)), inner)
503
            }
504
            AbstractLiteral::MSet(items) => {
505
259005
                let (_, inner) = domain.as_mset().expect("multiset literal domain");
506
259005
                let n = i32::try_from(items.len()).expect("literal cardinality fits i32");
507
259005
                let occurrence = if n == 0 {
508
86335
                    Range::Single(0)
509
                } else {
510
172670
                    Range::Bounded(1, n)
511
                };
512
259005
                Domain::mset(MSetAttr::new(Range::Single(n), occurrence), inner)
513
            }
514
1355384
            _ => domain,
515
        }
516
1761014
    }
517
}
518

            
519
impl Typeable for AbstractLiteral<Expression> {
520
2380466
    fn return_type(&self) -> ReturnType {
521
2380466
        match self {
522
252990
            AbstractLiteral::Set(items) if items.is_empty() => {
523
                ReturnType::Set(Box::new(ReturnType::Unknown))
524
            }
525
            AbstractLiteral::Set(items) => {
526
252990
                let item_type = items[0].return_type();
527

            
528
                // if any items do not have a type, return none.
529
669741
                let item_types: Vec<ReturnType> = items.iter().map(|x| x.return_type()).collect();
530

            
531
                bug_assert!(
532
669741
                    item_types.iter().all(|x| x == &item_type),
533
                    "all items in a set should have the same type"
534
                );
535

            
536
252990
                ReturnType::Set(Box::new(item_type))
537
            }
538
32922
            AbstractLiteral::MSet(items) if items.is_empty() => {
539
10974
                ReturnType::MSet(Box::new(ReturnType::Unknown))
540
            }
541
            AbstractLiteral::MSet(items) => {
542
21948
                let item_type = items[0].return_type();
543

            
544
                // if any items do not have a type, return none.
545
43896
                let item_types: Vec<ReturnType> = items.iter().map(|x| x.return_type()).collect();
546

            
547
                bug_assert!(
548
43896
                    item_types.iter().all(|x| x == &item_type),
549
                    "all items in a set should have the same type"
550
                );
551

            
552
21948
                ReturnType::MSet(Box::new(item_type))
553
            }
554
45043
            AbstractLiteral::Sequence(items) if items.is_empty() => {
555
18476
                ReturnType::Sequence(Box::new(ReturnType::Unknown))
556
            }
557
            AbstractLiteral::Sequence(items) => {
558
26567
                let item_type = items[0].return_type();
559

            
560
                // if any items do not have a type, return none.
561
53537
                let item_types: Vec<ReturnType> = items.iter().map(|x| x.return_type()).collect();
562

            
563
                bug_assert!(
564
53537
                    item_types.iter().all(|x| x == &item_type),
565
                    "all items in a sequence should have the same type"
566
                );
567

            
568
26567
                ReturnType::Sequence(Box::new(item_type))
569
            }
570
899
            AbstractLiteral::Partition(items) if items.is_empty() || items[0].is_empty() => {
571
                ReturnType::Partition(Box::new(ReturnType::Unknown))
572
            }
573
            AbstractLiteral::Partition(items) => {
574
899
                let item_type = items[0][0].return_type();
575

            
576
                // if any items do not have a type, return none.
577
                let item_types: Vec<ReturnType> =
578
1085
                    items.iter().flatten().map(|x| x.return_type()).collect();
579

            
580
                bug_assert!(
581
1085
                    item_types.iter().all(|x| x == &item_type),
582
                    "all items in every part of a partition should have the same type"
583
                );
584

            
585
899
                ReturnType::Partition(Box::new(item_type))
586
            }
587
17484
            AbstractLiteral::Permutation(items) if items.is_empty() || items[0].is_empty() => {
588
31
                ReturnType::Permutation(Box::new(ReturnType::Unknown))
589
            }
590
            AbstractLiteral::Permutation(items) => {
591
17453
                let item_type = items[0][0].return_type();
592

            
593
                let item_types: Vec<ReturnType> =
594
52700
                    items.iter().flatten().map(|x| x.return_type()).collect();
595

            
596
                bug_assert!(
597
52700
                    item_types.iter().all(|x| x == &item_type),
598
                    "all items in every cycle of a permutation should have the same type"
599
                );
600

            
601
17453
                ReturnType::Permutation(Box::new(item_type))
602
            }
603
1494946
            AbstractLiteral::Matrix(items, _) if items.is_empty() => {
604
40331
                ReturnType::Matrix(Box::new(ReturnType::Unknown))
605
            }
606
            AbstractLiteral::Matrix(items, _) => {
607
1454615
                let item_type = items[0].return_type();
608

            
609
                // if any items do not have a type, return none.
610
10874045
                let item_types: Vec<ReturnType> = items.iter().map(|x| x.return_type()).collect();
611

            
612
                bug_assert!(
613
10874045
                    item_types.iter().all(|x| x == &item_type),
614
                    "all items in a matrix should have the same type. items: {items} types: {types:#?}",
615
                    items = pretty_vec(items),
616
                    types = items
617
                        .iter()
618
                        .map(|x| x.return_type())
619
                        .collect::<Vec<ReturnType>>()
620
                );
621

            
622
1454615
                ReturnType::Matrix(Box::new(item_type))
623
            }
624
            AbstractLiteral::Tuple(items) => {
625
499695
                let mut item_types = vec![];
626
499695
                for item in items {
627
999582
                    item_types.push(item.return_type());
628
                }
629
499695
                ReturnType::Tuple(item_types)
630
            }
631
            AbstractLiteral::Record(items) => {
632
13578
                let mut item_types = vec![];
633
13578
                for item in items {
634
27156
                    item_types.push(item.clone().func_map(|x| x.return_type()));
635
                }
636
13578
                item_types.sort();
637
13578
                ReturnType::Record(item_types)
638
            }
639
            AbstractLiteral::Function(items) => {
640
2511
                if items.is_empty() {
641
31
                    return ReturnType::Function(
642
31
                        Box::new(ReturnType::Unknown),
643
31
                        Box::new(ReturnType::Unknown),
644
31
                    );
645
2480
                }
646

            
647
                // Check that all items have the same return type
648
2480
                let (x1, y1) = &items[0];
649
2480
                let (t1, t2) = (x1.return_type(), y1.return_type());
650
2480
                for (x, y) in items {
651
7223
                    let (tx, ty) = (x.return_type(), y.return_type());
652
7223
                    if tx != t1 {
653
                        bug!("Expected {t1}, got {x}: {tx}");
654
7223
                    }
655
7223
                    if ty != t2 {
656
                        bug!("Expected {t2}, got {y}: {ty}");
657
7223
                    }
658
                }
659

            
660
2480
                ReturnType::Function(Box::new(t1), Box::new(t2))
661
            }
662
            AbstractLiteral::Variant(item) => {
663
                // Variants hold multiple possible types. In the case of a literal we know which type it chose
664
18135
                ReturnType::Variant(vec![item.as_ref().clone().func_map(|x| x.return_type())])
665
            }
666
            AbstractLiteral::Relation(items) => {
667
2263
                if items.is_empty() {
668
                    return ReturnType::Relation(vec![ReturnType::Unknown]);
669
2263
                }
670
2263
                let mut item_types = vec![];
671
2263
                let x1 = &items[0];
672
2263
                let size = x1.len();
673
2263
                for item in x1 {
674
4526
                    item_types.push(item.return_type());
675
                }
676
2263
                for x in items {
677
6789
                    if x.len() != size {
678
                        let strs = item_types.iter().map(|x| format!("{}", x)).join(",");
679
                        bug!("Expected ({strs}) with length {size}, got size {}", x.len());
680
6789
                    }
681
6789
                    for i in 1..size {
682
6789
                        if let Some(new_type) = x.get(i)
683
6789
                            && let Some(old_type) = item_types.get(i)
684
6789
                            && new_type.return_type() != *old_type
685
                        {
686
                            bug!("Expected {old_type}, got {new_type}");
687
6789
                        }
688
                    }
689
                }
690
2263
                ReturnType::Relation(item_types)
691
            }
692
        }
693
2380466
    }
694
}
695

            
696
impl<T> AbstractLiteral<T>
697
where
698
    T: AbstractLiteralValue,
699
{
700
    /// Creates a matrix with elements `elems`, with domain `int(1..)`.
701
    ///
702
    /// This acts as a variable sized list.
703
640271532
    pub fn matrix_implied_indices(elems: Vec<T>) -> Self {
704
640271532
        AbstractLiteral::Matrix(
705
640271532
            elems,
706
640271532
            GroundDomain::Int(vec![Range::UnboundedR(1)], None).into(),
707
640271532
        )
708
640271532
    }
709

            
710
    /// If the AbstractLiteral is a list, returns its elements.
711
    ///
712
    /// A list is any a matrix with the domain `int(1..)`. This includes matrix literals without
713
    /// any explicitly specified domain.
714
582158190
    pub fn unwrap_list(&self) -> Option<&Vec<T>> {
715
582158190
        let AbstractLiteral::Matrix(elems, domain) = self else {
716
            return None;
717
        };
718

            
719
582158190
        T::has_implied_list_domain(domain).then_some(elems)
720
582158190
    }
721

            
722
    /// If this abstract literal is a list, consumes it and returns its elements.
723
9080939
    pub fn into_list(self) -> Option<Vec<T>> {
724
9080939
        let AbstractLiteral::Matrix(elems, domain) = self else {
725
            return None;
726
        };
727

            
728
9080939
        T::has_implied_list_domain(&domain).then_some(elems)
729
9080939
    }
730
}
731

            
732
impl<T> Display for AbstractLiteral<T>
733
where
734
    T: AbstractLiteralValue,
735
{
736
40771669
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
737
40771669
        match self {
738
            AbstractLiteral::Set(elems) => {
739
8806042
                let elems_str: String = elems.iter().map(|x| format!("{x}")).join(",");
740
4579294
                write!(f, "{{{elems_str}}}")
741
            }
742
            AbstractLiteral::MSet(elems) => {
743
2803020
                let elems_str: String = elems.iter().map(|x| format!("{x}")).join(",");
744
1233490
                write!(f, "mset({elems_str})")
745
            }
746
            AbstractLiteral::Matrix(elems, index_domain) => {
747
73513619
                let elems_str: String = elems.iter().map(|x| format!("{x}")).join(",");
748
25882691
                write!(f, "[{elems_str};{index_domain}]")
749
            }
750
            AbstractLiteral::Tuple(elems) => {
751
12620384
                let elems_str: String = elems.iter().map(|x| format!("{x}")).join(",");
752
6309628
                write!(f, "({elems_str})")
753
            }
754
            AbstractLiteral::Sequence(elems) => {
755
891320
                let elems_str: String = elems.iter().map(|x| format!("{x}")).join(",");
756
726549
                write!(f, "sequence({elems_str})")
757
            }
758
            AbstractLiteral::Partition(parts) => {
759
3844
                let elems_str: String = parts
760
3844
                    .iter()
761
7440
                    .map(|inner| {
762
13702
                        let elems_str = inner.iter().map(|x| format!("{x}")).join(",");
763
7440
                        format!("{{{}}}", elems_str)
764
7440
                    })
765
3844
                    .join(", ");
766

            
767
3844
                write!(f, "partition({elems_str})")
768
            }
769
            AbstractLiteral::Permutation(cycles) => {
770
103292
                let cycles_str: String = cycles
771
103292
                    .iter()
772
111848
                    .map(|cycle| {
773
326554
                        let elems_str = cycle.iter().map(|x| format!("{x}")).join(",");
774
111848
                        format!("({elems_str})")
775
111848
                    })
776
103292
                    .join("");
777

            
778
103292
                write!(f, "permutation{cycles_str}")
779
            }
780
            AbstractLiteral::Record(entries) => {
781
979290
                let entries_str: String = entries
782
979290
                    .iter()
783
1958580
                    .map(|entry| format!("{} = {}", entry.name, entry.value))
784
979290
                    .join(",");
785
979290
                write!(f, "record {{{entries_str}}}")
786
            }
787
            AbstractLiteral::Function(entries) => {
788
277326
                let entries_str: String = entries
789
277326
                    .iter()
790
610824
                    .map(|entry| format!("{} --> {}", entry.0, entry.1))
791
277326
                    .join(",");
792
277326
                write!(f, "function({entries_str})")
793
            }
794
            AbstractLiteral::Variant(entry) => {
795
643591
                write!(f, "variant{{{} = {}}}", entry.name, entry.value)
796
            }
797
            AbstractLiteral::Relation(elems) => {
798
32674
                let elems_str: String = elems
799
32674
                    .iter()
800
237708
                    .map(|x| format!("({})", x.iter().map(|x| format!("{x}")).join(",")))
801
32674
                    .join(",");
802
32674
                write!(f, "relation({elems_str})")
803
            }
804
        }
805
40771669
    }
806
}
807

            
808
impl<T> Uniplate for AbstractLiteral<T>
809
where
810
    T: AbstractLiteralValue + Biplate<AbstractLiteral<T>>,
811
{
812
3615738
    fn uniplate(&self) -> (Tree<Self>, Box<dyn Fn(Tree<Self>) -> Self>) {
813
        // walking into T
814
3615738
        match self {
815
            AbstractLiteral::Set(vec) => {
816
418340
                let (f1_tree, f1_ctx) = <_ as Biplate<AbstractLiteral<T>>>::biplate(vec);
817
418340
                (f1_tree, Box::new(move |x| AbstractLiteral::Set(f1_ctx(x))))
818
            }
819
            AbstractLiteral::MSet(vec) => {
820
142008
                let (f1_tree, f1_ctx) = <_ as Biplate<AbstractLiteral<T>>>::biplate(vec);
821
142008
                (f1_tree, Box::new(move |x| AbstractLiteral::MSet(f1_ctx(x))))
822
            }
823
            AbstractLiteral::Matrix(elems, index_domain) => {
824
1972806
                let index_domain = index_domain.clone();
825
1972806
                let (f1_tree, f1_ctx) = <_ as Biplate<AbstractLiteral<T>>>::biplate(elems);
826
                (
827
1972806
                    f1_tree,
828
1972806
                    Box::new(move |x| AbstractLiteral::Matrix(f1_ctx(x), index_domain.clone())),
829
                )
830
            }
831
            AbstractLiteral::Sequence(vec) => {
832
100640
                let (f1_tree, f1_ctx) = <_ as Biplate<AbstractLiteral<T>>>::biplate(vec);
833
                (
834
100640
                    f1_tree,
835
100640
                    Box::new(move |x| AbstractLiteral::Sequence(f1_ctx(x))),
836
                )
837
            }
838
            AbstractLiteral::Tuple(elems) => {
839
752208
                let (f1_tree, f1_ctx) = <_ as Biplate<AbstractLiteral<T>>>::biplate(elems);
840
                (
841
752208
                    f1_tree,
842
752208
                    Box::new(move |x| AbstractLiteral::Tuple(f1_ctx(x))),
843
                )
844
            }
845
            AbstractLiteral::Record(entries) => {
846
122688
                let (f1_tree, f1_ctx) = <_ as Biplate<AbstractLiteral<T>>>::biplate(entries);
847
                (
848
122688
                    f1_tree,
849
122688
                    Box::new(move |x| AbstractLiteral::Record(f1_ctx(x))),
850
                )
851
            }
852
            AbstractLiteral::Function(entries) => {
853
34712
                let entry_count = entries.len();
854
34712
                let flattened: Vec<T> = entries
855
34712
                    .iter()
856
75744
                    .flat_map(|(lhs, rhs)| [lhs.clone(), rhs.clone()])
857
                    .collect();
858

            
859
                let (f1_tree, f1_ctx) =
860
34712
                    <Vec<T> as Biplate<AbstractLiteral<T>>>::biplate(&flattened);
861
                (
862
34712
                    f1_tree,
863
34712
                    Box::new(move |x| {
864
34712
                        let rebuilt = f1_ctx(x);
865
34712
                        assert_eq!(
866
34712
                            rebuilt.len(),
867
34712
                            entry_count * 2,
868
                            "number of function literal children should remain unchanged"
869
                        );
870

            
871
34712
                        let mut iter = rebuilt.into_iter();
872
34712
                        let mut pairs = Vec::with_capacity(entry_count);
873
110456
                        while let (Some(lhs), Some(rhs)) = (iter.next(), iter.next()) {
874
75744
                            pairs.push((lhs, rhs));
875
                        }
876

            
877
34712
                        AbstractLiteral::Function(pairs)
878
34712
                    }),
879
                )
880
            }
881
            AbstractLiteral::Variant(entries) => {
882
64640
                let (f1_tree, f1_ctx) = <_ as Biplate<AbstractLiteral<T>>>::biplate(entries);
883
                (
884
64640
                    f1_tree,
885
64640
                    Box::new(move |x| AbstractLiteral::Variant(f1_ctx(x))),
886
                )
887
            }
888
            AbstractLiteral::Relation(elems) => {
889
2992
                let (f1_tree, f1_ctx) = <_ as Biplate<AbstractLiteral<T>>>::biplate(elems);
890
                (
891
2992
                    f1_tree,
892
2992
                    Box::new(move |x| AbstractLiteral::Relation(f1_ctx(x))),
893
                )
894
            }
895
            AbstractLiteral::Partition(elems) => {
896
384
                let (f1_tree, f1_ctx) = <_ as Biplate<AbstractLiteral<T>>>::biplate(elems);
897
                (
898
384
                    f1_tree,
899
384
                    Box::new(move |x| AbstractLiteral::Partition(f1_ctx(x))),
900
                )
901
            }
902
            AbstractLiteral::Permutation(elems) => {
903
4320
                let (f1_tree, f1_ctx) = <_ as Biplate<AbstractLiteral<T>>>::biplate(elems);
904
                (
905
4320
                    f1_tree,
906
4320
                    Box::new(move |x| AbstractLiteral::Permutation(f1_ctx(x))),
907
                )
908
            }
909
        }
910
3615738
    }
911
}
912

            
913
impl<U, To> Biplate<To> for AbstractLiteral<U>
914
where
915
    To: Uniplate,
916
    U: AbstractLiteralValue + Biplate<AbstractLiteral<U>> + Biplate<To>,
917
    Field<U>: Biplate<AbstractLiteral<U>> + Biplate<To>,
918
{
919
2293235264
    fn biplate(&self) -> (Tree<To>, Box<dyn Fn(Tree<To>) -> Self>) {
920
2293235264
        if std::any::TypeId::of::<To>() == std::any::TypeId::of::<AbstractLiteral<U>>() {
921
            // To ==From => return One(self)
922

            
923
            unsafe {
924
                // SAFETY: asserted the type equality above
925
10063907
                let self_to = std::mem::transmute::<&AbstractLiteral<U>, &To>(self).clone();
926
10063907
                let tree = Tree::One(self_to);
927
10063907
                let ctx = Box::new(move |x| {
928
10063902
                    let Tree::One(x) = x else {
929
                        panic!();
930
                    };
931

            
932
10063902
                    std::mem::transmute::<&To, &AbstractLiteral<U>>(&x).clone()
933
10063902
                });
934

            
935
10063907
                (tree, ctx)
936
            }
937
        } else {
938
            // walking into T
939
2283171357
            match self {
940
                AbstractLiteral::Set(vec) => {
941
10270248
                    let (f1_tree, f1_ctx) = <_ as Biplate<To>>::biplate(vec);
942
10270248
                    (f1_tree, Box::new(move |x| AbstractLiteral::Set(f1_ctx(x))))
943
                }
944
                AbstractLiteral::MSet(vec) => {
945
2117145
                    let (f1_tree, f1_ctx) = <_ as Biplate<To>>::biplate(vec);
946
2117145
                    (f1_tree, Box::new(move |x| AbstractLiteral::MSet(f1_ctx(x))))
947
                }
948
                AbstractLiteral::Matrix(elems, index_domain) => {
949
2227927735
                    let index_domain = index_domain.clone();
950
2227927735
                    let (f1_tree, f1_ctx) = <Vec<U> as Biplate<To>>::biplate(elems);
951
                    (
952
2227927735
                        f1_tree,
953
2227927735
                        Box::new(move |x| AbstractLiteral::Matrix(f1_ctx(x), index_domain.clone())),
954
                    )
955
                }
956
                AbstractLiteral::Sequence(vec) => {
957
6594878
                    let (f1_tree, f1_ctx) = <_ as Biplate<To>>::biplate(vec);
958
                    (
959
6594878
                        f1_tree,
960
6594878
                        Box::new(move |x| AbstractLiteral::Sequence(f1_ctx(x))),
961
                    )
962
                }
963
                AbstractLiteral::Tuple(elems) => {
964
31151900
                    let (f1_tree, f1_ctx) = <_ as Biplate<To>>::biplate(elems);
965
                    (
966
31151900
                        f1_tree,
967
31151900
                        Box::new(move |x| AbstractLiteral::Tuple(f1_ctx(x))),
968
                    )
969
                }
970
                AbstractLiteral::Record(entries) => {
971
2541287
                    let (f1_tree, f1_ctx) = <_ as Biplate<To>>::biplate(entries);
972
                    (
973
2541287
                        f1_tree,
974
2541287
                        Box::new(move |x| AbstractLiteral::Record(f1_ctx(x))),
975
                    )
976
                }
977
                AbstractLiteral::Function(entries) => {
978
465124
                    let entry_count = entries.len();
979
465124
                    let flattened: Vec<U> = entries
980
465124
                        .iter()
981
1062897
                        .flat_map(|(lhs, rhs)| [lhs.clone(), rhs.clone()])
982
                        .collect();
983

            
984
465124
                    let (f1_tree, f1_ctx) = <Vec<U> as Biplate<To>>::biplate(&flattened);
985
                    (
986
465124
                        f1_tree,
987
465124
                        Box::new(move |x| {
988
148087
                            let rebuilt = f1_ctx(x);
989
148087
                            assert_eq!(
990
148087
                                rebuilt.len(),
991
148087
                                entry_count * 2,
992
                                "number of function literal children should remain unchanged"
993
                            );
994

            
995
148087
                            let mut iter = rebuilt.into_iter();
996
148087
                            let mut pairs = Vec::with_capacity(entry_count);
997
482329
                            while let (Some(lhs), Some(rhs)) = (iter.next(), iter.next()) {
998
334242
                                pairs.push((lhs, rhs));
999
                            }
148087
                            AbstractLiteral::Function(pairs)
148087
                        }),
                    )
                }
                AbstractLiteral::Variant(entries) => {
1885947
                    let (f1_tree, f1_ctx) = <_ as Biplate<To>>::biplate(entries);
                    (
1885947
                        f1_tree,
1885947
                        Box::new(move |x| AbstractLiteral::Variant(f1_ctx(x))),
                    )
                }
                AbstractLiteral::Relation(elems) => {
48856
                    let (f1_tree, f1_ctx) = <_ as Biplate<To>>::biplate(elems);
                    (
48856
                        f1_tree,
48856
                        Box::new(move |x| AbstractLiteral::Relation(f1_ctx(x))),
                    )
                }
                AbstractLiteral::Partition(elems) => {
7688
                    let (f1_tree, f1_ctx) = <_ as Biplate<To>>::biplate(elems);
                    (
7688
                        f1_tree,
7688
                        Box::new(move |x| AbstractLiteral::Partition(f1_ctx(x))),
                    )
                }
                AbstractLiteral::Permutation(elems) => {
160549
                    let (f1_tree, f1_ctx) = <_ as Biplate<To>>::biplate(elems);
                    (
160549
                        f1_tree,
160549
                        Box::new(move |x| AbstractLiteral::Permutation(f1_ctx(x))),
                    )
                }
            }
        }
2293235264
    }
666554789
    fn children_bi_count(&self) -> usize {
        // Manual `biplate` (not derive): delegate counts to the plated containers so wide
        // matrices/lists stay O(1) instead of materialising `children_bi`.
666554789
        if std::any::TypeId::of::<To>() == std::any::TypeId::of::<AbstractLiteral<U>>() {
            return 1;
666554789
        }
666554789
        match self {
            AbstractLiteral::Set(v)
            | AbstractLiteral::MSet(v)
            | AbstractLiteral::Sequence(v)
            | AbstractLiteral::Tuple(v)
666120665
            | AbstractLiteral::Matrix(v, _) => <Vec<U> as Biplate<To>>::children_bi_count(v),
            AbstractLiteral::Record(entries) => {
39990
                <Vec<Field<U>> as Biplate<To>>::children_bi_count(entries)
            }
            AbstractLiteral::Variant(entry) => {
313875
                <Moo<Field<U>> as Biplate<To>>::children_bi_count(entry)
            }
            AbstractLiteral::Relation(elems)
            | AbstractLiteral::Partition(elems)
            | AbstractLiteral::Permutation(elems) => {
66681
                <Vec<Vec<U>> as Biplate<To>>::children_bi_count(elems)
            }
13578
            AbstractLiteral::Function(_) => <Self as Biplate<To>>::children_bi(self).len(),
        }
666554789
    }
666554789
    fn try_replace_child_at_bi(&mut self, index: usize, child: To) -> bool {
        // Same as `children_bi_count`: keep in-place updates for owned vectors (lee-distance).
666554789
        if std::any::TypeId::of::<To>() == std::any::TypeId::of::<AbstractLiteral<U>>() {
            if index != 0 {
                return false;
            }
            // SAFETY: TypeId equality means To and AbstractLiteral<U> are the same type.
            unsafe {
                let child_as_self = std::mem::transmute_copy::<To, AbstractLiteral<U>>(&child);
                std::mem::forget(child);
                *self = child_as_self;
            }
            return true;
666554789
        }
666554789
        match self {
            AbstractLiteral::Set(v)
            | AbstractLiteral::MSet(v)
            | AbstractLiteral::Sequence(v)
            | AbstractLiteral::Tuple(v)
            | AbstractLiteral::Matrix(v, _) => {
666120665
                <Vec<U> as Biplate<To>>::try_replace_child_at_bi(v, index, child)
            }
            AbstractLiteral::Record(entries) => {
39990
                <Vec<Field<U>> as Biplate<To>>::try_replace_child_at_bi(entries, index, child)
            }
            AbstractLiteral::Variant(entry) => {
313875
                <Moo<Field<U>> as Biplate<To>>::try_replace_child_at_bi(entry, index, child)
            }
            AbstractLiteral::Relation(elems)
            | AbstractLiteral::Partition(elems)
            | AbstractLiteral::Permutation(elems) => {
66681
                <Vec<Vec<U>> as Biplate<To>>::try_replace_child_at_bi(elems, index, child)
            }
            AbstractLiteral::Function(_) => {
13578
                let mut children = <Self as Biplate<To>>::children_bi(self);
13578
                if index >= children.len() {
                    return false;
13578
                }
13578
                children[index] = child;
13578
                *self = self.with_children_bi(children);
13578
                true
            }
        }
666554789
    }
}
impl TryFrom<Literal> for i32 {
    type Error = &'static str;
130693052
    fn try_from(value: Literal) -> Result<Self, Self::Error> {
130693052
        match value {
130693021
            Literal::Int(i) => Ok(i),
31
            _ => Err("Cannot convert non-i32 literal to i32"),
        }
130693052
    }
}
impl TryFrom<Box<Literal>> for i32 {
    type Error = &'static str;
    fn try_from(value: Box<Literal>) -> Result<Self, Self::Error> {
        (*value).try_into()
    }
}
impl TryFrom<&Box<Literal>> for i32 {
    type Error = &'static str;
    fn try_from(value: &Box<Literal>) -> Result<Self, Self::Error> {
        TryFrom::<&Literal>::try_from(value.as_ref())
    }
}
impl TryFrom<&Moo<Literal>> for i32 {
    type Error = &'static str;
    fn try_from(value: &Moo<Literal>) -> Result<Self, Self::Error> {
        TryFrom::<&Literal>::try_from(value.as_ref())
    }
}
impl TryFrom<&Literal> for i32 {
    type Error = &'static str;
2120799
    fn try_from(value: &Literal) -> Result<Self, Self::Error> {
2120799
        match value {
2120799
            Literal::Int(i) => Ok(*i),
            _ => Err("Cannot convert non-i32 literal to i32"),
        }
2120799
    }
}
impl TryFrom<Literal> for bool {
    type Error = &'static str;
29881030
    fn try_from(value: Literal) -> Result<Self, Self::Error> {
29881030
        match value {
29880086
            Literal::Bool(b) => Ok(b),
944
            _ => Err("Cannot convert non-bool literal to bool"),
        }
29881030
    }
}
impl TryFrom<&Literal> for bool {
    type Error = &'static str;
    fn try_from(value: &Literal) -> Result<Self, Self::Error> {
        match value {
            Literal::Bool(b) => Ok(*b),
            _ => Err("Cannot convert non-bool literal to bool"),
        }
    }
}
impl TryFrom<Literal> for EnumVariant {
    type Error = &'static str;
24
    fn try_from(value: Literal) -> Result<Self, Self::Error> {
24
        match value {
24
            Literal::EnumVariant(v) => Ok(v),
            _ => Err("Cannot convert non-enum literal to enum variant"),
        }
24
    }
}
impl TryFrom<&Literal> for EnumVariant {
    type Error = &'static str;
    fn try_from(value: &Literal) -> Result<Self, Self::Error> {
        match value {
            Literal::EnumVariant(v) => Ok(v.clone()),
            _ => Err("Cannot convert non-enum literal to enum variant"),
        }
    }
}
impl From<i32> for Literal {
160877029
    fn from(i: i32) -> Self {
160877029
        Literal::Int(i)
160877029
    }
}
impl From<bool> for Literal {
3001349
    fn from(b: bool) -> Self {
3001349
        Literal::Bool(b)
3001349
    }
}
impl From<Literal> for Ustr {
    fn from(value: Literal) -> Self {
        // TODO: avoid the temporary-allocation of a string by format! here?
        Ustr::from(&format!("{value}"))
    }
}
impl From<AbstractLiteral<Literal>> for Literal {
13922461
    fn from(literal: AbstractLiteral<Literal>) -> Self {
13922461
        Literal::AbstractLiteral(literal)
13922461
    }
}
impl AbstractLiteral<Expression> {
    /// If all the elements are literals, returns this as an AbstractLiteral<Literal>.
    /// Otherwise, returns `None`.
109484027
    pub fn into_literals(self) -> Option<AbstractLiteral<Literal>> {
109484027
        match self {
            AbstractLiteral::Set(elements) => {
1452943
                let literals = elements
1452943
                    .into_iter()
3323105
                    .map(|expr| match expr {
2257710
                        Expression::Atomic(_, Atom::Literal(lit)) => Some(lit),
                        Expression::AbstractLiteral(_, abslit) => {
1061874
                            Some(Literal::AbstractLiteral(abslit.into_literals()?))
                        }
3521
                        _ => None,
3323105
                    })
324030
                    .collect::<Option<Vec<_>>>()?;
1128913
                Some(AbstractLiteral::Set(literals))
            }
            AbstractLiteral::MSet(elements) => {
98766
                let literals = elements
98766
                    .into_iter()
131688
                    .map(|expr| match expr {
131688
                        Expression::Atomic(_, Atom::Literal(lit)) => Some(lit),
                        Expression::AbstractLiteral(_, abslit) => {
                            Some(Literal::AbstractLiteral(abslit.into_literals()?))
                        }
                        _ => None,
131688
                    })
                    .collect::<Option<Vec<_>>>()?;
98766
                Some(AbstractLiteral::MSet(literals))
            }
            AbstractLiteral::Partition(elems) => {
                // want to ascertain if every elem in Vec<Vec<Expr>> is a literal. If any are not, return none
                // otherwise confirm it is an abslit<lit>
558
                let mut partition: Vec<Vec<_>> = Vec::new();
558
                for part in elems {
558
                    let literals = part
558
                        .into_iter()
558
                        .map(|expr| match expr {
558
                            Expression::Atomic(_, Atom::Literal(lit)) => Some(lit),
                            Expression::AbstractLiteral(_, abslit) => {
                                Some(Literal::AbstractLiteral(abslit.into_literals()?))
                            }
                            _ => None,
558
                        })
                        .collect::<Option<Vec<_>>>()?;
558
                    partition.push(literals);
                }
558
                Some(AbstractLiteral::Partition(partition))
            }
            AbstractLiteral::Permutation(elems) => {
46630
                let mut permutation: Vec<Vec<_>> = Vec::new();
46630
                for cycle in elems {
47472
                    let literals = cycle
47472
                        .into_iter()
140364
                        .map(|expr| match expr {
140364
                            Expression::Atomic(_, Atom::Literal(lit)) => Some(lit),
                            Expression::AbstractLiteral(_, abslit) => {
                                Some(Literal::AbstractLiteral(abslit.into_literals()?))
                            }
                            _ => None,
140364
                        })
                        .collect::<Option<Vec<_>>>()?;
47472
                    permutation.push(literals);
                }
46630
                Some(AbstractLiteral::Permutation(permutation))
            }
            AbstractLiteral::Matrix(items, domain) => {
103511120
                let mut literals = vec![];
103511120
                for item in items {
124279342
                    let literal = match item {
29793320
                        Expression::Atomic(_, Atom::Literal(lit)) => Some(lit),
                        Expression::AbstractLiteral(_, abslit) => {
1989004
                            Some(Literal::AbstractLiteral(abslit.into_literals()?))
                        }
92497018
                        _ => None,
92497018
                    }?;
31716852
                    literals.push(literal);
                }
10948630
                Some(AbstractLiteral::Matrix(literals, domain.resolve().ok()?))
            }
            AbstractLiteral::Sequence(elements) => {
2057253
                let literals = elements
2057253
                    .into_iter()
2715755
                    .map(|expr| match expr {
1165693
                        Expression::Atomic(_, Atom::Literal(lit)) => Some(lit),
                        Expression::AbstractLiteral(_, abslit) => {
                            Some(Literal::AbstractLiteral(abslit.into_literals()?))
                        }
1550062
                        _ => None,
2715755
                    })
1550062
                    .collect::<Option<Vec<_>>>()?;
507191
                Some(AbstractLiteral::Sequence(literals))
            }
            AbstractLiteral::Tuple(items) => {
2102265
                let mut literals = vec![];
2102265
                for item in items {
4137973
                    let literal = match item {
3981733
                        Expression::Atomic(_, Atom::Literal(lit)) => Some(lit),
                        Expression::AbstractLiteral(_, abslit) => {
31
                            Some(Literal::AbstractLiteral(abslit.into_literals()?))
                        }
156209
                        _ => None,
156209
                    }?;
3981764
                    literals.push(literal);
                }
1946056
                Some(AbstractLiteral::Tuple(literals))
            }
            AbstractLiteral::Record(entries) => {
42656
                let mut literals = vec![];
42656
                for entry in entries {
85312
                    let literal = match entry.value {
85312
                        Expression::Atomic(_, Atom::Literal(lit)) => Some(lit),
                        Expression::AbstractLiteral(_, abslit) => {
                            Some(Literal::AbstractLiteral(abslit.into_literals()?))
                        }
                        _ => None,
                    }?;
85312
                    literals.push((entry.name, literal));
                }
                Some(AbstractLiteral::Record(
42656
                    literals
42656
                        .into_iter()
                        .map(|(name, literal)| Field {
85312
                            name,
85312
                            value: literal,
85312
                        })
                        .collect(),
                ))
            }
            AbstractLiteral::Function(entries) => {
6789
                let mut literals = vec![];
6789
                for (e1, e2) in entries {
20367
                    let literal1 = match e1 {
20367
                        Expression::Atomic(_, Atom::Literal(lit)) => Some(lit),
                        Expression::AbstractLiteral(_, abslit) => {
                            Some(Literal::AbstractLiteral(abslit.into_literals()?))
                        }
                        _ => None,
                    }?;
20367
                    let literal2 = match e2 {
20367
                        Expression::Atomic(_, Atom::Literal(lit)) => Some(lit),
                        Expression::AbstractLiteral(_, abslit) => {
                            Some(Literal::AbstractLiteral(abslit.into_literals()?))
                        }
                        _ => None,
                    }?;
20367
                    literals.push((literal1, literal2));
                }
6789
                Some(AbstractLiteral::Function(literals))
            }
            AbstractLiteral::Variant(entry) => {
158258
                let literal = match entry.value.clone() {
9055
                    Expression::Atomic(_, Atom::Literal(lit)) => Some(lit),
                    Expression::AbstractLiteral(_, abslit) => {
                        Some(Literal::AbstractLiteral(abslit.into_literals()?))
                    }
149203
                    _ => None,
149203
                }?;
9055
                Some(AbstractLiteral::Variant(Moo::new(Field {
9055
                    name: entry.name.clone(),
9055
                    value: literal,
9055
                })))
            }
            AbstractLiteral::Relation(tuples) => {
6789
                let mut literal_tuples = Vec::with_capacity(tuples.len());
6789
                for fields in tuples {
20367
                    let literals = fields
20367
                        .into_iter()
40734
                        .map(|expr| match expr {
40734
                            Expression::Atomic(_, Atom::Literal(lit)) => Some(lit),
                            Expression::AbstractLiteral(_, abslit) => {
                                Some(Literal::AbstractLiteral(abslit.into_literals()?))
                            }
                            _ => None,
40734
                        })
                        .collect::<Option<Vec<_>>>()?;
20367
                    literal_tuples.push(literals);
                }
6789
                Some(AbstractLiteral::Relation(literal_tuples))
            }
        }
109484027
    }
}
// need display implementations for other types as well
impl Display for Literal {
202629952
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
202629952
        match &self {
148566634
            Literal::Int(i) => write!(f, "{i}"),
21645448
            Literal::Bool(b) => write!(f, "{b}"),
144
            Literal::EnumVariant(ev) => write!(f, "{}", ev.name()),
12
            Literal::Unnamed(value) => write!(f, "{}_{}", value.ty.name, value.value),
32417714
            Literal::AbstractLiteral(l) => write!(f, "{l}"),
        }
202629952
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    use crate::ast::matrix::{flatten, partial_flatten, shape_of};
    use crate::ast::{DeclarationPtr, Metadata, Name};
    use crate::{domain_int_ground, into_matrix, matrix, matrix_lit, range};
    use uniplate::Uniplate;
    #[test]
1
    fn essence_value_ordering_uses_occurrence_lex_for_sets() {
8
        let set = |values: &[i32]| {
8
            Literal::AbstractLiteral(AbstractLiteral::Set(
8
                values.iter().copied().map(Literal::Int).collect(),
8
            ))
8
        };
1
        let ordered = [
1
            set(&[]),
1
            set(&[3]),
1
            set(&[2]),
1
            set(&[2, 3]),
1
            set(&[1]),
1
            set(&[1, 3]),
1
            set(&[1, 2]),
1
            set(&[1, 2, 3]),
1
        ];
1
        for pair in ordered.windows(2) {
7
            assert_eq!(pair[0].essence_cmp(&pair[1]), Ordering::Less);
        }
1
    }
    #[test]
1
    fn essence_value_ordering_is_lexicographic_for_tuples_and_matrices() {
4
        let tuple = |values: &[i32]| {
4
            Literal::AbstractLiteral(AbstractLiteral::Tuple(
4
                values.iter().copied().map(Literal::Int).collect(),
4
            ))
4
        };
1
        assert_eq!(tuple(&[1, 2]).essence_cmp(&tuple(&[1, 3])), Ordering::Less);
1
        assert_eq!(
1
            tuple(&[1, 2]).essence_cmp(&tuple(&[1, 2, 0])),
1
            Ordering::Less
        );
2
        let matrix = |values: &[i32]| {
2
            Literal::AbstractLiteral(AbstractLiteral::Matrix(
2
                values.iter().copied().map(Literal::Int).collect(),
2
                Moo::new(GroundDomain::Int(
2
                    vec![Range::Bounded(1, values.len() as i32)],
2
                    None,
2
                )),
2
            ))
2
        };
1
        assert_eq!(
1
            matrix(&[1, 2]).essence_cmp(&matrix(&[1, 3])),
1
            Ordering::Less
        );
1
    }
    #[test]
1
    fn mset_domain_accepts_domain_letting_references() {
1
        let declaration = DeclarationPtr::new_domain_letting(
1
            Name::user("NUM"),
1
            Domain::int(vec![Range::Bounded(1, 999)]),
1
        );
1
        let alias = Domain::reference(declaration).unwrap();
1
        let item = Expression::DomainAnnotation(
1
            Metadata::new(),
1
            Moo::new(Expression::Atomic(
1
                Metadata::new(),
1
                Atom::Literal(Literal::Int(1)),
1
            )),
1
            alias,
1
        );
1
        let domain = AbstractLiteral::MSet(vec![item.clone(), item])
1
            .domain_of()
1
            .unwrap();
1
        let (_, item_domain) = domain.as_mset().unwrap();
1
        assert_eq!(
1
            item_domain.resolve(),
1
            Ok(Moo::new(GroundDomain::Int(
1
                vec![Range::Bounded(1, 999)],
1
                None
1
            )))
        );
1
    }
    #[test]
1
    fn matrix_uniplate_universe() {
        // Can we traverse through matrices with uniplate?
1
        let my_matrix: AbstractLiteral<Literal> = into_matrix![
1
            vec![Literal::AbstractLiteral(matrix![Literal::Bool(true);Moo::new(GroundDomain::Bool)]); 5];
1
            Moo::new(GroundDomain::Bool)
        ];
1
        let expected_index_domains = vec![Moo::new(GroundDomain::Bool); 6];
        let actual_index_domains: Vec<Moo<GroundDomain>> =
6
            my_matrix.cata(&move |elem, children| {
6
                let mut res = vec![];
6
                res.extend(children.into_iter().flatten());
6
                if let AbstractLiteral::Matrix(_, index_domain) = elem {
6
                    res.push(index_domain);
                }
6
                res
6
            });
1
        assert_eq!(actual_index_domains, expected_index_domains);
1
    }
    #[test]
1
    fn matrix_flatten() {
1
        let tensor: AbstractLiteral<Literal> = matrix![
            [
                // batch 1
1
                [1, 2, 3, 4],
1
                [5, 6, 7, 8],
1
                [9, 10, 11, 12]
            ],
            [
                // batch 2
1
                [13, 14, 15, 16],
1
                [17, 18, 19, 20],
1
                [21, 22, 23, 24]
            ]
        ];
1
        let actual_elems: Vec<Literal> = flatten(&tensor).cloned().collect();
1
        let expected_elems = (1..25).map(Literal::from).collect::<Vec<_>>();
1
        assert_eq!(actual_elems, expected_elems);
1
    }
    #[test]
1
    fn matrix_domain_1d() {
1
        let matrix = matrix_lit![10, 11, 12, 13; domain_int_ground!(1..4)];
1
        let dom = matrix.domain_of();
1
        let (inner_dom, idx_doms) = dom.as_matrix_ground().expect("must be ground matrix");
1
        assert_eq!(inner_dom, &domain_int_ground!(10..13));
1
        assert_eq!(idx_doms.len(), 1);
1
        assert_eq!(&idx_doms[0], &domain_int_ground!(1..4));
1
    }
    #[test]
1
    fn matrix_domain_2d() {
1
        let matrix = matrix_lit![
1
            [1, 2, 3, 4],
1
            [5, 6, 7, 8];
            [
1
                domain_int_ground!(1..2),
1
                domain_int_ground!(1..4)
            ]
        ];
1
        let dom = matrix.domain_of();
1
        let (inner_dom, idx_doms) = dom.as_matrix_ground().expect("must be ground matrix");
1
        assert_eq!(inner_dom, &domain_int_ground!(1..8));
1
        assert_eq!(idx_doms.len(), 2);
1
        assert_eq!(&idx_doms[0], &domain_int_ground!(1..2));
1
        assert_eq!(&idx_doms[1], &domain_int_ground!(1..4));
1
    }
    #[test]
1
    fn matrix_shape_3d() {
1
        let tensor: AbstractLiteral<Literal> = matrix![
            [
1
                [1, 2, 3, 4],
1
                [5, 6, 7, 8],
1
                [9, 10, 11, 12]
            ],
            [
1
                [13, 14, 15, 16],
1
                [17, 18, 19, 20],
1
                [21, 22, 23, 24]
            ];
            [
1
                domain_int_ground!(1..2),
1
                domain_int_ground!(1..3),
1
                domain_int_ground!(1..4)
            ]
        ];
1
        let shape = shape_of(&tensor).expect("shape_of to work on a 3D matrix");
1
        assert_eq!(shape.size, 24);
1
        assert_eq!(shape.dims, vec![2, 3, 4]);
1
        assert_eq!(shape.strides, vec![12, 4, 1]);
1
        assert_eq!(
1
            shape.idx_doms,
1
            vec![
1
                domain_int_ground!(1..2),
1
                domain_int_ground!(1..3),
1
                domain_int_ground!(1..4)
            ]
        );
1
    }
    #[test]
1
    fn matrix_partial_flatten() {
1
        let tensor: AbstractLiteral<Literal> = matrix![
            [
                // batch 1
1
                [1, 2, 3, 4],
1
                [5, 6, 7, 8],
1
                [9, 10, 11, 12]
            ],
            [
                // batch 2
1
                [13, 14, 15, 16],
1
                [17, 18, 19, 20],
1
                [21, 22, 23, 24]
            ]
        ];
1
        assert_eq!(partial_flatten(0, tensor.clone()), tensor);
1
        let expected_flatten_1: AbstractLiteral<Literal> = matrix![
1
            [1, 2, 3, 4],
1
            [5, 6, 7, 8],
1
            [9, 10, 11, 12],
1
            [13, 14, 15, 16],
1
            [17, 18, 19, 20],
1
            [21, 22, 23, 24]
        ];
1
        assert_eq!(partial_flatten(1, tensor.clone()), expected_flatten_1);
        let expected_flatten_2 =
1
            AbstractLiteral::matrix_implied_indices((1..25).map(Literal::from).collect());
1
        assert_eq!(partial_flatten(2, tensor), expected_flatten_2);
1
    }
}