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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
use super::SourceId;
use crate::{encodings::*, FileSystem};
use std::{convert::TryInto, fmt, ops::Range};

/// A start and end. Also contains trace of original source
#[derive(PartialEq, Eq, Clone)]
#[cfg_attr(feature = "span-serialize", derive(serde::Serialize))]
#[cfg_attr(
    feature = "self-rust-tokenize",
    derive(self_rust_tokenize::SelfRustTokenize)
)]
pub struct Span {
    pub start: u32,
    pub end: u32,
    pub source: SourceId,
}

impl fmt::Debug for Span {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.source.is_null() {
            f.write_fmt(format_args!("{}..{}", self.start, self.end,))
        } else {
            f.write_fmt(format_args!(
                "{}..{}#{}",
                self.start, self.end, self.source.0
            ))
        }
    }
}

impl Span {
    /// Returns whether the end of `self` is the start of `other`
    pub fn is_adjacent_to(&self, other: &Self) -> bool {
        self.source == other.source && self.end == other.start
    }

    /// Returns a new [`Span`] which starts at the start of `self` a ends at the end of `other`
    pub fn union(&self, other: &Self) -> Span {
        Span {
            start: self.start,
            end: other.end,
            source: self.source,
        }
    }

    pub fn get_start(&self) -> Position {
        Position(self.start, self.source)
    }

    pub fn get_end(&self) -> Position {
        Position(self.end, self.source)
    }

    pub fn into_line_column_span<T: StringEncoding>(
        self,
        fs: &impl FileSystem,
    ) -> LineColumnSpan<T> {
        fs.get_source(self.source, |source| {
            let line_start = source
                .line_starts
                .get_index_of_line_pos_is_on(self.start as usize);
            let line_start_byte = source.line_starts.0[line_start];
            let column_start =
                T::get_encoded_length(&source.content[line_start_byte..(self.start as usize)]);

            let line_end = source
                .line_starts
                .get_index_of_line_pos_is_on(self.end as usize);
            let line_end_byte = source.line_starts.0[line_end];
            let column_end =
                T::get_encoded_length(&source.content[line_end_byte..(self.end as usize)]);

            LineColumnSpan {
                line_start: line_start as u32,
                column_start: column_start as u32,
                line_end: line_end as u32,
                column_end: column_end as u32,
                encoding: T::new(),
                source: self.source,
            }
        })
    }

    /// TODO explain use cases
    pub const NULL_SPAN: Span = Span {
        start: 0,
        end: 0,
        source: SourceId::NULL,
    };

    /// TODO explain use cases
    pub fn is_null(&self) -> bool {
        self.source == SourceId::NULL
    }
}

impl From<Span> for Range<u32> {
    fn from(span: Span) -> Range<u32> {
        Range {
            start: span.start,
            end: span.end,
        }
    }
}

impl From<Span> for Range<usize> {
    fn from(span: Span) -> Range<usize> {
        Range {
            start: span.start.try_into().unwrap(),
            end: span.end.try_into().unwrap(),
        }
    }
}

/// A scalar/singular byte wise position. **Zero based**
#[derive(PartialEq, Eq, Clone)]
pub struct Position(pub u32, pub SourceId);

impl fmt::Debug for Position {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.1.is_null() {
            f.write_fmt(format_args!("{}", self.0,))
        } else {
            f.write_fmt(format_args!("{}#{}", self.0, self.1 .0))
        }
    }
}

impl Position {
    pub fn into_line_column_position<T: StringEncoding>(
        self,
        fs: &impl FileSystem,
    ) -> LineColumnPosition<T> {
        fs.get_source(self.1, |source| {
            let line = source
                .line_starts
                .get_index_of_line_pos_is_on(self.0 as usize);
            let line_byte = source.line_starts.0[line];
            let column =
                T::get_encoded_length(&source.content[line_byte..(self.0 as usize)]) as u32;
            LineColumnPosition {
                line: line as u32,
                column,
                encoding: T::new(),
                source: self.1,
            }
        })
    }
}

/// **Zero based**
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct LineColumnPosition<T: StringEncoding> {
    pub line: u32,
    pub column: u32,
    pub source: SourceId,
    encoding: T,
}

impl<T: StringEncoding> LineColumnPosition<T> {
    pub fn into_scalar_position(self, fs: &impl FileSystem) -> Position {
        fs.get_source(self.source, |source| {
            let line_byte = source.line_starts.0[self.line as usize];
            let column_length =
                T::encoded_length_to_byte_count(&source.content[line_byte..], self.column as usize);
            Position((line_byte + column_length).try_into().unwrap(), self.source)
        })
    }
}

/// **Zero based**
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct LineColumnSpan<T: StringEncoding> {
    pub line_start: u32,
    pub column_start: u32,
    pub line_end: u32,
    pub column_end: u32,
    pub source: SourceId,
    encoding: T,
}

impl<T: StringEncoding> LineColumnSpan<T> {
    pub fn into_scalar_span(self, fs: &impl FileSystem) -> Span {
        fs.get_source(self.source, |source| {
            let line_start_byte = source.line_starts.0[self.line_start as usize];
            let column_start_length = T::encoded_length_to_byte_count(
                &source.content[line_start_byte..],
                self.column_start as usize,
            );

            let line_end_byte = source.line_starts.0[self.line_end as usize];
            let column_end_length = T::encoded_length_to_byte_count(
                &source.content[line_end_byte..],
                self.column_start as usize,
            );

            Span {
                start: (line_start_byte + column_start_length).try_into().unwrap(),
                end: (line_end_byte + column_end_length).try_into().unwrap(),
                source: self.source,
            }
        })
    }
}

#[cfg(feature = "lsp-types-morphisms")]
impl Into<lsp_types::Position> for LineColumnPosition<Utf8> {
    fn into(self) -> lsp_types::Position {
        lsp_types::Position {
            line: self.line,
            character: self.column,
        }
    }
}

#[cfg(feature = "lsp-types-morphisms")]
impl Into<lsp_types::Range> for LineColumnSpan<Utf8> {
    fn into(self) -> lsp_types::Range {
        lsp_types::Range {
            start: lsp_types::Position {
                line: self.line_start,
                character: self.column_start,
            },
            end: lsp_types::Position {
                line: self.line_end,
                character: self.column_end,
            },
        }
    }
}

#[cfg(feature = "lsp-types-morphisms")]
impl From<lsp_types::Position> for LineColumnPosition<Utf8> {
    fn from(lsp_position: lsp_types::Position) -> Self {
        LineColumnPosition {
            column: lsp_position.character,
            line: lsp_position.line,
            encoding: Utf8,
            source: SourceId::NULL,
        }
    }
}

#[cfg(feature = "lsp-types-morphisms")]
impl From<lsp_types::Range> for LineColumnSpan<Utf8> {
    fn from(lsp_range: lsp_types::Range) -> Self {
        LineColumnSpan {
            line_start: lsp_range.start.line,
            column_start: lsp_range.start.character,
            line_end: lsp_range.end.line,
            column_end: lsp_range.end.character,
            encoding: Utf8,
            source: SourceId::NULL,
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::{encodings::Utf8, MapFileStore};

    use super::*;

    const SOURCE: &str = "Hello World
I am a paragraph over two lines
Another line";

    fn get_file_system_and_source() -> (MapFileStore, SourceId) {
        let mut fs = MapFileStore::default();
        let source = fs.new_source_id("".into(), SOURCE.into());
        (fs, source)
    }

    #[test]
    fn scalar_span_to_line_column() {
        let (fs, source) = get_file_system_and_source();

        let paragraph_span = Span {
            start: 19,
            end: 28,
            source,
        };

        assert_eq!(&SOURCE[Range::from(paragraph_span.clone())], "paragraph");
        assert_eq!(
            paragraph_span.into_line_column_span(&fs),
            LineColumnSpan {
                line_start: 1,
                column_start: 7,
                line_end: 1,
                column_end: 16,
                encoding: Utf8,
                source
            }
        );
    }

    #[test]
    fn scalar_position_to_line_column() {
        let (fs, source) = get_file_system_and_source();

        let l_of_line_position = Position(52, source);
        assert_eq!(&SOURCE[l_of_line_position.0.try_into().unwrap()..], "line");

        assert_eq!(
            l_of_line_position.into_line_column_position(&fs),
            LineColumnPosition {
                line: 2,
                column: 8,
                encoding: Utf8,
                source
            }
        );
    }

    #[test]
    fn line_column_position_to_position() {
        let (fs, source) = get_file_system_and_source();
        let start_of_another_position = LineColumnPosition {
            line: 2,
            column: 0,
            source,
            encoding: Utf8,
        };
        assert_eq!(
            start_of_another_position.into_scalar_position(&fs),
            Position(44, source)
        );
    }

    #[test]
    fn line_column_span_to_span() {
        let (fs, source) = get_file_system_and_source();
        let line_another_span = LineColumnSpan {
            line_start: 1,
            column_start: 26,
            line_end: 2,
            column_end: 12,
            source,
            encoding: Utf8,
        };

        let line_another_span = line_another_span.into_scalar_span(&fs);
        assert_eq!(
            &SOURCE[Range::from(line_another_span)],
            "lines\nAnother line"
        );
    }
}