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
use rslint_rowan::{Language, SyntaxElement, SyntaxNode, SyntaxToken, TextRange};
use std::{collections::HashMap, ops::Range};

/// A value which can be used as the range inside of a diagnostic.
///
/// This is essentially a hack to allow us to use SyntaxElement, SyntaxNode, etc directly
pub trait Span {
    fn as_range(&self) -> Range<usize>;

    fn as_text_range(&self) -> TextRange {
        TextRange::new(
            (self.as_range().start as u32).into(),
            (self.as_range().end as u32).into(),
        )
    }

    /// Make a new span which extends to another span
    ///
    /// ```text
    /// from      to
    /// ^^^^^^^^^^^^
    /// ```
    fn join<T: Span>(&self, other: T) -> Range<usize> {
        self.as_range().start..other.as_range().end
    }

    /// Make a new span which is between another span
    ///
    /// ```text
    /// from      to
    ///     ^^^^^^
    /// ```
    fn between<T: Span>(&self, other: T) -> Range<usize> {
        self.as_range().end..other.as_range().start
    }

    /// Make a new span which extends until another span
    ///
    /// ```text
    /// from      to
    /// ^^^^^^^^^^
    /// ```
    fn until<T: Span>(&self, other: T) -> Range<usize> {
        self.as_range().start..other.as_range().start
    }

    fn sub_start(&self, amount: usize) -> Range<usize> {
        let range = self.as_range();
        range.start - amount..range.end
    }

    fn add_start(&self, amount: usize) -> Range<usize> {
        let range = self.as_range();
        range.start + amount..range.end
    }

    fn sub_end(&self, amount: usize) -> Range<usize> {
        let range = self.as_range();
        range.start..range.end - amount
    }

    fn add_end(&self, amount: usize) -> Range<usize> {
        let range = self.as_range();
        range.start..range.end + amount
    }
}

impl<T: Span> Span for &T {
    fn as_range(&self) -> Range<usize> {
        (*self).as_range()
    }
}

impl<T: Span> Span for &mut T {
    fn as_range(&self) -> Range<usize> {
        (**self).as_range()
    }
}

impl<T: Clone> Span for Range<T>
where
    T: Into<usize>,
{
    fn as_range(&self) -> Range<usize> {
        self.start.clone().into()..self.end.clone().into()
    }
}

impl<T: Language> Span for SyntaxNode<T> {
    fn as_range(&self) -> Range<usize> {
        self.text_range().into()
    }
}

impl<T: Language> Span for SyntaxToken<T> {
    fn as_range(&self) -> Range<usize> {
        self.text_range().into()
    }
}

impl<T: Language> Span for SyntaxElement<T> {
    fn as_range(&self) -> Range<usize> {
        match self {
            SyntaxElement::Node(n) => n.text_range(),
            SyntaxElement::Token(t) => t.text_range(),
        }
        .into()
    }
}

impl Span for TextRange {
    fn as_range(&self) -> Range<usize> {
        (*self).into()
    }
}

/// An id that points into a file database.
pub type FileId = usize;

/// A range that is indexed in a specific file.
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FileSpan {
    pub file: FileId,
    pub range: Range<usize>,
}

impl FileSpan {
    pub fn new(file: FileId, span: impl Span) -> Self {
        Self {
            file,
            range: span.as_range(),
        }
    }
}

/// Interface for interacting with source files
/// that are identified by a unique identifier.
pub trait Files {
    /// Returns the name of the file identified by the id.
    fn name(&self, id: FileId) -> Option<&str>;

    /// Returns the source of the file identified by the id.
    fn source(&self, id: FileId) -> Option<&str>;

    /// The index of the line at the byte index.
    ///
    /// ## Implementation
    /// This can be implemented by caching the results of [`line_starts`]
    /// and then use [`binary_search`](https://doc.rust-lang.org/std/primitive.slice.html#method.binary_search)
    /// to compute the line index.
    ///
    /// ```ignore
    /// match self.line_starts.binary_search(byte_index) {
    ///     Ok(line) => line,
    ///     Err(next_line) => next_line - 1,
    /// }
    /// ```
    fn line_index(&self, file_id: FileId, byte_index: usize) -> Option<usize>;

    /// The byte range of line in the source of the file.
    fn line_range(&self, id: FileId, line_index: usize) -> Option<Range<usize>>;
}

/// A file database that contains only one file.
#[derive(Clone, Debug)]
pub struct SimpleFile {
    name: String,
    source: String,
    line_starts: Vec<usize>,
}

impl SimpleFile {
    /// Create a new file with the name and source.
    pub fn new(name: String, source: String) -> Self {
        Self {
            line_starts: line_starts(&source).collect(),
            name,
            source,
        }
    }

    /// Returns a `SimpleFile` that has no name and no source.
    pub fn empty() -> SimpleFile {
        SimpleFile::new(String::new(), String::new())
    }

    fn line_start(&self, line_index: usize) -> Option<usize> {
        use std::cmp::Ordering;

        match line_index.cmp(&self.line_starts.len()) {
            Ordering::Less => self.line_starts.get(line_index).cloned(),
            Ordering::Equal => Some(self.source.len()),
            Ordering::Greater => None,
        }
    }
}

impl Files for SimpleFile {
    fn name(&self, _id: FileId) -> Option<&str> {
        Some(&self.name)
    }

    fn source(&self, _id: FileId) -> Option<&str> {
        Some(&self.source)
    }

    fn line_index(&self, _file_id: FileId, byte_index: usize) -> Option<usize> {
        Some(
            self.line_starts
                .binary_search(&byte_index)
                .unwrap_or_else(|next_line| next_line - 1),
        )
    }

    fn line_range(&self, _: FileId, line_index: usize) -> Option<Range<usize>> {
        let line_start = self.line_start(line_index)?;
        let next_line_start = self.line_start(line_index + 1)?;

        Some(line_start..next_line_start)
    }
}

/// A file database that stores multiple files.
#[derive(Clone, Debug, Default)]
pub struct SimpleFiles {
    files: HashMap<FileId, SimpleFile>,
    id: usize,
}

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

    /// Adds a file to this database and returns the id for the new file.
    pub fn add(&mut self, name: String, source: String) -> FileId {
        let id = self.id;
        self.id += 1;
        self.files.insert(id, SimpleFile::new(name, source));
        id
    }

    pub fn get(&self, id: FileId) -> Option<&SimpleFile> {
        self.files.get(&id)
    }
}

impl Files for SimpleFiles {
    fn name(&self, id: FileId) -> Option<&str> {
        self.files.get(&id)?.name(id)
    }

    fn source(&self, id: FileId) -> Option<&str> {
        self.files.get(&id)?.source(id)
    }

    fn line_index(&self, id: FileId, byte_index: usize) -> Option<usize> {
        self.files.get(&id)?.line_index(id, byte_index)
    }

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

/// Computes the byte indicies of every line start.
pub fn line_starts(source: &str) -> impl '_ + Iterator<Item = usize> {
    std::iter::once(0).chain(
        source
            .match_indices(&['\n', '\r', '\u{2028}', '\u{2029}'][..])
            .map(|(i, _)| i + 1),
    )
}