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
use std::fmt::{Display, Formatter};
use serde::Serialize;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Hash)]
pub struct Span {
    pub start: usize,
    pub end: usize,
    pub start_position: (usize, usize),
    pub end_position: (usize, usize),
}

impl Default for Span {

    fn default() -> Self {
        Self {
            start: 0,
            end: 0,
            start_position: (1, 1),
            end_position: (1, 1),
        }
    }
}

impl Span {

    pub fn contains(&self, position: usize) -> bool {
        position >= self.start && position <= self.end
    }

    pub fn contains_line_col(&self, line_col: (usize, usize)) -> bool {
        line_col.0 >= self.start_position.0 &&
            line_col.0 <= self.end_position.0 &&
            if line_col.0 == self.start_position.0 { line_col.1 >= self.start_position.1 } else { true } &&
            if line_col.0 == self.end_position.0 { line_col.1 <= self.end_position.1 } else { true }
    }

    pub fn overlaps(&self, other: Span) -> bool {
        self.contains(other.start) || self.contains(other.end)
    }

    pub fn merge(&self, other: &Span) -> Span {
        Span {
            start: if self.start < other.start { self.start } else { other.start },
            end: if self.end < other.end { other.end } else { self.end },
            start_position: if self.start < other.start { self.start_position } else { other.start_position },
            end_position: if self.end < other.end { other.end_position } else { self.end_position },
        }
    }
}

impl Display for Span {

    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(&format!(
            "{}:{} - {}:{}",
            self.start_position.0,
            self.start_position.1,
            self.end_position.0,
            self.end_position.1
        ))
    }
}