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
191905
    pub fn is_lower_or_upper_bounded(&self) -> bool {
21
191905
        match &self {
22
            Range::Single(_)
23
            | Range::Bounded(_, _)
24
            | Range::UnboundedL(_)
25
191904
            | Range::UnboundedR(_) => true,
26
1
            Range::Unbounded => false,
27
        }
28
191905
    }
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
5
    pub fn is_finite(&self) -> bool {
37
5
        match &self {
38
2
            Range::Single(_) | Range::Bounded(_, _) => true,
39
3
            Range::Unbounded | Range::UnboundedL(_) | Range::UnboundedR(_) => false,
40
        }
41
5
    }
42
}
43

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

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

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

            
76
impl<A: Ord + Clone> Range<A> {
77
    /// Create a new range with a lower and upper bound
78
16106
    pub fn new(lo: Option<A>, hi: Option<A>) -> Range<A> {
79
16106
        match (lo, hi) {
80
1
            (None, None) => Range::Unbounded,
81
1
            (Some(l), None) => Range::UnboundedR(l),
82
2
            (None, Some(r)) => Range::UnboundedL(r),
83
16102
            (Some(l), Some(r)) => {
84
16102
                if l == r {
85
320
                    Range::Single(l)
86
                } else {
87
15782
                    let min = Ord::min(&l, &r).clone();
88
15782
                    let max = Ord::max(l, r);
89
15782
                    Range::Bounded(min, max)
90
                }
91
            }
92
        }
93
16106
    }
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
13485
    pub fn spanning(rngs: &[Range<A>]) -> Range<A> {
99
13485
        if rngs.is_empty() {
100
1
            return Range::Unbounded;
101
13484
        }
102

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

            
119
impl<A: Num + Ord + Clone> Range<A> {
120
588
    pub fn length(&self) -> Option<A> {
121
588
        match self {
122
2
            Range::Single(_) => Some(A::one()),
123
581
            Range::Bounded(i, j) => Some(j.clone() - i.clone() + A::one()),
124
5
            Range::UnboundedR(_) | Range::UnboundedL(_) | Range::Unbounded => None,
125
        }
126
588
    }
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
247471
    pub fn overlaps(&self, other: &Range<A>) -> bool {
135
247471
        self.low()
136
247471
            .is_none_or(|la| other.high().is_none_or(|rb| la <= rb))
137
247210
            && self
138
247210
                .high()
139
247210
                .is_none_or(|ra| other.low().is_none_or(|lb| ra >= lb))
140
247471
    }
141

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

            
151
    /// Returns true if this interval touches another one on the right
152
    /// E.g: [3, 4] touches_right  [1, 2]
153
245513
    pub fn touches_right(&self, other: &Range<A>) -> bool {
154
245513
        self.low().is_some_and(|la| {
155
245512
            let la = la.clone() - A::one();
156
245512
            other.high().is_some_and(|rb| la.eq(rb))
157
245512
        })
158
245513
    }
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
247948
    pub fn joins(&self, other: &Range<A>) -> bool {
168
247948
        self.touches_left(other) || self.overlaps(other) || self.touches_right(other)
169
247948
    }
170

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

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

            
183
    /// If the two ranges join, return a new range which spans both
184
247948
    pub fn join(&self, other: &Range<A>) -> Option<Range<A>> {
185
247948
        if self.joins(other) {
186
2622
            let lo = Ord::min(self.low(), other.low());
187
2622
            let hi = Ord::max(self.high(), other.high());
188
2622
            return Some(Range::new(lo.cloned(), hi.cloned()));
189
245326
        }
190
245326
        None
191
247948
    }
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
58089
    pub fn squeeze(rngs: &[Range<A>]) -> Vec<Range<A>> {
203
58089
        let mut ans = Vec::from(rngs);
204

            
205
58089
        if ans.is_empty() {
206
40
            return ans;
207
58049
        }
208

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

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

            
225
            // If no merges occurred, we're done
226
60671
            if !merged {
227
58049
                break;
228
2622
            }
229
        }
230

            
231
58049
        ans
232
58089
    }
233

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

            
247
200
    pub fn values(rngs: &[Range<A>]) -> Option<impl Iterator<Item = A>> {
248
200
        let itrs = rngs
249
200
            .iter()
250
200
            .map(Range::iter)
251
200
            .collect::<Option<Vec<RangeIterator<A>>>>()?;
252
200
        Some(itrs.into_iter().flatten())
253
200
    }
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
385760
    fn next(&mut self) -> Option<Self::Item> {
266
385760
        match self {
267
9120
            RangeIterator::Single(val) => val.take(),
268
376640
            RangeIterator::Bounded { current, end } => {
269
376640
                if current > end {
270
60900
                    return None;
271
315740
                }
272

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

            
276
315740
                Some(result)
277
            }
278
        }
279
385760
    }
280
}
281

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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