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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
use std::sync::Arc;

type Pos = usize;

/// A [`SourceInfo`] maintains location data for parsed objects.
/// Maintains the filename (if from a file) or the originating string (if from a string).
/// Helps with the conversion from byte-position in the source to a [`LineCol`].
#[derive(Clone, Debug)]
pub struct SourceInfo {
    source: Source,
    linelens: LineLens,
}

impl SourceInfo {
    pub fn unknown() -> SourceInfo {
        SourceInfo {
            source: Source::Unknown,
            linelens: LineLens::from(""),
        }
    }

    pub fn source(&self) -> &Source {
        &self.source
    }

    pub fn from_file(filepath: &std::path::Path, contents: &str) -> SourceInfo {
        SourceInfo {
            source: Source::File(Arc::new(filepath.to_owned())),
            linelens: LineLens::from(contents),
        }
    }

    pub fn from_string(contents: &str) -> SourceInfo {
        SourceInfo {
            source: Source::String(Arc::new(contents.to_owned())),
            linelens: LineLens::from(contents),
        }
    }

    pub fn start(&self, item: &dyn HasSpan) -> LineCol {
        self.linelens.linecol(item.span().start)
    }

    pub fn end(&self, item: &dyn HasSpan) -> LineCol {
        self.linelens.linecol(item.span().end)
    }

    pub fn linecol_from(&self, pos: usize) -> LineCol {
        self.linelens.linecol(pos)
    }
}

#[derive(Clone, Debug)]
pub enum Source {
    File(Arc<std::path::PathBuf>),
    String(Arc<String>),
    Unknown,
}

/// A [`LineCol`] is a container for a line and column.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct LineCol(usize, usize);

impl LineCol {
    pub fn from(line: usize, col: usize) -> LineCol {
        assert!(line > 0);
        assert!(col > 0);
        LineCol(line - 1, col - 1)
    }

    /// The line number. Starts with line 1.
    pub fn line(&self) -> usize {
        self.0 + 1
    }

    /// The column. Starts with column 1.
    pub fn col(&self) -> usize {
        self.1 + 1
    }
}

impl std::fmt::Display for LineCol {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        write!(f, "{}:{}", self.line(), self.col())
    }
}

/// A [`Span`] tracks the span of an object parsed from a source.
#[derive(Clone)]
pub struct Span {
    start: Pos,
    end: Pos,
    source_info: SourceInfo,
}

impl std::fmt::Debug for Span {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        match &self.source_info.source {
            Source::File(path) => write!(f, "[{}-{}:{:?}]", self.start(), self.end(), path),
            Source::String(s) => write!(f, "[{}-{}:{:?}]", self.start(), self.end(), String::from_utf8_lossy(&s.as_bytes()[self.start..self.end])),
            Source::Unknown => write!(f, "[{}-{}]", self.start(), self.end()),
        }
    }
}

impl std::fmt::Display for Span {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        match &self.source_info.source {
            Source::File(_path) => write!(f, "[{}-{}]", self.start(), self.end()),
            Source::String(_s) => write!(f, "[{}-{}]", self.start(), self.end()),
            Source::Unknown => write!(f, "[{}-{}]", self.start(), self.end()),
        }
    }
}

impl Span {
    /// When the location of something is unknown, you can use this.
    pub fn unknown() -> Span {
        Span {
            start: 0,
            end: 0,
            source_info: SourceInfo::unknown(),
        }
    }

    pub fn from(source_info: &SourceInfo, start: usize, end: usize) -> Span {
        Span {
            start,
            end,
            source_info: source_info.clone(),
        }
    }

    /// The start of the span.
    pub fn start(&self) -> LineCol {
        self.source_info.linelens.linecol(self.start)
    }

    /// The end of the span.
    pub fn end(&self) -> LineCol {
        self.source_info.linelens.linecol(self.end)
    }

    pub fn source(&self) -> &str {
        if let Source::String(source) = &self.source_info.source {
            &source[self.start..self.end]
        } else {
            ""
        }
    }

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

/// Many objects have location information.
/// [`HasSpan`] allows you to call [`HasLoc::loc`] to get the span information.
pub trait HasSpan {
    fn span(&self) -> Span;
}

#[derive(Clone, Debug)]
struct LineLens(Vec<usize>);

impl LineLens {
    fn from(text: &str) -> LineLens {
        let mut lens = vec![];
        for line in text.split("\n") {
            lens.push(line.len() + 1);
        }
        LineLens(lens)
    }

    fn linecol(&self, pos: Pos) -> LineCol {
        let mut line = 0;
        let mut col = pos;
        for line_len in &self.0 {
            if col >= *line_len {
                col -= *line_len;
                line += 1;
            } else {
                break
            }
        }
        LineCol(line, col)
    }
}

#[test]
fn linelens() {
    // TODO Move this to tests.
    let text = "Hello,
world!
How are you?";

    let linelens = LineLens::from(text);
    assert_eq!(linelens.linecol(0).to_string(), "1:1".to_string());
    assert_eq!(linelens.linecol(5).to_string(), "1:6".to_string());
    assert_eq!(linelens.linecol(6).to_string(), "1:7".to_string());
    assert_eq!(linelens.linecol(7).to_string(), "2:1".to_string());
    assert_eq!(linelens.linecol(7).to_string(), "2:1".to_string());
    assert_eq!(linelens.linecol(12).to_string(), "2:6".to_string());
    assert_eq!(linelens.linecol(13).to_string(), "2:7".to_string());
    assert_eq!(linelens.linecol(14).to_string(), "3:1".to_string());
}