1
use crate::ast::domains::attrs::MSetAttr;
2
use crate::ast::domains::attrs::SetAttr;
3
use crate::ast::{
4
    DeclarationKind, DomainOpError, Expression, FuncAttr, Literal, Metadata, Moo,
5
    RecordEntryGround, Reference, Typeable,
6
    domains::{
7
        GroundDomain,
8
        domain::{DomainPtr, Int},
9
        range::Range,
10
    },
11
};
12
use crate::{bug, domain_int, matrix_expr, range};
13
use conjure_cp_core::ast::pretty::pretty_vec;
14
use conjure_cp_core::ast::{Name, ReturnType, eval_constant};
15
use itertools::Itertools;
16
use polyquine::Quine;
17
use serde::{Deserialize, Serialize};
18
use std::fmt::{Display, Formatter};
19
use std::iter::zip;
20
use std::ops::Deref;
21
use uniplate::Uniplate;
22

            
23
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Quine, Uniplate)]
24
#[path_prefix(conjure_cp::ast)]
25
#[biplate(to=Expression)]
26
#[biplate(to=Reference)]
27
pub enum IntVal {
28
    Const(Int),
29
    #[polyquine_skip]
30
    Reference(Reference),
31
    Expr(Moo<Expression>),
32
}
33

            
34
impl From<Int> for IntVal {
35
44640
    fn from(value: Int) -> Self {
36
44640
        Self::Const(value)
37
44640
    }
38
}
39

            
40
impl TryInto<Int> for IntVal {
41
    type Error = DomainOpError;
42

            
43
144212
    fn try_into(self) -> Result<Int, Self::Error> {
44
144212
        match self {
45
139892
            IntVal::Const(val) => Ok(val),
46
4320
            _ => Err(DomainOpError::NotGround),
47
        }
48
144212
    }
49
}
50

            
51
impl From<Range<Int>> for Range<IntVal> {
52
22500
    fn from(value: Range<Int>) -> Self {
53
22500
        match value {
54
360
            Range::Single(x) => Range::Single(x.into()),
55
22140
            Range::Bounded(l, r) => Range::Bounded(l.into(), r.into()),
56
            Range::UnboundedL(r) => Range::UnboundedL(r.into()),
57
            Range::UnboundedR(l) => Range::UnboundedR(l.into()),
58
            Range::Unbounded => Range::Unbounded,
59
        }
60
22500
    }
61
}
62

            
63
impl TryInto<Range<Int>> for Range<IntVal> {
64
    type Error = DomainOpError;
65

            
66
76544
    fn try_into(self) -> Result<Range<Int>, Self::Error> {
67
76544
        match self {
68
5540
            Range::Single(x) => Ok(Range::Single(x.try_into()?)),
69
69606
            Range::Bounded(l, r) => Ok(Range::Bounded(l.try_into()?, r.try_into()?)),
70
160
            Range::UnboundedL(r) => Ok(Range::UnboundedL(r.try_into()?)),
71
500
            Range::UnboundedR(l) => Ok(Range::UnboundedR(l.try_into()?)),
72
738
            Range::Unbounded => Ok(Range::Unbounded),
73
        }
74
76544
    }
75
}
76

            
77
impl From<SetAttr<Int>> for SetAttr<IntVal> {
78
    fn from(value: SetAttr<Int>) -> Self {
79
        SetAttr {
80
            size: value.size.into(),
81
        }
82
    }
83
}
84

            
85
impl TryInto<SetAttr<Int>> for SetAttr<IntVal> {
86
    type Error = DomainOpError;
87

            
88
438
    fn try_into(self) -> Result<SetAttr<Int>, Self::Error> {
89
438
        let size: Range<Int> = self.size.try_into()?;
90
438
        Ok(SetAttr { size })
91
438
    }
92
}
93

            
94
impl From<MSetAttr<Int>> for MSetAttr<IntVal> {
95
    fn from(value: MSetAttr<Int>) -> Self {
96
        MSetAttr {
97
            size: value.size.into(),
98
            occurrence: value.occurrence.into(),
99
        }
100
    }
101
}
102

            
103
impl TryInto<MSetAttr<Int>> for MSetAttr<IntVal> {
104
    type Error = DomainOpError;
105

            
106
360
    fn try_into(self) -> Result<MSetAttr<Int>, Self::Error> {
107
360
        let size: Range<Int> = self.size.try_into()?;
108
360
        let occurrence: Range<Int> = self.occurrence.try_into()?;
109
360
        Ok(MSetAttr { size, occurrence })
110
360
    }
111
}
112

            
113
impl From<FuncAttr<Int>> for FuncAttr<IntVal> {
114
    fn from(value: FuncAttr<Int>) -> Self {
115
        FuncAttr {
116
            size: value.size.into(),
117
            partiality: value.partiality,
118
            jectivity: value.jectivity,
119
        }
120
    }
121
}
122

            
123
impl TryInto<FuncAttr<Int>> for FuncAttr<IntVal> {
124
    type Error = DomainOpError;
125

            
126
520
    fn try_into(self) -> Result<FuncAttr<Int>, Self::Error> {
127
520
        let size: Range<Int> = self.size.try_into()?;
128
520
        Ok(FuncAttr {
129
520
            size,
130
520
            jectivity: self.jectivity,
131
520
            partiality: self.partiality,
132
520
        })
133
520
    }
134
}
135

            
136
impl Display for IntVal {
137
6215400
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
138
6215400
        match self {
139
3103920
            IntVal::Const(val) => write!(f, "{val}"),
140
2956440
            IntVal::Reference(re) => write!(f, "{re}"),
141
155040
            IntVal::Expr(expr) => write!(f, "({expr})"),
142
        }
143
6215400
    }
144
}
145

            
146
impl IntVal {
147
2700
    pub fn new_ref(re: &Reference) -> Option<IntVal> {
148
2700
        match re.ptr.kind().deref() {
149
2580
            DeclarationKind::ValueLetting(expr) | DeclarationKind::TemporaryValueLetting(expr) => {
150
2580
                match expr.return_type() {
151
2580
                    ReturnType::Int => Some(IntVal::Reference(re.clone())),
152
                    _ => None,
153
                }
154
            }
155
            DeclarationKind::Given(dom) => match dom.return_type() {
156
                ReturnType::Int => Some(IntVal::Reference(re.clone())),
157
                _ => None,
158
            },
159
120
            DeclarationKind::Quantified(inner) => match inner.domain().return_type() {
160
120
                ReturnType::Int => Some(IntVal::Reference(re.clone())),
161
                _ => None,
162
            },
163
            DeclarationKind::Find(var) => match var.return_type() {
164
                ReturnType::Int => Some(IntVal::Reference(re.clone())),
165
                _ => None,
166
            },
167
            DeclarationKind::DomainLetting(_) | DeclarationKind::RecordField(_) => None,
168
        }
169
2700
    }
170

            
171
1680
    pub fn new_expr(value: Moo<Expression>) -> Option<IntVal> {
172
1680
        if value.return_type() != ReturnType::Int {
173
            return None;
174
1680
        }
175
1680
        Some(IntVal::Expr(value))
176
1680
    }
177

            
178
140880
    pub fn resolve(&self) -> Option<Int> {
179
140880
        match self {
180
69240
            IntVal::Const(value) => Some(*value),
181
3820
            IntVal::Expr(expr) => eval_expr_to_int(expr),
182
67820
            IntVal::Reference(re) => match re.ptr.kind().deref() {
183
65860
                DeclarationKind::ValueLetting(expr)
184
67060
                | DeclarationKind::TemporaryValueLetting(expr) => eval_expr_to_int(expr),
185
                // If this is an int given we will be able to resolve it eventually, but not yet
186
                DeclarationKind::Given(_) => None,
187
                DeclarationKind::Quantified(inner) => {
188
                    if let Some(generator) = inner.generator()
189
                        && let Some(expr) = generator.as_value_letting()
190
                    {
191
                        eval_expr_to_int(&expr)
192
                    } else {
193
                        None
194
                    }
195
                }
196
                // Decision variables inside domains are unresolved until solving.
197
760
                DeclarationKind::Find(_) => None,
198
                DeclarationKind::DomainLetting(_) | DeclarationKind::RecordField(_) => bug!(
199
                    "Expected integer expression, given, or letting inside int domain; Got: {re}"
200
                ),
201
            },
202
        }
203
140880
    }
204
}
205

            
206
70880
fn eval_expr_to_int(expr: &Expression) -> Option<Int> {
207
70880
    match eval_constant(expr)? {
208
70440
        Literal::Int(v) => Some(v),
209
        _ => bug!("Expected integer expression, got: {expr}"),
210
    }
211
70880
}
212

            
213
impl From<IntVal> for Expression {
214
1320
    fn from(value: IntVal) -> Self {
215
1320
        match value {
216
480
            IntVal::Const(val) => val.into(),
217
540
            IntVal::Reference(re) => re.into(),
218
300
            IntVal::Expr(expr) => expr.as_ref().clone(),
219
        }
220
1320
    }
221
}
222

            
223
impl From<IntVal> for Moo<Expression> {
224
    fn from(value: IntVal) -> Self {
225
        match value {
226
            IntVal::Const(val) => Moo::new(val.into()),
227
            IntVal::Reference(re) => Moo::new(re.into()),
228
            IntVal::Expr(expr) => expr,
229
        }
230
    }
231
}
232

            
233
impl std::ops::Neg for IntVal {
234
    type Output = IntVal;
235

            
236
2880
    fn neg(self) -> Self::Output {
237
2880
        match self {
238
2880
            IntVal::Const(val) => IntVal::Const(-val),
239
            IntVal::Reference(_) | IntVal::Expr(_) => {
240
                IntVal::Expr(Moo::new(Expression::Neg(Metadata::new(), self.into())))
241
            }
242
        }
243
2880
    }
244
}
245

            
246
impl<T> std::ops::Add<T> for IntVal
247
where
248
    T: Into<Expression>,
249
{
250
    type Output = IntVal;
251

            
252
    fn add(self, rhs: T) -> Self::Output {
253
        let lhs: Expression = self.into();
254
        let rhs: Expression = rhs.into();
255
        let sum = matrix_expr!(lhs, rhs; domain_int!(1..));
256
        IntVal::Expr(Moo::new(Expression::Sum(Metadata::new(), Moo::new(sum))))
257
    }
258
}
259

            
260
impl Range<IntVal> {
261
209300
    pub fn resolve(&self) -> Option<Range<Int>> {
262
209300
        match self {
263
            Range::Single(x) => Some(Range::Single(x.resolve()?)),
264
209300
            Range::Bounded(l, r) => Some(Range::Bounded(l.resolve()?, r.resolve()?)),
265
            Range::UnboundedL(r) => Some(Range::UnboundedL(r.resolve()?)),
266
            Range::UnboundedR(l) => Some(Range::UnboundedR(l.resolve()?)),
267
            Range::Unbounded => Some(Range::Unbounded),
268
        }
269
209300
    }
270
}
271

            
272
impl SetAttr<IntVal> {
273
    pub fn resolve(&self) -> Option<SetAttr<Int>> {
274
        Some(SetAttr {
275
            size: self.size.resolve()?,
276
        })
277
    }
278
}
279

            
280
impl MSetAttr<IntVal> {
281
    pub fn resolve(&self) -> Option<MSetAttr<Int>> {
282
        Some(MSetAttr {
283
            size: self.size.resolve()?,
284
            occurrence: self.occurrence.resolve()?,
285
        })
286
    }
287
}
288

            
289
impl FuncAttr<IntVal> {
290
    pub fn resolve(&self) -> Option<FuncAttr<Int>> {
291
        Some(FuncAttr {
292
            size: self.size.resolve()?,
293
            partiality: self.partiality.clone(),
294
            jectivity: self.jectivity.clone(),
295
        })
296
    }
297
}
298

            
299
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Uniplate, Quine)]
300
#[path_prefix(conjure_cp::ast)]
301
pub struct RecordEntry {
302
    pub name: Name,
303
    pub domain: DomainPtr,
304
}
305

            
306
impl RecordEntry {
307
    pub fn resolve(self) -> Option<RecordEntryGround> {
308
        Some(RecordEntryGround {
309
            name: self.name,
310
            domain: self.domain.resolve()?,
311
        })
312
    }
313
}
314

            
315
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Quine, Uniplate)]
316
#[path_prefix(conjure_cp::ast)]
317
#[biplate(to=Expression)]
318
#[biplate(to=Reference)]
319
#[biplate(to=IntVal)]
320
#[biplate(to=DomainPtr)]
321
#[biplate(to=RecordEntry)]
322
pub enum UnresolvedDomain {
323
    Int(Vec<Range<IntVal>>),
324
    /// A set of elements drawn from the inner domain
325
    Set(SetAttr<IntVal>, DomainPtr),
326
    MSet(MSetAttr<IntVal>, DomainPtr),
327
    /// A n-dimensional matrix with a value domain and n-index domains
328
    Matrix(DomainPtr, Vec<DomainPtr>),
329
    /// A tuple of N elements, each with its own domain
330
    Tuple(Vec<DomainPtr>),
331
    /// A reference to a domain letting
332
    #[polyquine_skip]
333
    Reference(Reference),
334
    /// A record
335
    Record(Vec<RecordEntry>),
336
    /// A function with attributes, domain, and range
337
    Function(FuncAttr<IntVal>, DomainPtr, DomainPtr),
338
}
339

            
340
impl UnresolvedDomain {
341
354720
    pub fn resolve(&self) -> Option<GroundDomain> {
342
354720
        match self {
343
69780
            UnresolvedDomain::Int(rngs) => rngs
344
69780
                .iter()
345
69780
                .map(Range::<IntVal>::resolve)
346
69780
                .collect::<Option<_>>()
347
69780
                .map(GroundDomain::Int),
348
            UnresolvedDomain::Set(attr, inner) => {
349
                Some(GroundDomain::Set(attr.resolve()?, inner.resolve()?))
350
            }
351
            UnresolvedDomain::MSet(attr, inner) => {
352
                Some(GroundDomain::MSet(attr.resolve()?, inner.resolve()?))
353
            }
354
108960
            UnresolvedDomain::Matrix(inner, idx_doms) => {
355
108960
                let inner_gd = inner.resolve()?;
356
108960
                idx_doms
357
108960
                    .iter()
358
108960
                    .map(DomainPtr::resolve)
359
108960
                    .collect::<Option<_>>()
360
108960
                    .map(|idx| GroundDomain::Matrix(inner_gd, idx))
361
            }
362
            UnresolvedDomain::Tuple(inners) => inners
363
                .iter()
364
                .map(DomainPtr::resolve)
365
                .collect::<Option<_>>()
366
                .map(GroundDomain::Tuple),
367
            UnresolvedDomain::Record(entries) => entries
368
                .iter()
369
                .map(|f| {
370
                    f.domain.resolve().map(|gd| RecordEntryGround {
371
                        name: f.name.clone(),
372
                        domain: gd,
373
                    })
374
                })
375
                .collect::<Option<_>>()
376
                .map(GroundDomain::Record),
377
175980
            UnresolvedDomain::Reference(re) => re
378
175980
                .ptr
379
175980
                .as_domain_letting()
380
175980
                .unwrap_or_else(|| {
381
                    bug!("Reference domain should point to domain letting, but got {re}")
382
                })
383
175980
                .resolve()
384
175980
                .map(Moo::unwrap_or_clone),
385
            UnresolvedDomain::Function(attr, dom, cdom) => {
386
                if let Some(attr_gd) = attr.resolve()
387
                    && let Some(dom_gd) = dom.resolve()
388
                    && let Some(cdom_gd) = cdom.resolve()
389
                {
390
                    return Some(GroundDomain::Function(attr_gd, dom_gd, cdom_gd));
391
                }
392
                None
393
            }
394
        }
395
354720
    }
396

            
397
    pub(super) fn union_unresolved(
398
        &self,
399
        other: &UnresolvedDomain,
400
    ) -> Result<UnresolvedDomain, DomainOpError> {
401
        match (self, other) {
402
            (UnresolvedDomain::Int(lhs), UnresolvedDomain::Int(rhs)) => {
403
                let merged = lhs.iter().chain(rhs.iter()).cloned().collect_vec();
404
                Ok(UnresolvedDomain::Int(merged))
405
            }
406
            (UnresolvedDomain::Int(_), _) | (_, UnresolvedDomain::Int(_)) => {
407
                Err(DomainOpError::WrongType)
408
            }
409
            (UnresolvedDomain::Set(_, in1), UnresolvedDomain::Set(_, in2)) => {
410
                Ok(UnresolvedDomain::Set(SetAttr::default(), in1.union(in2)?))
411
            }
412
            (UnresolvedDomain::Set(_, _), _) | (_, UnresolvedDomain::Set(_, _)) => {
413
                Err(DomainOpError::WrongType)
414
            }
415
            (UnresolvedDomain::MSet(_, in1), UnresolvedDomain::MSet(_, in2)) => {
416
                Ok(UnresolvedDomain::MSet(MSetAttr::default(), in1.union(in2)?))
417
            }
418
            (UnresolvedDomain::MSet(_, _), _) | (_, UnresolvedDomain::MSet(_, _)) => {
419
                Err(DomainOpError::WrongType)
420
            }
421
            (UnresolvedDomain::Matrix(in1, idx1), UnresolvedDomain::Matrix(in2, idx2))
422
                if idx1 == idx2 =>
423
            {
424
                Ok(UnresolvedDomain::Matrix(in1.union(in2)?, idx1.clone()))
425
            }
426
            (UnresolvedDomain::Matrix(_, _), _) | (_, UnresolvedDomain::Matrix(_, _)) => {
427
                Err(DomainOpError::WrongType)
428
            }
429
            (UnresolvedDomain::Tuple(lhs), UnresolvedDomain::Tuple(rhs))
430
                if lhs.len() == rhs.len() =>
431
            {
432
                let mut merged = Vec::new();
433
                for (l, r) in zip(lhs, rhs) {
434
                    merged.push(l.union(r)?)
435
                }
436
                Ok(UnresolvedDomain::Tuple(merged))
437
            }
438
            (UnresolvedDomain::Tuple(_), _) | (_, UnresolvedDomain::Tuple(_)) => {
439
                Err(DomainOpError::WrongType)
440
            }
441
            // TODO: Could we support unions of reference domains symbolically?
442
            (UnresolvedDomain::Reference(_), _) | (_, UnresolvedDomain::Reference(_)) => {
443
                Err(DomainOpError::NotGround)
444
            }
445
            // TODO: Could we define semantics for merging record domains?
446
            #[allow(unreachable_patterns)] // Technically redundant but logically makes sense
447
            (UnresolvedDomain::Record(_), _) | (_, UnresolvedDomain::Record(_)) => {
448
                Err(DomainOpError::WrongType)
449
            }
450
            #[allow(unreachable_patterns)]
451
            // Technically redundant but logically clearer to have both
452
            (UnresolvedDomain::Function(_, _, _), _) | (_, UnresolvedDomain::Function(_, _, _)) => {
453
                Err(DomainOpError::WrongType)
454
            }
455
        }
456
    }
457

            
458
    pub fn element_domain(&self) -> Option<DomainPtr> {
459
        match self {
460
            UnresolvedDomain::Set(_, inner_dom) => Some(inner_dom.clone()),
461
            UnresolvedDomain::Matrix(_, _) => {
462
                todo!("Unwrap one dimension of the domain")
463
            }
464
            _ => None,
465
        }
466
    }
467
}
468

            
469
impl Typeable for UnresolvedDomain {
470
84360
    fn return_type(&self) -> ReturnType {
471
84360
        match self {
472
16020
            UnresolvedDomain::Reference(re) => re.return_type(),
473
6000
            UnresolvedDomain::Int(_) => ReturnType::Int,
474
            UnresolvedDomain::Set(_attr, inner) => ReturnType::Set(Box::new(inner.return_type())),
475
            UnresolvedDomain::MSet(_attr, inner) => ReturnType::MSet(Box::new(inner.return_type())),
476
62340
            UnresolvedDomain::Matrix(inner, _idx) => {
477
62340
                ReturnType::Matrix(Box::new(inner.return_type()))
478
            }
479
            UnresolvedDomain::Tuple(inners) => {
480
                let mut inner_types = Vec::new();
481
                for inner in inners {
482
                    inner_types.push(inner.return_type());
483
                }
484
                ReturnType::Tuple(inner_types)
485
            }
486
            UnresolvedDomain::Record(entries) => {
487
                let mut entry_types = Vec::new();
488
                for entry in entries {
489
                    entry_types.push(entry.domain.return_type());
490
                }
491
                ReturnType::Record(entry_types)
492
            }
493
            UnresolvedDomain::Function(_, dom, cdom) => {
494
                ReturnType::Function(Box::new(dom.return_type()), Box::new(cdom.return_type()))
495
            }
496
        }
497
84360
    }
498
}
499

            
500
impl Display for UnresolvedDomain {
501
20077380
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
502
20077380
        match &self {
503
10388340
            UnresolvedDomain::Reference(re) => write!(f, "{re}"),
504
3106620
            UnresolvedDomain::Int(ranges) => {
505
3106620
                if ranges.iter().all(Range::is_lower_or_upper_bounded) {
506
3107700
                    let rngs: String = ranges.iter().map(|r| format!("{r}")).join(", ");
507
3106620
                    write!(f, "int({})", rngs)
508
                } else {
509
                    write!(f, "int")
510
                }
511
            }
512
            UnresolvedDomain::Set(attrs, inner_dom) => write!(f, "set {attrs} of {inner_dom}"),
513
            UnresolvedDomain::MSet(attrs, inner_dom) => write!(f, "mset {attrs} of {inner_dom}"),
514
6582420
            UnresolvedDomain::Matrix(value_domain, index_domains) => {
515
6582420
                write!(
516
6582420
                    f,
517
                    "matrix indexed by {} of {value_domain}",
518
6582420
                    pretty_vec(&index_domains.iter().collect_vec())
519
                )
520
            }
521
            UnresolvedDomain::Tuple(domains) => {
522
                write!(
523
                    f,
524
                    "tuple of ({})",
525
                    pretty_vec(&domains.iter().collect_vec())
526
                )
527
            }
528
            UnresolvedDomain::Record(entries) => {
529
                write!(
530
                    f,
531
                    "record of ({})",
532
                    pretty_vec(
533
                        &entries
534
                            .iter()
535
                            .map(|entry| format!("{}: {}", entry.name, entry.domain))
536
                            .collect_vec()
537
                    )
538
                )
539
            }
540
            UnresolvedDomain::Function(attribute, domain, codomain) => {
541
                write!(f, "function {} {} --> {} ", attribute, domain, codomain)
542
            }
543
        }
544
20077380
    }
545
}