1
use crate::ast::domains::Int;
2
use num_traits::Num;
3
use polyquine::Quine;
4
use serde::{Deserialize, Serialize};
5
use std::fmt::Display;
6

            
7
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Quine)]
8
#[path_prefix(conjure_cp::ast)]
9
pub enum Range<A = Int> {
10
    Single(A),
11
    Bounded(A, A),
12
    UnboundedL(A),
13
    UnboundedR(A),
14
    Unbounded,
15
}
16

            
17
impl<A> Range<A> {
18
    /// Whether the range is **bounded** on either side. A bounded range may still be infinite.
19
    /// See also: [Range::is_finite].
20
352757258
    pub fn is_lower_or_upper_bounded(&self) -> bool {
21
352757258
        match &self {
22
            Range::Single(_)
23
            | Range::Bounded(_, _)
24
            | Range::UnboundedL(_)
25
352757256
            | Range::UnboundedR(_) => true,
26
2
            Range::Unbounded => false,
27
        }
28
352757258
    }
29

            
30
    /// Whether the range is **unbounded** on both sides.
31
    pub fn is_unbounded(&self) -> bool {
32
        !self.is_lower_or_upper_bounded()
33
    }
34

            
35
    /// Whether the range is **finite**. See also: [Range::is_lower_or_upper_bounded].
36
10
    pub fn is_finite(&self) -> bool {
37
10
        match &self {
38
4
            Range::Single(_) | Range::Bounded(_, _) => true,
39
6
            Range::Unbounded | Range::UnboundedL(_) | Range::UnboundedR(_) => false,
40
        }
41
10
    }
42
}
43

            
44
impl<A: Ord> Range<A> {
45
19642
    pub fn contains(&self, val: &A) -> bool {
46
19642
        match self {
47
124
            Range::Single(x) => x == val,
48
19516
            Range::Bounded(x, y) => x <= val && val <= y,
49
            Range::UnboundedR(x) => x <= val,
50
            Range::UnboundedL(x) => val <= x,
51
2
            Range::Unbounded => true,
52
        }
53
19642
    }
54

            
55
    /// Returns the lower bound of the range, if it has one
56
3323236
    pub fn low(&self) -> Option<&A> {
57
3323236
        match self {
58
2454590
            Range::Single(a) => Some(a),
59
868606
            Range::Bounded(a, _) => Some(a),
60
14
            Range::UnboundedR(a) => Some(a),
61
26
            Range::UnboundedL(_) | Range::Unbounded => None,
62
        }
63
3323236
    }
64

            
65
    /// Returns the upper bound of the range, if it has one
66
3323232
    pub fn high(&self) -> Option<&A> {
67
3323232
        match self {
68
2439144
            Range::Single(a) => Some(a),
69
884048
            Range::Bounded(_, a) => Some(a),
70
24
            Range::UnboundedL(a) => Some(a),
71
16
            Range::UnboundedR(_) | Range::Unbounded => None,
72
        }
73
3323232
    }
74
}
75

            
76
impl<A: Ord + Clone> Range<A> {
77
    /// Create a new range with a lower and upper bound
78
307540
    pub fn new(lo: Option<A>, hi: Option<A>) -> Range<A> {
79
307540
        match (lo, hi) {
80
2
            (None, None) => Range::Unbounded,
81
2
            (Some(l), None) => Range::UnboundedR(l),
82
4
            (None, Some(r)) => Range::UnboundedL(r),
83
307532
            (Some(l), Some(r)) => {
84
307532
                if l == r {
85
18600
                    Range::Single(l)
86
                } else {
87
288932
                    let min = Ord::min(&l, &r).clone();
88
288932
                    let max = Ord::max(l, r);
89
288932
                    Range::Bounded(min, max)
90
                }
91
            }
92
        }
93
307540
    }
94

            
95
    /// Given a slice of ranges, create a single range that spans from the start
96
    /// of the leftmost range to the end of the rightmost range.
97
    /// An empty slice is considered equivalent to `Range::unbounded`.
98
158342
    pub fn spanning(rngs: &[Range<A>]) -> Range<A> {
99
158342
        if rngs.is_empty() {
100
2
            return Range::Unbounded;
101
158340
        }
102

            
103
158340
        let mut lo = rngs[0].low();
104
158340
        let mut hi = rngs[0].high();
105
165466
        for rng in rngs {
106
165466
            lo = match (lo, rng.low()) {
107
165458
                (Some(curr), Some(new)) => Some(curr.min(new)),
108
8
                _ => None,
109
            };
110
165466
            hi = match (hi, rng.high()) {
111
165462
                (Some(curr), Some(new)) => Some(curr.max(new)),
112
4
                _ => None,
113
            };
114
        }
115
158340
        Range::new(lo.cloned(), hi.cloned())
116
158342
    }
117
}
118

            
119
impl<A: Num + Ord + Clone> Range<A> {
120
1176
    pub fn length(&self) -> Option<A> {
121
1176
        match self {
122
4
            Range::Single(_) => Some(A::one()),
123
1162
            Range::Bounded(i, j) => Some(j.clone() - i.clone() + A::one()),
124
10
            Range::UnboundedR(_) | Range::UnboundedL(_) | Range::Unbounded => None,
125
        }
126
1176
    }
127

            
128
    /// Returns true if this interval overlaps another one, i.e. at least one
129
    /// number is part of both `self` and `other`
130
    /// E.g:
131
    /// - [0, 2] overlaps [2, 4]
132
    /// - [1, 3] overlaps [2, 4]
133
    /// - [4, 6] overlaps [2, 4]
134
692714
    pub fn overlaps(&self, other: &Range<A>) -> bool {
135
692714
        self.low()
136
692714
            .is_none_or(|la| other.high().is_none_or(|rb| la <= rb))
137
690792
            && self
138
690792
                .high()
139
690792
                .is_none_or(|ra| other.low().is_none_or(|lb| ra >= lb))
140
692714
    }
141

            
142
    /// Returns true if this interval touches another one on the left
143
    /// E.g: [1, 2] touches_left  [3, 4]
144
722084
    pub fn touches_left(&self, other: &Range<A>) -> bool {
145
722084
        self.high().is_some_and(|ra| {
146
722084
            let ra = ra.clone() + A::one();
147
722084
            other.low().is_some_and(|lb| ra.eq(lb))
148
722084
        })
149
722084
    }
150

            
151
    /// Returns true if this interval touches another one on the right
152
    /// E.g: [3, 4] touches_right  [1, 2]
153
574606
    pub fn touches_right(&self, other: &Range<A>) -> bool {
154
574606
        self.low().is_some_and(|la| {
155
574604
            let la = la.clone() - A::one();
156
574604
            other.high().is_some_and(|rb| la.eq(rb))
157
574604
        })
158
574606
    }
159

            
160
    /// Returns true if this interval overlaps or touches another one
161
    /// E.g:
162
    /// - [1, 3] joins [4, 6]
163
    /// - [2, 4] joins [4, 6]
164
    /// - [3, 5] joins [4, 6]
165
    /// - [6, 8] joins [4, 6]
166
    /// - [7, 8] joins [4, 6]
167
722072
    pub fn joins(&self, other: &Range<A>) -> bool {
168
722072
        self.touches_left(other) || self.overlaps(other) || self.touches_right(other)
169
722072
    }
170

            
171
    /// Returns true if this interval is strictly before another one
172
14
    pub fn is_before(&self, other: &Range<A>) -> bool {
173
14
        self.high()
174
14
            .is_some_and(|ra| other.low().is_some_and(|lb| ra < &(lb.clone() - A::one())))
175
14
    }
176

            
177
    /// Returns true if this interval is strictly after another one
178
12
    pub fn is_after(&self, other: &Range<A>) -> bool {
179
12
        self.low()
180
12
            .is_some_and(|la| other.high().is_some_and(|rb| la > &(rb.clone() + A::one())))
181
12
    }
182

            
183
    /// If the two ranges join, return a new range which spans both
184
722072
    pub fn join(&self, other: &Range<A>) -> Option<Range<A>> {
185
722072
        if self.joins(other) {
186
148760
            let lo = Ord::min(self.low(), other.low());
187
148760
            let hi = Ord::max(self.high(), other.high());
188
148760
            return Some(Range::new(lo.cloned(), hi.cloned()));
189
573312
        }
190
573312
        None
191
722072
    }
192

            
193
    /// Merge all joining ranges in the list, and return a new vec of disjoint ranges.
194
    /// E.g:
195
    /// ```ignore
196
    /// [(2..3), (4), (..1), (6..8)] -> [(..4), (6..8)]
197
    /// ```
198
    ///
199
    /// # Performance
200
    /// Currently uses a naive O(n^2) algorithm.
201
    /// A more optimal approach based on interval trees is planned.
202
1442498
    pub fn squeeze(rngs: &[Range<A>]) -> Vec<Range<A>> {
203
1442498
        let mut ans = Vec::from(rngs);
204

            
205
1442498
        if ans.is_empty() {
206
40
            return ans;
207
1442458
        }
208

            
209
        loop {
210
1591218
            let mut merged = false;
211

            
212
            // Check every pair of ranges and join them if possible
213
1651428
            'outer: for i in 0..ans.len() {
214
1651428
                for j in (i + 1)..ans.len() {
215
722072
                    if let Some(joined) = ans[i].join(&ans[j]) {
216
148760
                        ans[i] = joined;
217
                        // Safe to delete here because we restart the outer loop immediately
218
148760
                        ans.remove(j);
219
148760
                        merged = true;
220
148760
                        break 'outer;
221
573312
                    }
222
                }
223
            }
224

            
225
            // If no merges occurred, we're done
226
1591218
            if !merged {
227
1442458
                break;
228
148760
            }
229
        }
230

            
231
1442458
        ans
232
1442498
    }
233

            
234
    /// If this range is bounded, returns a lazy iterator over all values within the range.
235
    /// Otherwise, returns None.
236
208904
    pub fn iter(&self) -> Option<RangeIterator<A>> {
237
208904
        match self {
238
8340
            Range::Single(val) => Some(RangeIterator::Single(Some(val.clone()))),
239
200564
            Range::Bounded(start, end) => Some(RangeIterator::Bounded {
240
200564
                current: start.clone(),
241
200564
                end: end.clone(),
242
200564
            }),
243
            Range::UnboundedL(_) | Range::UnboundedR(_) | Range::Unbounded => None,
244
        }
245
208904
    }
246

            
247
504
    pub fn values(rngs: &[Range<A>]) -> Option<impl Iterator<Item = A>> {
248
504
        let itrs = rngs
249
504
            .iter()
250
504
            .map(Range::iter)
251
504
            .collect::<Option<Vec<RangeIterator<A>>>>()?;
252
504
        Some(itrs.into_iter().flatten())
253
504
    }
254
}
255

            
256
/// Iterator for Range<A> that yields values lazily
257
pub enum RangeIterator<A> {
258
    Single(Option<A>),
259
    Bounded { current: A, end: A },
260
}
261

            
262
impl<A: Num + Ord + Clone> Iterator for RangeIterator<A> {
263
    type Item = A;
264

            
265
1326564
    fn next(&mut self) -> Option<Self::Item> {
266
1326564
        match self {
267
16680
            RangeIterator::Single(val) => val.take(),
268
1309884
            RangeIterator::Bounded { current, end } => {
269
1309884
                if current > end {
270
200564
                    return None;
271
1109320
                }
272

            
273
1109320
                let result = current.clone();
274
1109320
                *current = current.clone() + A::one();
275

            
276
1109320
                Some(result)
277
            }
278
        }
279
1326564
    }
280
}
281

            
282
impl<A: Display> Display for Range<A> {
283
352757248
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284
352757248
        match self {
285
2514628
            Range::Single(i) => write!(f, "{i}"),
286
215179236
            Range::Bounded(i, j) => write!(f, "{i}..{j}"),
287
135063384
            Range::UnboundedR(i) => write!(f, "{i}.."),
288
            Range::UnboundedL(i) => write!(f, "..{i}"),
289
            Range::Unbounded => write!(f, ""),
290
        }
291
352757248
    }
292
}
293

            
294
#[allow(unused_imports)]
295
mod test {
296
    use super::*;
297
    use crate::range;
298

            
299
    #[test]
300
2
    pub fn test_range_macros() {
301
2
        assert_eq!(range!(1..3), Range::Bounded(1, 3));
302
2
        assert_eq!(range!(1..), Range::UnboundedR(1));
303
2
        assert_eq!(range!(..3), Range::UnboundedL(3));
304
2
        assert_eq!(range!(1), Range::Single(1));
305
2
    }
306

            
307
    #[test]
308
2
    pub fn test_range_low() {
309
2
        assert_eq!(range!(1..3).low(), Some(&1));
310
2
        assert_eq!(range!(1..).low(), Some(&1));
311
2
        assert_eq!(range!(1).low(), Some(&1));
312
2
        assert_eq!(range!(..3).low(), None);
313
2
        assert_eq!(Range::<Int>::Unbounded.low(), None);
314
2
    }
315

            
316
    #[test]
317
2
    pub fn test_range_high() {
318
2
        assert_eq!(range!(1..3).high(), Some(&3));
319
2
        assert_eq!(range!(1..).high(), None);
320
2
        assert_eq!(range!(1).high(), Some(&1));
321
2
        assert_eq!(range!(..3).high(), Some(&3));
322
2
        assert_eq!(Range::<Int>::Unbounded.high(), None);
323
2
    }
324

            
325
    #[test]
326
2
    pub fn test_range_is_finite() {
327
2
        assert!(range!(1..3).is_finite());
328
2
        assert!(range!(1).is_finite());
329
2
        assert!(!range!(1..).is_finite());
330
2
        assert!(!range!(..3).is_finite());
331
2
        assert!(!Range::<Int>::Unbounded.is_finite());
332
2
    }
333

            
334
    #[test]
335
2
    pub fn test_range_bounded() {
336
2
        assert!(range!(1..3).is_lower_or_upper_bounded());
337
2
        assert!(range!(1).is_lower_or_upper_bounded());
338
2
        assert!(range!(1..).is_lower_or_upper_bounded());
339
2
        assert!(range!(..3).is_lower_or_upper_bounded());
340
2
        assert!(!Range::<Int>::Unbounded.is_lower_or_upper_bounded());
341
2
    }
342

            
343
    #[test]
344
2
    pub fn test_range_length() {
345
2
        assert_eq!(range!(1..3).length(), Some(3));
346
2
        assert_eq!(range!(1).length(), Some(1));
347
2
        assert_eq!(range!(1..).length(), None);
348
2
        assert_eq!(range!(..3).length(), None);
349
2
        assert_eq!(Range::<Int>::Unbounded.length(), None);
350
2
    }
351

            
352
    #[test]
353
2
    pub fn test_range_contains_value() {
354
2
        assert!(range!(1..3).contains(&2));
355
2
        assert!(!range!(1..3).contains(&4));
356
2
        assert!(range!(1).contains(&1));
357
2
        assert!(!range!(1).contains(&2));
358
2
        assert!(Range::Unbounded.contains(&42));
359
2
    }
360

            
361
    #[test]
362
2
    pub fn test_range_overlaps() {
363
2
        assert!(range!(1..3).overlaps(&range!(2..4)));
364
2
        assert!(range!(1..3).overlaps(&range!(3..5)));
365
2
        assert!(!range!(1..3).overlaps(&range!(4..6)));
366
2
        assert!(Range::Unbounded.overlaps(&range!(1..3)));
367
2
    }
368

            
369
    #[test]
370
2
    pub fn test_range_touches_left() {
371
2
        assert!(range!(1..2).touches_left(&range!(3..4)));
372
2
        assert!(range!(1..2).touches_left(&range!(3)));
373
2
        assert!(range!(-5..-4).touches_left(&range!(-3..2)));
374
2
        assert!(!range!(1..2).touches_left(&range!(4..5)));
375
2
        assert!(!range!(1..2).touches_left(&range!(2..3)));
376
2
        assert!(!range!(3..4).touches_left(&range!(1..2)));
377
2
    }
378

            
379
    #[test]
380
2
    pub fn test_range_touches_right() {
381
2
        assert!(range!(3..4).touches_right(&range!(1..2)));
382
2
        assert!(range!(3).touches_right(&range!(1..2)));
383
2
        assert!(range!(0..1).touches_right(&range!(-2..-1)));
384
2
        assert!(!range!(1..2).touches_right(&range!(3..4)));
385
2
        assert!(!range!(2..3).touches_right(&range!(1..2)));
386
2
        assert!(!range!(1..2).touches_right(&range!(1..2)));
387
2
    }
388

            
389
    #[test]
390
2
    pub fn test_range_is_before() {
391
2
        assert!(range!(1..2).is_before(&range!(4..5)));
392
2
        assert!(range!(1..2).is_before(&range!(4..)));
393
2
        assert!(!range!(1..2).is_before(&range!(3..)));
394
2
        assert!(!range!(1..2).is_before(&range!(..4)));
395
2
        assert!(!range!(1..2).is_before(&range!(2..4)));
396
2
        assert!(!range!(3..4).is_before(&range!(1..2)));
397
2
        assert!(!range!(1..2).is_before(&Range::Unbounded));
398
2
    }
399

            
400
    #[test]
401
2
    pub fn test_range_is_after() {
402
2
        assert!(range!(5..6).is_after(&range!(1..2)));
403
2
        assert!(range!(4..5).is_after(&range!(..2)));
404
2
        assert!(!range!(4..5).is_after(&range!(..3)));
405
2
        assert!(!range!(2..3).is_after(&range!(1..2)));
406
2
        assert!(!range!(1..2).is_after(&range!(3..4)));
407
2
        assert!(!range!(1..2).is_after(&Range::Unbounded));
408
2
    }
409

            
410
    #[test]
411
2
    pub fn test_range_squeeze() {
412
2
        let input = vec![range!(2..3), range!(4), range!(..1), range!(6..8)];
413
2
        let squeezed = Range::squeeze(&input);
414
2
        assert_eq!(squeezed, vec![range!(..4), range!(6..8)]);
415
2
    }
416

            
417
    #[test]
418
2
    pub fn test_range_spanning() {
419
2
        assert_eq!(Range::<Int>::spanning(&[]), Range::Unbounded);
420
2
        assert_eq!(Range::spanning(&[range!(1..2), range!(4..5)]), range!(1..5));
421
2
        assert_eq!(
422
2
            Range::spanning(&[range!(..0), range!(2..4)]),
423
            Range::UnboundedL(4)
424
        );
425
2
        assert_eq!(
426
2
            Range::spanning(&[range!(0), range!(2..3), range!(5..)]),
427
            Range::UnboundedR(0)
428
        );
429
2
        assert_eq!(
430
2
            Range::spanning(&[range!(..0), range!(2..)]),
431
            Range::Unbounded
432
        );
433
2
    }
434
}