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
//! Module containing types and functions for mapping between byte indexes and line and column
//! locations
use std::{fmt, ops::Range, sync::Arc};

use itertools::Itertools;

use crate::pos::{ByteOffset, BytePos, Column, Line, Location, RawIndex, Span};

use codespan_reporting::files::{Error, Files, SimpleFile};

pub type Result<T> = std::result::Result<T, Error>;

pub type FileId = BytePos;

pub struct FileMap {
    file: SimpleFile<String, String>,
    span_start: FileId,
}

impl fmt::Debug for FileMap {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FileMap")
            .field("file", &self.file.source())
            .field("span", &self.span())
            .finish()
    }
}

impl FileMap {
    pub fn new(name: String, source: String) -> Self {
        Self {
            file: SimpleFile::new(name, source),
            span_start: BytePos(1),
        }
    }

    fn with_index(name: String, source: String, span_start: FileId) -> Self {
        FileMap {
            file: SimpleFile::new(name, source),
            span_start,
        }
    }

    fn from_usize(&self, pos: usize) -> BytePos {
        self.span_start + ByteOffset(pos as i64)
    }

    fn to_usize(&self, pos: BytePos) -> Option<usize> {
        if self.span().containment(pos) == std::cmp::Ordering::Equal {
            Some(pos.to_usize() - self.span_start.to_usize())
        } else {
            None
        }
    }

    pub fn span(&self) -> Span<BytePos> {
        Span::new(
            self.span_start,
            self.span_start + ByteOffset(self.src().len() as i64),
        )
    }

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

    pub fn name(&self) -> &str {
        self.file.name()
    }
}

#[derive(Clone, Debug, Default)]
pub struct CodeMap {
    files: Vec<Arc<FileMap>>,
}

impl CodeMap {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn add_filemap(&mut self, filename: String, source: String) -> Arc<FileMap> {
        let start_index = self
            .files
            .last()
            .map(|file| file.span().end())
            .unwrap_or_default()
            + ByteOffset::from(1);
        let file_map = Arc::new(FileMap::with_index(filename, source, start_index));
        self.files.push(file_map.clone());
        file_map
    }

    pub fn to_usize(&self, pos: BytePos) -> Option<usize> {
        self.get(pos)?.to_usize(pos)
    }

    pub fn find_file(&self, file: &str) -> Option<&Arc<FileMap>> {
        self.files.iter().find(|file_map| file_map.name() == file)
    }

    pub fn get(&self, file_id: FileId) -> Option<&Arc<FileMap>> {
        let i = self.find_index(file_id)?;
        self.files.get(i)
    }

    fn get_codespan(&self, file_id: FileId) -> Result<&Arc<FileMap>> {
        self.get(file_id).ok_or(Error::FileMissing)
    }

    pub fn update(&mut self, index: BytePos, src: String) -> Option<Arc<FileMap>> {
        self.find_index(index).map(|i| {
            let min = if i == 0 {
                BytePos(1)
            } else {
                self.files[i - 1].span().end() + ByteOffset(1)
            };
            let max = self
                .files
                .get(i + 1)
                .map_or(BytePos(RawIndex::max_value()), |file_map| {
                    file_map.span().start()
                })
                - ByteOffset(1);
            if src.len() <= (max - min).to_usize() {
                let start_index = self.files[i].span().start();
                let name = self.files[i].name().to_owned();
                let new_file = Arc::new(FileMap::with_index(name, src, start_index));
                self.files[i] = new_file.clone();
                new_file
            } else {
                let file = self.files.remove(i);
                match self
                    .files
                    .first()
                    .map(|file| file.span().start().to_usize() - 1)
                    .into_iter()
                    .chain(
                        self.files
                            .iter()
                            .tuple_windows()
                            .map(|(x, y)| (y.span().start() - x.span().end()).to_usize() - 1),
                    )
                    .position(|size| size >= src.len() + 1)
                {
                    Some(j) => {
                        let start_index = if j == 0 {
                            BytePos(1)
                        } else {
                            self.files[j - 1].span().end() + ByteOffset(1)
                        };
                        let new_file = Arc::new(FileMap::with_index(
                            file.name().to_owned(),
                            src,
                            start_index,
                        ));
                        self.files.insert(j, new_file.clone());
                        new_file
                    }
                    None => self.add_filemap(file.name().to_owned(), src),
                }
            }
        })
    }

    fn find_index(&self, index: BytePos) -> Option<usize> {
        use std::cmp::Ordering;
        self.files
            .binary_search_by(|file| {
                let span = file.span();
                match () {
                    () if span.start() > index => Ordering::Greater,
                    () if span.end() < index => Ordering::Less,
                    () => Ordering::Equal,
                }
            })
            .ok()
    }
}

impl<'a> Files<'a> for FileMap {
    type FileId = ();
    type Name = String;
    type Source = &'a str;

    fn name(&self, _file_id: Self::FileId) -> Result<Self::Name> {
        Ok(self.file.name().clone())
    }

    fn source(&self, _file_id: Self::FileId) -> Result<&str> {
        Ok(self.file.source())
    }

    fn line_index(&self, file_id: Self::FileId, byte_index: usize) -> Result<usize> {
        self.file.line_index(file_id, byte_index)
    }

    fn line_range(&self, file_id: Self::FileId, line_index: usize) -> Result<Range<usize>> {
        self.file.line_range(file_id, line_index)
    }
}

impl<'a> Files<'a> for CodeMap {
    type FileId = FileId;
    type Name = String;
    type Source = &'a str;

    fn name(&self, file_id: FileId) -> Result<Self::Name> {
        Ok(self.get_codespan(file_id)?.name().to_owned())
    }

    fn source(&self, file_id: FileId) -> Result<&str> {
        Ok(self.get_codespan(file_id)?.source())
    }

    fn line_index(&self, file_id: FileId, byte_index: usize) -> Result<usize> {
        self.get_codespan(file_id)?.line_index((), byte_index)
    }

    fn line_range(&self, file_id: FileId, line_index: usize) -> Result<Range<usize>> {
        self.get_codespan(file_id)?.line_range((), line_index)
    }
}

pub trait Source {
    fn new(s: &str) -> Self
    where
        Self: Sized;

    fn location(&self, byte: BytePos) -> Option<Location>;

    fn span(&self) -> Span<BytePos>;

    fn src(&self) -> &str;

    fn src_slice(&self, span: Span<BytePos>) -> &str;

    fn byte_index(&self, line: Line, column: Column) -> Option<BytePos>;

    fn line_number_at_byte(&self, pos: BytePos) -> Option<Line>;

    /// Returns the starting position of any comments and whitespace before `end`
    fn comment_start_before(&self, end: BytePos) -> BytePos;

    fn comments_between(&self, span: Span<BytePos>) -> CommentIter;
}

impl Source for FileMap {
    fn new(s: &str) -> Self
    where
        Self: Sized,
    {
        Self::new("test".into(), s.into())
    }

    fn span(&self) -> Span<BytePos> {
        FileMap::span(self)
    }

    fn src(&self) -> &str {
        self.source()
    }

    fn src_slice(&self, span: Span<BytePos>) -> &str {
        &self.src()[self.to_usize(span.start()).unwrap()..self.to_usize(span.end()).unwrap()]
    }

    fn byte_index(&self, line: Line, column: Column) -> Option<BytePos> {
        let range = self.line_range((), line.to_usize()).ok()?;
        Some(self.from_usize(range.start + column.to_usize()))
    }

    fn line_number_at_byte(&self, pos: BytePos) -> Option<Line> {
        self.line_index((), self.to_usize(pos)?)
            .ok()
            .map(|l| Line(l as u32))
    }

    /// Returns the line and column location of `byte`
    fn location(&self, byte: BytePos) -> Option<Location> {
        Files::location(self, (), self.to_usize(byte)?)
            .ok()
            .map(|loc| Location {
                line: Line(loc.line_number as u32 - 1),
                column: Column(loc.column_number as u32 - 1),
                absolute: byte,
            })
    }

    /// Returns the starting position of any comments and whitespace before `end`
    fn comment_start_before(&self, end: BytePos) -> BytePos {
        let mut iter = self.comments_between(Span::new(BytePos::from(0), end));
        // Scan from `end` until a non comment token is found
        for _ in iter.by_ref().rev() {}
        BytePos::from(iter.src.len() as u32)
    }

    fn comments_between(&self, span: Span<BytePos>) -> CommentIter {
        CommentIter {
            src: self.src_slice(span),
        }
    }
}

impl Source for () {
    fn new(_: &str) -> Self
    where
        Self: Sized,
    {
    }

    fn span(&self) -> Span<BytePos> {
        Span::new(1.into(), 1.into())
    }

    fn src(&self) -> &str {
        ""
    }

    fn src_slice(&self, _: Span<BytePos>) -> &str {
        panic!("src_slice: Expected FileMap")
    }

    fn byte_index(&self, _: Line, _: Column) -> Option<BytePos> {
        None
    }

    fn line_number_at_byte(&self, _: BytePos) -> Option<Line> {
        None
    }

    fn location(&self, _: BytePos) -> Option<Location> {
        None
    }

    fn comment_start_before(&self, pos: BytePos) -> BytePos {
        pos
    }

    fn comments_between(&self, _: Span<BytePos>) -> CommentIter {
        CommentIter { src: "" }
    }
}

pub struct CommentIter<'a> {
    src: &'a str,
}

impl<'a> Iterator for CommentIter<'a> {
    type Item = &'a str;

    fn next(&mut self) -> Option<&'a str> {
        if self.src.is_empty() {
            None
        } else {
            self.src = self
                .src
                .trim_matches(|c: char| c.is_whitespace() && c != '\n');
            if self.src.starts_with("//") && !self.src.starts_with("///") {
                let comment_line = self.src.lines().next().unwrap();
                self.src = &self.src[comment_line.len()..];
                self.src = if self.src.starts_with("\r\n") {
                    &self.src[2..]
                } else {
                    // \n
                    &self.src[1..]
                };
                Some(comment_line)
            } else if self.src.starts_with("/*") {
                self.src.find("*/").map(|i| {
                    let (comment, rest) = self.src.split_at(i + 2);
                    self.src = rest;
                    comment
                })
            } else if self.src.starts_with('\n') {
                self.src = &self.src[1..];
                Some("")
            } else {
                None
            }
        }
    }
}

impl<'a> DoubleEndedIterator for CommentIter<'a> {
    fn next_back(&mut self) -> Option<&'a str> {
        if self.src.is_empty() {
            None
        } else {
            self.src = self
                .src
                .trim_end_matches(|c: char| c.is_whitespace() && c != '\n');
            if self.src.ends_with('\n') {
                let comment_line = self.src[..self.src.len() - 1].lines().next_back()?;
                let trimmed = comment_line.trim_start();

                let newline_len = if self.src.ends_with("\r\n") { 2 } else { 1 };
                self.src = &self.src[..(self.src.len() - newline_len)];

                if trimmed.starts_with("//") && !trimmed.starts_with("///") {
                    self.src = &self.src[..(self.src.len() - 2 - trimmed.len() - 1)];
                    Some(trimmed)
                } else {
                    Some("")
                }
            } else if self.src.ends_with("*/") {
                self.src.rfind("/*").map(|i| {
                    let (rest, comment) = self.src.split_at(i);
                    self.src = rest;
                    comment
                })
            } else {
                None
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn empty_comment_iter() {
        assert_eq!(CommentIter { src: "" }.next(), None);
    }
}