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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
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, Hash)]
#[cfg_attr(feature = "serde-serialize", derive(serde::Serialize))]
#[cfg_attr(
    feature = "self-rust-tokenize",
    derive(self_rust_tokenize::SelfRustTokenize)
)]
pub struct BaseSpan<T> {
    pub start: u32,
    pub end: u32,
    pub source: T,
}

pub type Span = BaseSpan<()>;
pub type SpanWithSource = BaseSpan<SourceId>;

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

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

impl Span {
    /// TODO explain use cases
    pub const NULL_SPAN: Span = Span {
        start: 0,
        end: 0,
        source: (),
    };

    /// TODO explain use cases
    pub fn is_null(&self) -> bool {
        self.start == self.end
    }

    /// Returns whether the end of `self` is the start of `other`
    pub fn is_adjacent_to(&self, other: impl Into<Start>) -> bool {
        self.end == other.into().0
    }

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

    pub fn get_end(&self) -> End {
        End(self.end)
    }

    pub fn get_start(&self) -> Start {
        Start(self.start)
    }

    pub fn with_source(self, source: SourceId) -> SpanWithSource {
        SpanWithSource {
            start: self.start,
            end: self.end,
            source,
        }
    }
}

impl SpanWithSource {
    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_by_id(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: SpanWithSource = SpanWithSource {
        start: 0,
        end: 0,
        source: SourceId::NULL,
    };

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

    pub fn without_source(self) -> Span {
        Span {
            start: self.start,
            end: self.end,
            source: (),
        }
    }
}

// TODO why are two implementations needed
impl<T> From<BaseSpan<T>> for Range<u32> {
    fn from(span: BaseSpan<T>) -> Range<u32> {
        Range {
            start: span.start,
            end: span.end,
        }
    }
}

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

/// The byte start
#[derive(Debug, Clone, Copy)]
pub struct Start(pub u32);

impl Start {
    pub fn new(pos: u32) -> Self {
        Self(pos)
    }

    pub fn with_length(&self, len: usize) -> BaseSpan<()> {
        BaseSpan {
            start: self.0,
            end: self.0 + len as u32,
            source: (),
        }
    }

    pub fn get_end_after(&self, len: usize) -> End {
        End(self.0 + len as u32)
    }
}

/// The byte start
#[derive(Debug, Clone, Copy)]
pub struct End(pub u32);

impl End {
    pub fn new(pos: u32) -> Self {
        Self(pos)
    }

    pub fn is_adjacent_to(&self, other: impl Into<Start>) -> bool {
        self.0 == other.into().0
    }
}

impl From<Span> for Start {
    fn from(value: Span) -> Self {
        Start(value.start)
    }
}

impl From<Span> for End {
    fn from(value: Span) -> Self {
        End(value.end)
    }
}

impl<'a> From<&'a Span> for Start {
    fn from(value: &'a Span) -> Self {
        Start(value.start)
    }
}

impl<'a> From<&'a Span> for End {
    fn from(value: &'a Span) -> Self {
        End(value.end)
    }
}

impl Start {
    pub fn union(&self, end: impl Into<End>) -> Span {
        Span {
            start: self.0,
            end: end.into().0,
            source: (),
        }
    }
}

/// 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 {
        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_by_id(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_by_id(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) -> SpanWithSource {
        fs.get_source_by_id(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,
            );

            SpanWithSource {
                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, NoPathMap};

    use super::*;

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

    fn get_file_system_and_source() -> (MapFileStore<NoPathMap>, 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 = SpanWithSource {
            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"
        );
    }
}