Skip to main content

xur_span/
source_map.rs

1//! Every source file in a session, after `rustc_span::source_map`.
2//!
3//! Files are laid out one after another in a single global space of byte
4//! positions, so a [`Span`] identifies its file as well as its location and
5//! spans from different files never collide.
6
7use std::collections::HashMap;
8use std::fmt;
9use std::io;
10use std::path::{Path, PathBuf};
11use std::sync::Arc;
12
13use crate::Span;
14
15/// A 1-based line and column. The column counts characters, not bytes.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub struct LineCol {
18    pub line: u32,
19    pub col: u32,
20}
21
22impl fmt::Display for LineCol {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        write!(f, "{}:{}", self.line, self.col)
25    }
26}
27
28/// A loaded source file and the global positions it occupies.
29#[derive(Debug)]
30pub struct SourceFile {
31    /// The name shown in diagnostics, usually the path as given.
32    pub name: String,
33    pub src: String,
34    /// Global position of the file's first byte.
35    pub start: usize,
36    /// Byte offset (within the file) at which each line starts.
37    line_starts: Vec<usize>,
38}
39
40impl SourceFile {
41    fn new(name: String, src: String, start: usize) -> Self {
42        let line_starts = std::iter::once(0)
43            .chain(src.match_indices('\n').map(|(i, _)| i + 1))
44            .collect();
45        Self {
46            name,
47            src,
48            start,
49            line_starts,
50        }
51    }
52
53    /// Global position one past the file's last byte.
54    pub fn end(&self) -> usize {
55        self.start + self.src.len()
56    }
57
58    /// The span of the whole file.
59    pub fn span(&self) -> Span {
60        Span::new(self.start, self.end())
61    }
62
63    pub fn contains(&self, pos: usize) -> bool {
64        (self.start..=self.end()).contains(&pos)
65    }
66
67    /// The source text covered by `span`, which must lie in this file.
68    pub fn slice(&self, span: Span) -> &str {
69        &self.src[span.start - self.start..span.end - self.start]
70    }
71
72    /// The line/column of global position `pos`, which may be the end of
73    /// the file.
74    pub fn line_col(&self, pos: usize) -> LineCol {
75        let offset = pos - self.start;
76        let line = self.line_starts.partition_point(|&start| start <= offset) - 1;
77        let line_start = self.line_starts[line];
78        let col = self.src[line_start..offset].chars().count();
79        LineCol {
80            line: line as u32 + 1,
81            col: col as u32 + 1,
82        }
83    }
84}
85
86/// Reads source files; abstracted so tests can supply files from memory
87/// (rustc's `FileLoader`).
88pub trait FileLoader: Send + Sync {
89    fn read_file(&self, path: &Path) -> io::Result<String>;
90}
91
92/// Reads files from disk.
93pub struct RealFileLoader;
94
95impl FileLoader for RealFileLoader {
96    fn read_file(&self, path: &Path) -> io::Result<String> {
97        std::fs::read_to_string(path)
98    }
99}
100
101/// Serves files from memory, for tests and for embedding scripts that
102/// aren't on disk.
103#[derive(Debug, Default)]
104pub struct MemoryFileLoader {
105    files: HashMap<PathBuf, String>,
106}
107
108impl MemoryFileLoader {
109    pub fn new<'a>(files: impl IntoIterator<Item = (&'a str, &'a str)>) -> Self {
110        Self {
111            files: files
112                .into_iter()
113                .map(|(path, src)| (PathBuf::from(path), src.to_owned()))
114                .collect(),
115        }
116    }
117}
118
119impl FileLoader for MemoryFileLoader {
120    fn read_file(&self, path: &Path) -> io::Result<String> {
121        self.files
122            .get(path)
123            .cloned()
124            .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "file not found"))
125    }
126}
127
128#[derive(Debug, Default)]
129pub struct SourceMap {
130    files: Vec<Arc<SourceFile>>,
131}
132
133impl SourceMap {
134    pub fn new() -> Self {
135        Self::default()
136    }
137
138    /// Adds a file after all existing ones. A one-byte gap is left between
139    /// files so that the end-of-file position of one is not the start of
140    /// the next.
141    pub fn add_file(&mut self, name: impl Into<String>, src: impl Into<String>) -> Arc<SourceFile> {
142        let start = self.files.last().map_or(0, |file| file.end() + 1);
143        let file = Arc::new(SourceFile::new(name.into(), src.into(), start));
144        self.files.push(Arc::clone(&file));
145        file
146    }
147
148    pub fn files(&self) -> &[Arc<SourceFile>] {
149        &self.files
150    }
151
152    /// The file containing global position `pos`.
153    pub fn lookup_file(&self, pos: usize) -> &Arc<SourceFile> {
154        let index = self.files.partition_point(|file| file.start <= pos) - 1;
155        let file = &self.files[index];
156        debug_assert!(file.contains(pos), "position {pos} is in no file");
157        file
158    }
159
160    /// The source text covered by `span`.
161    pub fn slice(&self, span: Span) -> &str {
162        self.lookup_file(span.start).slice(span)
163    }
164
165    /// `name:line:col` for the start of `span`.
166    pub fn describe_pos(&self, span: Span) -> String {
167        let file = self.lookup_file(span.start);
168        format!("{}:{}", file.name, file.line_col(span.start))
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    fn single(src: &str) -> Arc<SourceFile> {
177        SourceMap::new().add_file("test.xur", src)
178    }
179
180    #[test]
181    fn line_col_first_line() {
182        let file = single("let x");
183        assert_eq!(file.line_col(0), LineCol { line: 1, col: 1 });
184        assert_eq!(file.line_col(4), LineCol { line: 1, col: 5 });
185    }
186
187    #[test]
188    fn line_col_after_newlines() {
189        let file = single("a\nbc\n\nd");
190        assert_eq!(file.line_col(2), LineCol { line: 2, col: 1 });
191        assert_eq!(file.line_col(3), LineCol { line: 2, col: 2 });
192        assert_eq!(file.line_col(5), LineCol { line: 3, col: 1 });
193        assert_eq!(file.line_col(6), LineCol { line: 4, col: 1 });
194    }
195
196    #[test]
197    fn line_col_counts_chars_not_bytes() {
198        // `α` is two bytes wide.
199        assert_eq!(single("α = 1").line_col(3), LineCol { line: 1, col: 3 });
200    }
201
202    #[test]
203    fn line_col_at_end_of_input() {
204        let file = single("a\nb");
205        assert_eq!(file.line_col(file.end()), LineCol { line: 2, col: 2 });
206    }
207
208    #[test]
209    fn files_occupy_disjoint_positions() {
210        let mut map = SourceMap::new();
211        let a = map.add_file("a.xur", "let a");
212        let b = map.add_file("b.xur", "let bb");
213        assert_eq!(a.span(), Span::new(0, 5));
214        assert_eq!(b.span(), Span::new(6, 12));
215        assert_eq!(map.lookup_file(5).name, "a.xur");
216        assert_eq!(map.lookup_file(6).name, "b.xur");
217        assert_eq!(map.slice(Span::new(10, 12)), "bb");
218        assert_eq!(b.line_col(10), LineCol { line: 1, col: 5 });
219        assert_eq!(map.describe_pos(Span::new(10, 12)), "b.xur:1:5");
220    }
221}