chisel_common/char/
span.rs

1use std::cmp::Ordering;
2use std::fmt::{Display, Formatter};
3
4use crate::char::coords::Coords;
5
6/// A [Span] represents a linear interval within the parser input, between to different [Coords]
7#[derive(Debug, Default, Copy, Clone, PartialEq)]
8pub struct Span {
9    /// Start [Coords] for the span
10    pub start: Coords,
11    /// End [Coords] for the span
12    pub end: Coords,
13}
14
15impl Span {}
16
17impl Eq for Span {}
18
19impl PartialOrd<Self> for Span {
20    /// The partial order is based on the start coordinates for a span
21    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
22        match self.start.cmp(&other.start) {
23            Ordering::Less => Some(Ordering::Less),
24            Ordering::Equal => Some(Ordering::Equal),
25            Ordering::Greater => Some(Ordering::Greater),
26        }
27    }
28}
29
30impl Ord for Span {
31    /// The total order for a span is based on the start coordinates of a span
32    fn cmp(&self, other: &Self) -> Ordering {
33        self.start.cmp(&other.start)
34    }
35}
36
37impl Display for Span {
38    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
39        write!(f, "start: {}, end: {}", self.start, self.end,)
40    }
41}
42#[cfg(test)]
43mod test {
44    use crate::char::coords::Coords;
45    use crate::char::span::Span;
46
47    #[test]
48    fn equality_between_defaults() {
49        let s1 = Span::default();
50        let s2 = Span::default();
51        assert_eq!(s1, s2)
52    }
53
54    #[test]
55    fn basic_ordering_should_work() {
56        let mut s1 = Span::default();
57        let s2 = Span::default();
58        s1.start = Coords {
59            line: 2,
60            column: 1,
61            absolute: 3,
62        };
63        assert!(s1 > s2)
64    }
65}