1
use crate::ast::domains::Int;
2
use crate::ast::domains::range::Range;
3
use funcmap::{FuncMap, TryFuncMap};
4
use itertools::Itertools;
5
use polyquine::Quine;
6
use serde::{Deserialize, Serialize};
7
use std::fmt::{Display, Formatter};
8

            
9
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, FuncMap, TryFuncMap, Quine)]
10
#[path_prefix(conjure_cp::ast)]
11
pub struct SetAttr<A = Int> {
12
    pub size: Range<A>,
13
    /// Optional user-facing representation preference (short name), e.g. `"packed"`.
14
    ///
15
    /// Written in Essence as `set (representation packed) of …`. When present, representation selection
16
    /// heuristics default to this representation if it is applicable.
17
    pub representation: Option<String>,
18
}
19

            
20
impl<A> SetAttr<A> {
21
714079
    pub fn new(size: Range<A>) -> Self {
22
714079
        Self {
23
714079
            size,
24
714079
            representation: None,
25
714079
        }
26
714079
    }
27

            
28
88
    pub fn new_min_max_size(min: A, max: A) -> Self {
29
88
        Self::new(Range::Bounded(min, max))
30
88
    }
31

            
32
2
    pub fn new_min_size(min: A) -> Self {
33
2
        Self::new(Range::UnboundedR(min))
34
2
    }
35

            
36
21
    pub fn new_max_size(max: A) -> Self {
37
21
        Self::new(Range::UnboundedL(max))
38
21
    }
39

            
40
170
    pub fn new_size(sz: A) -> Self {
41
170
        Self::new(Range::Single(sz))
42
170
    }
43

            
44
    /// Set the representation preference (Essence short name), returning the updated attributes.
45
436
    pub fn with_representation(mut self, name: impl Into<String>) -> Self {
46
436
        self.representation = Some(name.into());
47
436
        self
48
436
    }
49
}
50

            
51
impl<A> Default for SetAttr<A> {
52
244006
    fn default() -> Self {
53
244006
        SetAttr {
54
244006
            size: Range::Unbounded,
55
244006
            representation: None,
56
244006
        }
57
244006
    }
58
}
59

            
60
impl<A: Display> Display for SetAttr<A> {
61
770645
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
62
770645
        let mut attrs = Vec::new();
63
770645
        if let Some(representation) = &self.representation {
64
17753
            attrs.push(format!("representation {representation}"));
65
752892
        }
66
770645
        let size = fmt_size("size", &self.size);
67
770645
        if !size.is_empty() {
68
477792
            attrs.push(size);
69
292853
        }
70
770645
        if attrs.is_empty() {
71
287920
            Ok(())
72
        } else {
73
482725
            write!(f, "({})", attrs.join(", "))
74
        }
75
770645
    }
76
}
77

            
78
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, FuncMap, TryFuncMap, Quine)]
79
#[path_prefix(conjure_cp::ast)]
80
pub struct MSetAttr<A = Int> {
81
    pub size: Range<A>,
82
    pub occurrence: Range<A>,
83
    /// Optional user-facing representation preference (short name), e.g. `"repetition"`.
84
    ///
85
    /// Written in Essence as `mset (representation repetition) of …`. When present, representation selection
86
    /// heuristics default to this representation if it is applicable.
87
    #[serde(default)]
88
    pub representation: Option<String>,
89
}
90

            
91
impl<A> MSetAttr<A> {
92
407755
    pub fn new(size: Range<A>, occurrence: Range<A>) -> Self {
93
407755
        Self {
94
407755
            size,
95
407755
            occurrence,
96
407755
            representation: None,
97
407755
        }
98
407755
    }
99

            
100
    pub fn new_min_max_size(min: A, max: A) -> Self {
101
        Self::new(Range::Bounded(min, max), Range::Unbounded)
102
    }
103

            
104
1
    pub fn new_min_size(min: A) -> Self {
105
1
        Self::new(Range::UnboundedR(min), Range::Unbounded)
106
1
    }
107

            
108
11
    pub fn new_max_size(max: A) -> Self {
109
11
        Self::new(Range::UnboundedL(max), Range::Unbounded)
110
11
    }
111

            
112
2
    pub fn new_size(sz: A) -> Self {
113
2
        Self::new(Range::Single(sz), Range::Unbounded)
114
2
    }
115

            
116
    /// Set the representation preference (Essence short name), returning the updated attributes.
117
61
    pub fn with_representation(mut self, name: impl Into<String>) -> Self {
118
61
        self.representation = Some(name.into());
119
61
        self
120
61
    }
121
}
122

            
123
impl<A: Display> Display for MSetAttr<A> {
124
202431
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
125
202431
        let size_str = fmt_size("size", &self.size);
126

            
127
        // It only makes sense in terms of min and max occurrence for the essence language,
128
        // so for single ranges it is still presented as min and max occurrence.
129
202431
        let occ_str = match &self.occurrence {
130
            Range::Single(x) => format!("minOccur({x}), maxOccur({x})"),
131
279
            Range::Bounded(l, r) => format!("minOccur({l}), maxOccur({r})"),
132
178733
            Range::UnboundedL(r) => format!("maxOccur({r})"),
133
68
            Range::UnboundedR(l) => format!("minOccur({l})"),
134
23351
            Range::Unbounded => "".to_string(),
135
        };
136

            
137
202431
        let representation_str = self
138
202431
            .representation
139
202431
            .as_ref()
140
2761
            .map(|name| format!("representation {name}"))
141
            .unwrap_or_default();
142
202431
        let mut strs = [representation_str, size_str, occ_str]
143
202431
            .iter()
144
607293
            .filter(|s| !s.is_empty())
145
202431
            .join(", ");
146
202431
        if !strs.is_empty() {
147
202369
            strs = format!("({})", strs);
148
62
        }
149
202431
        write!(f, "{strs}")
150
202431
    }
151
}
152

            
153
impl<A> Default for MSetAttr<A> {
154
259005
    fn default() -> Self {
155
259005
        MSetAttr {
156
259005
            size: Range::Unbounded,
157
259005
            occurrence: Range::Unbounded,
158
259005
            representation: None,
159
259005
        }
160
259005
    }
161
}
162

            
163
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, FuncMap, TryFuncMap, Quine)]
164
#[path_prefix(conjure_cp::ast)]
165
pub struct FuncAttr<A = Int> {
166
    pub size: Range<A>,
167
    pub partiality: PartialityAttr,
168
    pub jectivity: JectivityAttr,
169
    /// Optional user-facing representation preference (short name), e.g. `"packed"`.
170
    ///
171
    /// Written in Essence as `function (representation packed, …)`. When present, representation
172
    /// selection heuristics default to this representation if it is applicable.
173
    pub representation: Option<String>,
174
}
175

            
176
impl<A> FuncAttr<A> {
177
    /// Set the representation preference (Essence short name), returning the updated attributes.
178
    pub fn with_representation(mut self, name: impl Into<String>) -> Self {
179
        self.representation = Some(name.into());
180
        self
181
    }
182
}
183

            
184
impl<A> Default for FuncAttr<A> {
185
6851
    fn default() -> Self {
186
6851
        FuncAttr {
187
6851
            size: Range::Unbounded,
188
            // Matches Conjure's own default (`Domain.hs`): a bare `function` with no explicit
189
            // `total` attribute is partial.
190
6851
            partiality: PartialityAttr::Partial,
191
6851
            jectivity: JectivityAttr::None,
192
6851
            representation: None,
193
6851
        }
194
6851
    }
195
}
196

            
197
impl<A: Display> Display for FuncAttr<A> {
198
106518
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
199
106518
        let size_str = fmt_size("size", &self.size);
200
106518
        let mut strs = [
201
106518
            fmt_representation(&self.representation),
202
106518
            size_str,
203
106518
            self.partiality.to_string(),
204
106518
            self.jectivity.to_string(),
205
106518
        ]
206
106518
        .iter()
207
426072
        .filter(|s| !s.is_empty())
208
106518
        .join(", ");
209
106518
        if !strs.is_empty() {
210
99923
            strs = format!("({})", strs);
211
6595
        }
212
106518
        write!(f, "{strs}")
213
106518
    }
214
}
215

            
216
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, FuncMap, TryFuncMap, Quine)]
217
#[path_prefix(conjure_cp::ast)]
218
pub struct SequenceAttr<A = Int> {
219
    pub size: Range<A>,
220
    pub jectivity: JectivityAttr,
221
    /// Optional user-facing representation preference (short name), e.g. `"packed"`.
222
    ///
223
    /// Written in Essence as `sequence{packed} of …`. When present, representation selection
224
    /// heuristics default to this representation if it is applicable.
225
    pub representation: Option<String>,
226
}
227

            
228
impl<A> SequenceAttr<A> {
229
    /// Set the representation preference (Essence short name), returning the updated attributes.
230
    pub fn with_representation(mut self, name: impl Into<String>) -> Self {
231
        self.representation = Some(name.into());
232
        self
233
    }
234
}
235

            
236
impl<A> Default for SequenceAttr<A> {
237
109341
    fn default() -> Self {
238
109341
        SequenceAttr {
239
109341
            size: Range::Unbounded,
240
109341
            jectivity: JectivityAttr::None,
241
109341
            representation: None,
242
109341
        }
243
109341
    }
244
}
245

            
246
impl<A: Display> Display for SequenceAttr<A> {
247
126591
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
248
126591
        let size_str = fmt_size("size", &self.size);
249
126591
        let mut strs = [
250
126591
            fmt_representation(&self.representation),
251
126591
            size_str,
252
126591
            self.jectivity.to_string(),
253
126591
        ]
254
126591
        .iter()
255
379773
        .filter(|s| !s.is_empty())
256
126591
        .join(", ");
257
126591
        if !strs.is_empty() {
258
126591
            strs = format!("({})", strs);
259
        }
260
126591
        write!(f, "{strs}")
261
126591
    }
262
}
263

            
264
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, FuncMap, TryFuncMap, Quine)]
265
#[path_prefix(conjure_cp::ast)]
266
pub struct PartitionAttr<A = Int> {
267
    pub num_parts: Range<A>, // i.e. how many parts there are in the partition
268
    pub part_len: Range<A>,  // i.e. the size of each constitutent part
269
    pub is_regular: bool,
270
    /// Optional user-facing representation preference (short name), e.g. `"packed"`.
271
    ///
272
    /// Written in Essence as `partition (representation packed, …)`. When present, representation
273
    /// selection heuristics default to this representation if it is applicable.
274
    pub representation: Option<String>,
275
}
276

            
277
impl<A> PartitionAttr<A> {
278
    /// Set the representation preference (Essence short name), returning the updated attributes.
279
    pub fn with_representation(mut self, name: impl Into<String>) -> Self {
280
        self.representation = Some(name.into());
281
        self
282
    }
283
}
284

            
285
impl<A: Display> Display for PartitionAttr<A> {
286
3502
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
287
3502
        let num_parts_str = fmt_size("numParts", &self.num_parts);
288
3502
        let part_len_str = fmt_size("partSize", &self.part_len);
289

            
290
3502
        let regular_str = match &self.is_regular {
291
806
            true => "regular".to_string(),
292
2696
            false => String::new(),
293
        };
294

            
295
3502
        let mut strs = [
296
3502
            fmt_representation(&self.representation),
297
3502
            num_parts_str,
298
3502
            part_len_str,
299
3502
            regular_str,
300
3502
        ]
301
3502
        .iter()
302
14008
        .filter(|s| !s.is_empty())
303
3502
        .join(", ");
304
3502
        if !strs.is_empty() {
305
2076
            strs = format!("({})", strs);
306
1426
        }
307
3502
        write!(f, "{strs}")
308
3502
    }
309
}
310

            
311
impl<A> Default for PartitionAttr<A> {
312
403
    fn default() -> Self {
313
403
        PartitionAttr {
314
403
            num_parts: Range::Unbounded,
315
403
            part_len: Range::Unbounded,
316
403
            is_regular: false,
317
403
            representation: None,
318
403
        }
319
403
    }
320
}
321

            
322
/// A permutation is inherently total and bijective by definition, so unlike partition or
323
/// function, its only attribute is a size constraint on `numMoved`, the number of moved points
324
/// (i.e. the points not fixed by the permutation) -- confirmed against real Conjure's own
325
/// `numMoved`/`minNumMoved`/`maxNumMoved` keywords (real Conjure does not accept
326
/// `size`/`minSize`/`maxSize` here, unlike set/relation/etc).
327
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, FuncMap, TryFuncMap, Quine)]
328
#[path_prefix(conjure_cp::ast)]
329
pub struct PermutationAttr<A = Int> {
330
    pub num_moved: Range<A>,
331
    /// Optional user-facing representation preference (short name), e.g. `"packed"`.
332
    ///
333
    /// Written in Essence as `permutation (representation packed, …)`. When present, representation
334
    /// selection heuristics default to this representation if it is applicable.
335
    pub representation: Option<String>,
336
}
337

            
338
impl<A> PermutationAttr<A> {
339
    /// Set the representation preference (Essence short name), returning the updated attributes.
340
    pub fn with_representation(mut self, name: impl Into<String>) -> Self {
341
        self.representation = Some(name.into());
342
        self
343
    }
344
}
345

            
346
impl<A: Display> Display for PermutationAttr<A> {
347
30814
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
348
30814
        let size_str = fmt_size("numMoved", &self.num_moved);
349
30814
        match &self.representation {
350
30690
            None if size_str.is_empty() => Ok(()),
351
775
            None => write!(f, "({size_str})"),
352
124
            Some(representation) if size_str.is_empty() => {
353
124
                write!(f, "(representation {representation})")
354
            }
355
            Some(representation) => write!(f, "(representation {representation}, {size_str})"),
356
        }
357
30814
    }
358
}
359

            
360
impl<A> Default for PermutationAttr<A> {
361
22165
    fn default() -> Self {
362
22165
        PermutationAttr {
363
22165
            num_moved: Range::Unbounded,
364
22165
            representation: None,
365
22165
        }
366
22165
    }
367
}
368

            
369
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Quine)]
370
pub enum PartialityAttr {
371
    Total,
372
    Partial,
373
}
374

            
375
impl Display for PartialityAttr {
376
106518
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
377
106518
        match self {
378
96793
            PartialityAttr::Total => write!(f, "total"),
379
9725
            PartialityAttr::Partial => write!(f, ""),
380
        }
381
106518
    }
382
}
383

            
384
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Quine)]
385
pub enum JectivityAttr {
386
    None,
387
    Injective,
388
    Surjective,
389
    Bijective,
390
}
391

            
392
impl Display for JectivityAttr {
393
233109
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
394
233109
        match self {
395
218638
            JectivityAttr::None => write!(f, ""),
396
11263
            JectivityAttr::Injective => write!(f, "injective"),
397
1176
            JectivityAttr::Surjective => write!(f, "surjective"),
398
2032
            JectivityAttr::Bijective => write!(f, "bijective"),
399
        }
400
233109
    }
401
}
402

            
403
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, FuncMap, TryFuncMap, Quine)]
404
#[path_prefix(conjure_cp::ast)]
405
pub struct RelAttr<A = Int> {
406
    pub size: Range<A>,
407
    pub binary: Vec<BinaryAttr>,
408
    /// Optional user-facing representation preference (short name), e.g. `"packed"`.
409
    ///
410
    /// Written in Essence as `relation (representation packed, …)`. When present, representation
411
    /// selection heuristics default to this representation if it is applicable.
412
    pub representation: Option<String>,
413
}
414

            
415
impl<A> RelAttr<A> {
416
    /// Set the representation preference (Essence short name), returning the updated attributes.
417
    pub fn with_representation(mut self, name: impl Into<String>) -> Self {
418
        self.representation = Some(name.into());
419
        self
420
    }
421
}
422

            
423
impl<A> Default for RelAttr<A> {
424
130
    fn default() -> Self {
425
130
        RelAttr {
426
130
            size: Range::Unbounded,
427
130
            binary: Vec::new(),
428
130
            representation: None,
429
130
        }
430
130
    }
431
}
432

            
433
impl<A: Display> Display for RelAttr<A> {
434
9324
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
435
9324
        let size_str = fmt_size("size", &self.size);
436
9324
        let mut strs = [
437
9324
            fmt_representation(&self.representation),
438
9324
            size_str,
439
9324
            self.binary.iter().join(", "),
440
9324
        ]
441
9324
        .iter()
442
27972
        .filter(|s| !s.is_empty())
443
9324
        .join(", ");
444
9324
        if !strs.is_empty() {
445
4098
            strs = format!("({})", strs);
446
5226
        }
447
9324
        write!(f, "{strs}")
448
9324
    }
449
}
450

            
451
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Quine)]
452
pub enum BinaryAttr {
453
    Reflexive,
454
    Irreflexive,
455
    Coreflexive,
456
    Symmetric,
457
    AntiSymmetric,
458
    ASymmetric,
459
    Transitive,
460
    Total,
461
    Connex,
462
    Euclidean,
463
    Serial,
464
    Equivalence,
465
    PartialOrder,
466
    LeftTotal,
467
    RightTotal,
468
    LinearOrder,
469
    WeakOrder,
470
    PreOrder,
471
    StrictPartialOrder,
472
}
473

            
474
impl Display for BinaryAttr {
475
2108
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
476
2108
        match self {
477
62
            BinaryAttr::Reflexive => write!(f, "reflexive"),
478
279
            BinaryAttr::Irreflexive => write!(f, "irreflexive"),
479
62
            BinaryAttr::Coreflexive => write!(f, "coreflexive"),
480
279
            BinaryAttr::Symmetric => write!(f, "symmetric"),
481
62
            BinaryAttr::AntiSymmetric => write!(f, "antiSymmetric"),
482
62
            BinaryAttr::ASymmetric => write!(f, "aSymmetric"),
483
62
            BinaryAttr::Transitive => write!(f, "transitive"),
484
62
            BinaryAttr::Total => write!(f, "total"),
485
62
            BinaryAttr::Connex => write!(f, "connex"),
486
279
            BinaryAttr::Euclidean => write!(f, "Euclidean"),
487
279
            BinaryAttr::Serial => write!(f, "serial"),
488
279
            BinaryAttr::Equivalence => write!(f, "equivalence"),
489
279
            BinaryAttr::PartialOrder => write!(f, "partialOrder"),
490
            BinaryAttr::LeftTotal => write!(f, "leftTotal"),
491
            BinaryAttr::RightTotal => write!(f, "rightTotal"),
492
            BinaryAttr::LinearOrder => write!(f, "linearOrder"),
493
            BinaryAttr::WeakOrder => write!(f, "weakOrder"),
494
            BinaryAttr::PreOrder => write!(f, "preOrder"),
495
            BinaryAttr::StrictPartialOrder => write!(f, "strictPartialOrder"),
496
        }
497
2108
    }
498
}
499

            
500
impl BinaryAttr {
501
    /// Parses the Essence keyword for a binary relation attribute (the inverse of `Display`).
502
    /// Used both by native domain-attribute parsing (`relation (reflexive, ...) of ...`) and by
503
    /// attribute-as-constraint lifting (`reflexive(r)`).
504
1457
    pub fn from_keyword(s: &str) -> Option<Self> {
505
1457
        Some(match s {
506
124
            "reflexive" => BinaryAttr::Reflexive,
507
217
            "irreflexive" => BinaryAttr::Irreflexive,
508
            "coreflexive" => BinaryAttr::Coreflexive,
509
217
            "symmetric" => BinaryAttr::Symmetric,
510
            "antiSymmetric" => BinaryAttr::AntiSymmetric,
511
            "aSymmetric" => BinaryAttr::ASymmetric,
512
            "transitive" => BinaryAttr::Transitive,
513
            "total" => BinaryAttr::Total,
514
            "connex" => BinaryAttr::Connex,
515
217
            "Euclidean" => BinaryAttr::Euclidean,
516
217
            "serial" => BinaryAttr::Serial,
517
217
            "equivalence" => BinaryAttr::Equivalence,
518
217
            "partialOrder" => BinaryAttr::PartialOrder,
519
            "leftTotal" => BinaryAttr::LeftTotal,
520
            "rightTotal" => BinaryAttr::RightTotal,
521
            "linearOrder" => BinaryAttr::LinearOrder,
522
            "weakOrder" => BinaryAttr::WeakOrder,
523
            "preOrder" => BinaryAttr::PreOrder,
524
            "strictPartialOrder" => BinaryAttr::StrictPartialOrder,
525
31
            _ => return None,
526
        })
527
1457
    }
528
}
529

            
530
/// Format a representation preference as an Essence attribute, or nothing without one.
531
245935
fn fmt_representation(representation: &Option<String>) -> String {
532
245935
    match representation {
533
496
        Some(representation) => format!("representation {representation}"),
534
245439
        None => String::new(),
535
    }
536
245935
}
537

            
538
/// Format a range as Essence size attribute
539
#[inline]
540
1253327
fn fmt_size<A: Display>(suffix: &str, sz: &Range<A>) -> String {
541
1253327
    let cap_suffix = capitalize(suffix);
542
1253327
    match sz {
543
332276
        Range::Single(x) => format!("{suffix} {x}"),
544
20282
        Range::Bounded(l, r) => format!("min{cap_suffix} {l}, max{cap_suffix} {r}"),
545
291643
        Range::UnboundedL(r) => format!("max{cap_suffix} {r}"),
546
161229
        Range::UnboundedR(l) => format!("min{cap_suffix} {l}"),
547
447897
        Range::Unbounded => "".to_string(),
548
    }
549
1253327
}
550

            
551
#[inline]
552
1253327
fn capitalize(s: &str) -> String {
553
1253327
    let mut c = s.chars();
554
1253327
    match c.next() {
555
        None => String::new(),
556
1253327
        Some(f) => f.to_uppercase().to_string() + c.as_str(),
557
    }
558
1253327
}