aboutsummaryrefslogtreecommitdiffstats
path: root/src/parse/span.rs
blob: 671c10de3baa93a6233920a1847109c798a6e956 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use std::sync::atomic::AtomicU32;

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FileId {
    id: u32,
}

impl FileId {
    pub fn new() -> Self {
        static GEN: AtomicU32 = AtomicU32::new(0);
        Self {
            id: GEN.fetch_add(1, std::sync::atomic::Ordering::SeqCst),
        }
    }

    pub fn from(self, start: u32) -> SpanFrom {
        SpanFrom::new(self, start)
    }

    pub fn span(self, start: u32, end: u32) -> Span {
        Span::new(self, start, end)
    }
}

impl Default for FileId {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Copy, Clone)]
pub struct SpanFrom {
    pub file: FileId,
    pub start: u32,
}

impl SpanFrom {
    pub fn new(file: FileId, start: u32) -> Self {
        Self { file, start }
    }

    pub fn to(self, end: u32) -> Span {
        Span::new(self.file, self.start, end)
    }

    pub fn with_len(self, len: u32) -> Span {
        self.to(self.start + len)
    }
}

#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Span {
    pub file: FileId,
    pub start: u32,
    pub end: u32,
}

/// manual implementation of PartialOrd to ensure shorter Spans are first
impl PartialOrd for Span {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

/// manual implementation of Ord to ensure shorter Spans are first
impl Ord for Span {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        match self.file.cmp(&other.file) {
            core::cmp::Ordering::Equal => {}
            ord => return ord,
        }
        match self.start.cmp(&other.start) {
            core::cmp::Ordering::Equal => {}
            ord => return ord,
        }
        other.end.cmp(&self.end)
    }
}

impl Span {
    pub fn new(file: FileId, start: u32, end: u32) -> Self {
        Self { file, start, end }
    }
}