codespan_reporting/
files.rs

1//! Source file support for diagnostic reporting.
2//!
3//! The main trait defined in this module is the [`Files`] trait, which provides
4//! provides the minimum amount of functionality required for printing [`Diagnostics`]
5//! with the [`term::emit`] function.
6//!
7//! Simple implementations of this trait are implemented:
8//!
9//! - [`SimpleFile`]: For single-file use-cases
10//! - [`SimpleFiles`]: For multi-file use-cases
11//!
12//! These data structures provide a pretty minimal API, however,
13//! so end-users are encouraged to create their own implementations for their
14//! own specific use-cases, such as an implementation that accesses the file
15//! system directly (and caches the line start locations), or an implementation
16//! using an incremental compilation library like [`salsa`].
17//!
18//! [`term::emit`]: crate::term::emit
19//! [`Diagnostics`]: crate::diagnostic::Diagnostic
20//! [`Files`]: Files
21//! [`SimpleFile`]: SimpleFile
22//! [`SimpleFiles`]: SimpleFiles
23//!
24//! [`salsa`]: https://crates.io/crates/salsa
25
26use alloc::vec::Vec;
27use core::ops::Range;
28
29/// An enum representing an error that happened while looking up a file or a piece of content in that file.
30#[derive(Debug)]
31#[non_exhaustive]
32pub enum Error {
33    /// A required file is not in the file database.
34    FileMissing,
35    /// The file is present, but does not contain the specified byte index.
36    IndexTooLarge { given: usize, max: usize },
37    /// The file is present, but does not contain the specified line index.
38    LineTooLarge { given: usize, max: usize },
39    /// The file is present and contains the specified line index, but the line does not contain
40    /// the specified column index.
41    ColumnTooLarge { given: usize, max: usize },
42    /// The given index is contained in the file, but is not a boundary of a UTF-8 code point.
43    InvalidCharBoundary { given: usize },
44    /// There was a error while doing IO.
45    #[cfg(feature = "std")]
46    Io(std::io::Error),
47    /// There was a error during formatting.
48    FormatError,
49}
50
51#[cfg(feature = "std")]
52impl From<std::io::Error> for Error {
53    fn from(err: std::io::Error) -> Error {
54        Error::Io(err)
55    }
56}
57
58impl From<core::fmt::Error> for Error {
59    fn from(_err: core::fmt::Error) -> Error {
60        Error::FormatError
61    }
62}
63
64impl core::fmt::Display for Error {
65    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
66        match self {
67            Error::FileMissing => write!(f, "file missing"),
68            Error::IndexTooLarge { given, max } => {
69                write!(f, "invalid index {}, maximum index is {}", given, max)
70            }
71            Error::LineTooLarge { given, max } => {
72                write!(f, "invalid line {}, maximum line is {}", given, max)
73            }
74            Error::ColumnTooLarge { given, max } => {
75                write!(f, "invalid column {}, maximum column {}", given, max)
76            }
77            Error::InvalidCharBoundary { .. } => write!(f, "index is not a code point boundary"),
78            #[cfg(feature = "std")]
79            Error::Io(err) => write!(f, "{}", err),
80            Error::FormatError => write!(f, "formatting error"),
81        }
82    }
83}
84
85#[cfg(feature = "std")]
86use std::error::Error as RustError;
87
88#[cfg(not(feature = "std"))]
89use core::error::Error as RustError;
90
91impl RustError for Error {
92    fn source(&self) -> Option<&(dyn RustError + 'static)> {
93        match &self {
94            #[cfg(feature = "std")]
95            Error::Io(err) => Some(err),
96            _ => None,
97        }
98    }
99}
100
101/// A minimal interface for accessing source files when rendering diagnostics.
102///
103/// A lifetime parameter `'a` is provided to allow any of the returned values to returned by reference.
104/// This is to workaround the lack of higher kinded lifetime parameters.
105/// This can be ignored if this is not needed, however.
106pub trait Files<'a> {
107    /// A unique identifier for files in the file provider. This will be used
108    /// for rendering `diagnostic::Label`s in the corresponding source files.
109    type FileId: 'a + Copy + PartialEq;
110    /// The user-facing name of a file, to be displayed in diagnostics.
111    type Name: 'a + core::fmt::Display;
112    /// The source code of a file.
113    type Source: 'a + AsRef<str>;
114
115    /// The user-facing name of a file.
116    fn name(&'a self, id: Self::FileId) -> Result<Self::Name, Error>;
117
118    /// The source code of a file.
119    fn source(&'a self, id: Self::FileId) -> Result<Self::Source, Error>;
120
121    /// The index of the line at the given byte index.
122    /// If the byte index is past the end of the file, returns the maximum line index in the file.
123    /// This means that this function only fails if the file is not present.
124    ///
125    /// # Note for trait implementors
126    ///
127    /// This can be implemented efficiently by performing a binary search over
128    /// a list of line starts that was computed by calling the [`line_starts`]
129    /// function that is exported from the [`files`] module. It might be useful
130    /// to pre-compute and cache these line starts.
131    ///
132    /// [`line_starts`]: crate::files::line_starts
133    /// [`files`]: crate::files
134    fn line_index(&'a self, id: Self::FileId, byte_index: usize) -> Result<usize, Error>;
135
136    /// The user-facing line number at the given line index.
137    /// It is not necessarily checked that the specified line index
138    /// is actually in the file.
139    ///
140    /// # Note for trait implementors
141    ///
142    /// This is usually 1-indexed from the beginning of the file, but
143    /// can be useful for implementing something like the
144    /// [C preprocessor's `#line` macro][line-macro].
145    ///
146    /// [line-macro]: https://en.cppreference.com/w/c/preprocessor/line
147    #[allow(unused_variables)]
148    fn line_number(&'a self, id: Self::FileId, line_index: usize) -> Result<usize, Error> {
149        Ok(line_index + 1)
150    }
151
152    /// The user-facing column number at the given line index and byte index.
153    ///
154    /// # Note for trait implementors
155    ///
156    /// This is usually 1-indexed from the the start of the line.
157    /// A default implementation is provided, based on the [`column_index`]
158    /// function that is exported from the [`files`] module.
159    ///
160    /// [`files`]: crate::files
161    /// [`column_index`]: crate::files::column_index
162    fn column_number(
163        &'a self,
164        id: Self::FileId,
165        line_index: usize,
166        byte_index: usize,
167    ) -> Result<usize, Error> {
168        let source = self.source(id)?;
169        let line_range = self.line_range(id, line_index)?;
170        let column_index = column_index(source.as_ref(), line_range, byte_index);
171
172        Ok(column_index + 1)
173    }
174
175    /// Convenience method for returning line and column number at the given
176    /// byte index in the file.
177    fn location(&'a self, id: Self::FileId, byte_index: usize) -> Result<Location, Error> {
178        let line_index = self.line_index(id, byte_index)?;
179
180        Ok(Location {
181            line_number: self.line_number(id, line_index)?,
182            column_number: self.column_number(id, line_index, byte_index)?,
183        })
184    }
185
186    /// The byte range of line in the source of the file.
187    fn line_range(&'a self, id: Self::FileId, line_index: usize) -> Result<Range<usize>, Error>;
188}
189
190/// A user-facing location in a source file.
191///
192/// Returned by [`Files::location`].
193///
194/// [`Files::location`]: Files::location
195#[derive(Debug, Copy, Clone, PartialEq, Eq)]
196pub struct Location {
197    /// The user-facing line number.
198    pub line_number: usize,
199    /// The user-facing column number.
200    pub column_number: usize,
201}
202
203/// The column index at the given byte index in the source file.
204/// This is the number of characters to the given byte index.
205///
206/// If the byte index is smaller than the start of the line, then `0` is returned.
207/// If the byte index is past the end of the line, the column index of the last
208/// character `+ 1` is returned.
209///
210/// # Example
211///
212/// ```rust
213/// use codespan_reporting::files;
214///
215/// let source = "\n\nšŸ—»āˆˆšŸŒ\n\n";
216///
217/// assert_eq!(files::column_index(source, 0..1, 0), 0);
218/// assert_eq!(files::column_index(source, 2..13, 0), 0);
219/// assert_eq!(files::column_index(source, 2..13, 2 + 0), 0);
220/// assert_eq!(files::column_index(source, 2..13, 2 + 1), 0);
221/// assert_eq!(files::column_index(source, 2..13, 2 + 4), 1);
222/// assert_eq!(files::column_index(source, 2..13, 2 + 8), 2);
223/// assert_eq!(files::column_index(source, 2..13, 2 + 10), 2);
224/// assert_eq!(files::column_index(source, 2..13, 2 + 11), 3);
225/// assert_eq!(files::column_index(source, 2..13, 2 + 12), 3);
226/// ```
227pub fn column_index(source: &str, line_range: Range<usize>, byte_index: usize) -> usize {
228    let end_index = core::cmp::min(byte_index, core::cmp::min(line_range.end, source.len()));
229
230    (line_range.start..end_index)
231        .filter(|byte_index| source.is_char_boundary(byte_index + 1))
232        .count()
233}
234
235/// Return the starting byte index of each line in the source string.
236///
237/// This can make it easier to implement [`Files::line_index`] by allowing
238/// implementors of [`Files`] to pre-compute the line starts, then search for
239/// the corresponding line range, as shown in the example below.
240///
241/// [`Files`]: Files
242/// [`Files::line_index`]: Files::line_index
243///
244/// # Example
245///
246/// ```rust
247/// use codespan_reporting::files;
248///
249/// let source = "foo\nbar\r\n\nbaz";
250/// let line_starts: Vec<_> = files::line_starts(source).collect();
251///
252/// assert_eq!(
253///     line_starts,
254///     [
255///         0,  // "foo\n"
256///         4,  // "bar\r\n"
257///         9,  // ""
258///         10, // "baz"
259///     ],
260/// );
261///
262/// fn line_index(line_starts: &[usize], byte_index: usize) -> Option<usize> {
263///     match line_starts.binary_search(&byte_index) {
264///         Ok(line) => Some(line),
265///         Err(next_line) => Some(next_line - 1),
266///     }
267/// }
268///
269/// assert_eq!(line_index(&line_starts, 5), Some(1));
270/// ```
271// NOTE: this is copied in `codespan::file::line_starts` and should be kept in sync.
272pub fn line_starts(source: &str) -> impl '_ + Iterator<Item = usize> {
273    core::iter::once(0).chain(source.match_indices('\n').map(|(i, _)| i + 1))
274}
275
276/// A file database that contains a single source file.
277///
278/// Because there is only single file in this database we use `()` as a [`FileId`].
279///
280/// This is useful for simple language tests, but it might be worth creating a
281/// custom implementation when a language scales beyond a certain size.
282///
283/// [`FileId`]: Files::FileId
284#[derive(Debug, Clone)]
285pub struct SimpleFile<Name, Source> {
286    /// The name of the file.
287    name: Name,
288    /// The source code of the file.
289    source: Source,
290    /// The starting byte indices in the source code.
291    line_starts: Vec<usize>,
292}
293
294impl<Name, Source> SimpleFile<Name, Source>
295where
296    Name: core::fmt::Display,
297    Source: AsRef<str>,
298{
299    /// Create a new source file.
300    pub fn new(name: Name, source: Source) -> SimpleFile<Name, Source> {
301        SimpleFile {
302            name,
303            line_starts: line_starts(source.as_ref()).collect(),
304            source,
305        }
306    }
307
308    /// Return the name of the file.
309    pub fn name(&self) -> &Name {
310        &self.name
311    }
312
313    /// Return the source of the file.
314    pub fn source(&self) -> &Source {
315        &self.source
316    }
317
318    /// Return the starting byte index of the line with the specified line index.
319    /// Convenience method that already generates errors if necessary.
320    fn line_start(&self, line_index: usize) -> Result<usize, Error> {
321        use core::cmp::Ordering;
322
323        match line_index.cmp(&self.line_starts.len()) {
324            Ordering::Less => Ok(self
325                .line_starts
326                .get(line_index)
327                .copied()
328                .expect("failed despite previous check")),
329            Ordering::Equal => Ok(self.source.as_ref().len()),
330            Ordering::Greater => Err(Error::LineTooLarge {
331                given: line_index,
332                max: self.line_starts.len() - 1,
333            }),
334        }
335    }
336}
337
338impl<'a, Name, Source> Files<'a> for SimpleFile<Name, Source>
339where
340    Name: 'a + core::fmt::Display + Clone,
341    Source: 'a + AsRef<str>,
342{
343    type FileId = ();
344    type Name = Name;
345    type Source = &'a str;
346
347    fn name(&self, (): ()) -> Result<Name, Error> {
348        Ok(self.name.clone())
349    }
350
351    fn source(&self, (): ()) -> Result<&str, Error> {
352        Ok(self.source.as_ref())
353    }
354
355    fn line_index(&self, (): (), byte_index: usize) -> Result<usize, Error> {
356        Ok(self
357            .line_starts
358            .binary_search(&byte_index)
359            .unwrap_or_else(|next_line| next_line - 1))
360    }
361
362    fn line_range(&self, (): (), line_index: usize) -> Result<Range<usize>, Error> {
363        let line_start = self.line_start(line_index)?;
364        let next_line_start = self.line_start(line_index + 1)?;
365
366        Ok(line_start..next_line_start)
367    }
368}
369
370/// A file database that can store multiple source files.
371///
372/// This is useful for simple language tests, but it might be worth creating a
373/// custom implementation when a language scales beyond a certain size.
374/// It is a glorified `Vec<SimpleFile>` that implements the `Files` trait.
375#[derive(Debug, Default, Clone)]
376pub struct SimpleFiles<Name, Source> {
377    files: Vec<SimpleFile<Name, Source>>,
378}
379
380impl<Name, Source> SimpleFiles<Name, Source>
381where
382    Name: core::fmt::Display,
383    Source: AsRef<str>,
384{
385    /// Create a new files database.
386    pub fn new() -> SimpleFiles<Name, Source> {
387        SimpleFiles { files: Vec::new() }
388    }
389
390    /// Add a file to the database, returning the handle that can be used to
391    /// refer to it again.
392    pub fn add(&mut self, name: Name, source: Source) -> usize {
393        let file_id = self.files.len();
394        self.files.push(SimpleFile::new(name, source));
395        file_id
396    }
397
398    /// Get the file corresponding to the given id.
399    pub fn get(&self, file_id: usize) -> Result<&SimpleFile<Name, Source>, Error> {
400        self.files.get(file_id).ok_or(Error::FileMissing)
401    }
402}
403
404impl<'a, Name, Source> Files<'a> for SimpleFiles<Name, Source>
405where
406    Name: 'a + core::fmt::Display + Clone,
407    Source: 'a + AsRef<str>,
408{
409    type FileId = usize;
410    type Name = Name;
411    type Source = &'a str;
412
413    fn name(&self, file_id: usize) -> Result<Name, Error> {
414        Ok(self.get(file_id)?.name().clone())
415    }
416
417    fn source(&self, file_id: usize) -> Result<&str, Error> {
418        Ok(self.get(file_id)?.source().as_ref())
419    }
420
421    fn line_index(&self, file_id: usize, byte_index: usize) -> Result<usize, Error> {
422        self.get(file_id)?.line_index((), byte_index)
423    }
424
425    fn line_range(&self, file_id: usize, line_index: usize) -> Result<Range<usize>, Error> {
426        self.get(file_id)?.line_range((), line_index)
427    }
428}
429
430#[cfg(test)]
431mod test {
432    use super::*;
433
434    const TEST_SOURCE: &str = "foo\nbar\r\n\nbaz";
435
436    #[test]
437    fn line_starts() {
438        let file = SimpleFile::new("test", TEST_SOURCE);
439
440        assert_eq!(
441            file.line_starts,
442            [
443                0,  // "foo\n"
444                4,  // "bar\r\n"
445                9,  // ""
446                10, // "baz"
447            ],
448        );
449    }
450
451    #[test]
452    fn line_span_sources() {
453        let file = SimpleFile::new("test", TEST_SOURCE);
454
455        let line_sources = (0..4)
456            .map(|line| {
457                let line_range = file.line_range((), line).unwrap();
458                &file.source[line_range]
459            })
460            .collect::<Vec<_>>();
461
462        assert_eq!(line_sources, ["foo\n", "bar\r\n", "\n", "baz"]);
463    }
464}