Skip to main content

solar_interface/source_map/
file.rs

1use crate::{BytePos, CharPos, pos::RelativeBytePos};
2use std::{
3    fmt, io,
4    ops::{Range, RangeInclusive},
5    path::{Path, PathBuf},
6    sync::Arc,
7};
8
9/// Identifies an offset of a multi-byte character in a `SourceFile`.
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11pub struct MultiByteChar {
12    /// The relative offset of the character in the `SourceFile`.
13    pub pos: RelativeBytePos,
14    /// The number of bytes, `>= 2`.
15    pub bytes: u8,
16}
17
18/// The name of a source file.
19///
20/// This is used as the key in the source map. See
21/// [`SourceMap::get_file`](crate::SourceMap::get_file).
22#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
23pub enum FileName {
24    /// Files from the file system.
25    Real(PathBuf),
26    /// Command line.
27    Stdin,
28    /// Custom sources for explicit parser calls from plugins and drivers.
29    Custom(String),
30}
31
32impl PartialEq<Path> for FileName {
33    fn eq(&self, other: &Path) -> bool {
34        match self {
35            Self::Real(p) => p == other,
36            _ => false,
37        }
38    }
39}
40
41impl PartialEq<&Path> for FileName {
42    fn eq(&self, other: &&Path) -> bool {
43        match self {
44            Self::Real(p) => p == *other,
45            _ => false,
46        }
47    }
48}
49
50impl PartialEq<PathBuf> for FileName {
51    fn eq(&self, other: &PathBuf) -> bool {
52        match self {
53            Self::Real(p) => p == other,
54            _ => false,
55        }
56    }
57}
58
59impl From<PathBuf> for FileName {
60    fn from(p: PathBuf) -> Self {
61        Self::Real(p)
62    }
63}
64
65impl From<&PathBuf> for FileName {
66    fn from(p: &PathBuf) -> Self {
67        Self::Real(p.clone())
68    }
69}
70
71impl From<&Path> for FileName {
72    fn from(p: &Path) -> Self {
73        Self::Real(p.to_path_buf())
74    }
75}
76
77impl From<String> for FileName {
78    fn from(s: String) -> Self {
79        Self::Custom(s)
80    }
81}
82
83impl From<&Self> for FileName {
84    fn from(s: &Self) -> Self {
85        s.clone()
86    }
87}
88
89impl FileName {
90    /// Parses a file name from a string.
91    ///
92    /// See [`SourceMap::parse_file_name`](crate::SourceMap::parse_file_name).
93    pub fn parse(sm: &crate::SourceMap, s: &str) -> Self {
94        sm.parse_file_name(s)
95    }
96
97    /// Creates a new `FileName` from a path.
98    pub fn real(path: impl Into<PathBuf>) -> Self {
99        Self::Real(path.into())
100    }
101
102    /// Creates a new `FileName` from a string.
103    pub fn custom(s: impl Into<String>) -> Self {
104        Self::Custom(s.into())
105    }
106
107    /// Displays the filename.
108    #[inline]
109    pub fn display(&self) -> FileNameDisplay<'_> {
110        let roots = crate::SessionGlobals::try_with(|g| g.map(|g| g.source_map.roots()))
111            .unwrap_or_else(|| arc_swap::Guard::from_inner(None));
112        FileNameDisplay { inner: self, roots }
113    }
114
115    /// Returns the path if the file name is a real file.
116    #[inline]
117    pub fn as_real(&self) -> Option<&Path> {
118        match self {
119            Self::Real(path) => Some(path),
120            _ => None,
121        }
122    }
123}
124
125/// A display wrapper for `FileName`.
126///
127/// Created by [`FileName::display`].
128pub struct FileNameDisplay<'a> {
129    pub(crate) inner: &'a FileName,
130    pub(crate) roots: arc_swap::Guard<Option<Arc<super::SourceRoots>>>,
131}
132
133impl fmt::Display for FileNameDisplay<'_> {
134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135        match self.inner {
136            FileName::Real(path) => {
137                let path = match &*self.roots {
138                    Some(roots) => roots.source_unit_name(path),
139                    None => path,
140                };
141                path.display().fmt(f)
142            }
143            FileName::Stdin => f.write_str("<stdin>"),
144            FileName::Custom(s) => write!(f, "<{s}>"),
145        }
146    }
147}
148
149#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
150pub(crate) struct SourceFileId(u64);
151
152impl SourceFileId {
153    pub(crate) fn new(filename: &FileName) -> Self {
154        use std::hash::{Hash, Hasher};
155        let mut hasher = solar_data_structures::map::FxHasher::with_seed(0);
156        filename.hash(&mut hasher);
157        Self(hasher.finish())
158    }
159}
160
161/// Sum of all file lengths is over [`u32::MAX`].
162#[derive(Debug)]
163pub struct OffsetOverflowError(pub(crate) ());
164
165impl fmt::Display for OffsetOverflowError {
166    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167        f.write_str("files larger than 4GiB are not supported")
168    }
169}
170
171impl std::error::Error for OffsetOverflowError {}
172
173impl From<OffsetOverflowError> for io::Error {
174    fn from(e: OffsetOverflowError) -> Self {
175        Self::new(io::ErrorKind::FileTooLarge, e)
176    }
177}
178
179/// A single source in the `SourceMap`.
180#[derive(Clone, derive_more::Debug)]
181#[non_exhaustive]
182pub struct SourceFile {
183    /// The name of the file that the source came from. Source that doesn't
184    /// originate from files has names between angle brackets by convention
185    /// (e.g., `<stdin>`).
186    pub name: FileName,
187    /// The complete source code.
188    #[debug(skip)]
189    pub src: Arc<String>,
190    /// The start position of this source in the `SourceMap`.
191    pub start_pos: BytePos,
192    /// The byte length of this source.
193    pub source_len: RelativeBytePos,
194    /// Locations of lines beginnings in the source code.
195    #[debug(skip)]
196    lines: Vec<RelativeBytePos>,
197    /// Locations of multi-byte characters in the source code.
198    #[debug(skip)]
199    pub multibyte_chars: Vec<MultiByteChar>,
200}
201
202impl PartialEq for SourceFile {
203    fn eq(&self, other: &Self) -> bool {
204        self.start_pos == other.start_pos
205    }
206}
207
208impl Eq for SourceFile {}
209
210impl std::hash::Hash for SourceFile {
211    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
212        self.start_pos.hash(state);
213    }
214}
215
216impl SourceFile {
217    /// Creates a new `SourceFile`. Use the [`SourceMap`](crate::SourceMap) methods instead.
218    pub(crate) fn new(
219        name: FileName,
220        id: SourceFileId,
221        mut src: Arc<String>,
222    ) -> Result<Self, OffsetOverflowError> {
223        // Compute the file hash before any normalization.
224        // let src_hash = SourceFileHash::new(hash_kind, &src);
225
226        // let normalized_pos = normalize_src(&mut src);
227
228        debug_assert_eq!(id, SourceFileId::new(&name));
229        let source_len = src.len();
230        let source_len = u32::try_from(source_len).map_err(|_| OffsetOverflowError(()))?;
231
232        let (lines, multibyte_chars) = super::analyze::analyze_source_file(&src);
233
234        if let Some(src) = Arc::get_mut(&mut src) {
235            src.shrink_to_fit();
236        }
237
238        Ok(Self {
239            name,
240            src,
241            start_pos: BytePos::from_u32(0),
242            source_len: RelativeBytePos::from_u32(source_len),
243            lines,
244            multibyte_chars,
245        })
246    }
247
248    pub fn lines(&self) -> &[RelativeBytePos] {
249        &self.lines
250    }
251
252    pub fn count_lines(&self) -> usize {
253        self.lines().len()
254    }
255
256    #[inline]
257    pub fn absolute_position(&self, pos: RelativeBytePos) -> BytePos {
258        BytePos::from_u32(pos.to_u32() + self.start_pos.to_u32())
259    }
260
261    #[inline]
262    pub fn relative_position(&self, pos: BytePos) -> RelativeBytePos {
263        RelativeBytePos::from_u32(pos.to_u32() - self.start_pos.to_u32())
264    }
265
266    #[inline]
267    pub fn end_position(&self) -> BytePos {
268        self.absolute_position(self.source_len)
269    }
270
271    /// Finds the line containing the given position. The return value is the
272    /// index into the `lines` array of this `SourceFile`, not the 1-based line
273    /// number. If the source_file is empty or the position is located before the
274    /// first line, `None` is returned.
275    pub fn lookup_line(&self, pos: RelativeBytePos) -> Option<usize> {
276        self.lines().partition_point(|x| x <= &pos).checked_sub(1)
277    }
278
279    pub fn line_bounds(&self, line_index: usize) -> Range<BytePos> {
280        if self.is_empty() {
281            return self.start_pos..self.start_pos;
282        }
283
284        let lines = self.lines();
285        assert!(line_index < lines.len());
286        if line_index == (lines.len() - 1) {
287            self.absolute_position(lines[line_index])..self.end_position()
288        } else {
289            self.absolute_position(lines[line_index])..self.absolute_position(lines[line_index + 1])
290        }
291    }
292
293    /// Returns the relative byte position of the start of the line at the given
294    /// 0-based line index.
295    pub fn line_position(&self, line_number: usize) -> Option<usize> {
296        self.lines().get(line_number).map(|x| x.to_usize())
297    }
298
299    /// Converts a `RelativeBytePos` to a `CharPos` relative to the `SourceFile`.
300    pub(crate) fn bytepos_to_file_charpos(&self, bpos: RelativeBytePos) -> CharPos {
301        // The number of extra bytes due to multibyte chars in the `SourceFile`.
302        let mut total_extra_bytes = 0;
303
304        for mbc in self.multibyte_chars.iter() {
305            if mbc.pos < bpos {
306                // Every character is at least one byte, so we only
307                // count the actual extra bytes.
308                total_extra_bytes += mbc.bytes as u32 - 1;
309                // We should never see a byte position in the middle of a
310                // character.
311                assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
312            } else {
313                break;
314            }
315        }
316
317        assert!(total_extra_bytes <= bpos.to_u32());
318        CharPos(bpos.to_usize() - total_extra_bytes as usize)
319    }
320
321    /// Returns the file's 1-based line number and 0-based character column for `pos`.
322    pub fn lookup_file_pos(&self, pos: RelativeBytePos) -> (usize, CharPos) {
323        let chpos = self.bytepos_to_file_charpos(pos);
324        match self.lookup_line(pos) {
325            Some(a) => {
326                let line = a + 1; // Line numbers start at 1
327                let linebpos = self.lines()[a];
328                let linechpos = self.bytepos_to_file_charpos(linebpos);
329                let col = chpos - linechpos;
330                assert!(chpos >= linechpos);
331                (line, col)
332            }
333            None => (0, chpos),
334        }
335    }
336
337    /// Looks up the file's (1-based) line number, (0-based `CharPos`) column offset, and (0-based)
338    /// column offset when displayed, for a given `BytePos`.
339    pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) {
340        let pos = self.relative_position(pos);
341        let (line, col_or_chpos) = self.lookup_file_pos(pos);
342        if line > 0 {
343            let Some(code) = self.get_line(line - 1) else {
344                // If we don't have the code available, it is ok as a fallback to return the bytepos
345                // instead of the "display" column, which is only used to properly show underlines
346                // in the terminal.
347                // FIXME: we'll want better handling of this in the future for the sake of tools
348                // that want to use the display col instead of byte offsets to modify code, but
349                // that is a problem for another day, the previous code was already incorrect for
350                // both displaying *and* third party tools using the json output naïvely.
351                debug!("couldn't find line {line} in {:?}", self.name);
352                return (line, col_or_chpos, col_or_chpos.0);
353            };
354            let display_col = code.chars().take(col_or_chpos.0).map(char_width).sum();
355            (line, col_or_chpos, display_col)
356        } else {
357            // This is never meant to happen?
358            (0, col_or_chpos, col_or_chpos.0)
359        }
360    }
361
362    /// Gets a line from the list of pre-computed line-beginnings.
363    /// The line number here is 0-based.
364    pub fn get_line(&self, line_number: usize) -> Option<&str> {
365        fn get_until_newline(src: &str, begin: usize) -> &str {
366            // We can't use `lines.get(line_number+1)` because we might
367            // be parsing when we call this function and thus the current
368            // line is the last one we have line info for.
369            let slice = &src[begin..];
370            match slice.find('\n') {
371                Some(e) => &slice[..e],
372                None => slice,
373            }
374        }
375
376        let start = self.lines().get(line_number)?.to_usize();
377        Some(get_until_newline(&self.src, start))
378    }
379
380    /// Gets a slice of the source text between two lines, including the
381    /// terminator of the second line (if any).
382    pub fn get_lines(&self, range: RangeInclusive<usize>) -> Option<&str> {
383        fn get_until_newline(src: &str, start: usize, end: usize) -> &str {
384            match src[end..].find('\n') {
385                Some(e) => &src[start..end + e + 1],
386                None => &src[start..],
387            }
388        }
389
390        let (start, end) = range.into_inner();
391        let lines = self.lines();
392        let start = lines.get(start)?.to_usize();
393        let end = lines.get(end)?.to_usize();
394        Some(get_until_newline(&self.src, start, end))
395    }
396
397    /// Returns whether or not the file contains the given `SourceMap` byte
398    /// position. The position one past the end of the file is considered to be
399    /// contained by the file. This implies that files for which `is_empty`
400    /// returns true still contain one byte position according to this function.
401    #[inline]
402    pub fn contains(&self, byte_pos: BytePos) -> bool {
403        byte_pos >= self.start_pos && byte_pos <= self.end_position()
404    }
405
406    #[inline]
407    pub fn is_empty(&self) -> bool {
408        self.source_len.to_u32() == 0
409    }
410
411    /// Calculates the original byte position relative to the start of the file
412    /// based on the given byte position.
413    pub fn original_relative_byte_pos(&self, pos: BytePos) -> RelativeBytePos {
414        let pos = self.relative_position(pos);
415        RelativeBytePos::from_u32(pos.0)
416    }
417}
418
419pub fn char_width(ch: char) -> usize {
420    match ch {
421        '\t' => 4,
422        _ => unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1),
423    }
424}