1use std::collections::HashMap;
8use std::fmt;
9use std::io;
10use std::path::{Path, PathBuf};
11use std::sync::Arc;
12
13use crate::Span;
14
15#[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#[derive(Debug)]
30pub struct SourceFile {
31 pub name: String,
33 pub src: String,
34 pub start: usize,
36 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 pub fn end(&self) -> usize {
55 self.start + self.src.len()
56 }
57
58 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 pub fn slice(&self, span: Span) -> &str {
69 &self.src[span.start - self.start..span.end - self.start]
70 }
71
72 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
86pub trait FileLoader: Send + Sync {
89 fn read_file(&self, path: &Path) -> io::Result<String>;
90}
91
92pub 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#[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
128pub struct OverlayFileLoader {
130 overrides: HashMap<PathBuf, String>,
131}
132
133impl OverlayFileLoader {
134 pub fn new(overrides: HashMap<PathBuf, String>) -> Self {
135 Self { overrides }
136 }
137}
138
139impl FileLoader for OverlayFileLoader {
140 fn read_file(&self, path: &Path) -> io::Result<String> {
141 if let Some(src) = self.overrides.get(path) {
142 return Ok(src.clone());
143 }
144 RealFileLoader.read_file(path)
145 }
146}
147
148#[derive(Debug, Default)]
149pub struct SourceMap {
150 files: Vec<Arc<SourceFile>>,
151}
152
153impl SourceMap {
154 pub fn new() -> Self {
155 Self::default()
156 }
157
158 pub fn add_file(&mut self, name: impl Into<String>, src: impl Into<String>) -> Arc<SourceFile> {
162 let start = self.files.last().map_or(0, |file| file.end() + 1);
163 let file = Arc::new(SourceFile::new(name.into(), src.into(), start));
164 self.files.push(Arc::clone(&file));
165 file
166 }
167
168 pub fn files(&self) -> &[Arc<SourceFile>] {
169 &self.files
170 }
171
172 pub fn lookup_file(&self, pos: usize) -> &Arc<SourceFile> {
174 let index = self.files.partition_point(|file| file.start <= pos) - 1;
175 let file = &self.files[index];
176 debug_assert!(file.contains(pos), "position {pos} is in no file");
177 file
178 }
179
180 pub fn slice(&self, span: Span) -> &str {
182 self.lookup_file(span.start).slice(span)
183 }
184
185 pub fn describe_pos(&self, span: Span) -> String {
187 let file = self.lookup_file(span.start);
188 format!("{}:{}", file.name, file.line_col(span.start))
189 }
190}
191
192#[cfg(test)]
193mod tests {
194 use super::*;
195
196 fn single(src: &str) -> Arc<SourceFile> {
197 SourceMap::new().add_file("test.xur", src)
198 }
199
200 #[test]
201 fn line_col_first_line() {
202 let file = single("let x");
203 assert_eq!(file.line_col(0), LineCol { line: 1, col: 1 });
204 assert_eq!(file.line_col(4), LineCol { line: 1, col: 5 });
205 }
206
207 #[test]
208 fn line_col_after_newlines() {
209 let file = single("a\nbc\n\nd");
210 assert_eq!(file.line_col(2), LineCol { line: 2, col: 1 });
211 assert_eq!(file.line_col(3), LineCol { line: 2, col: 2 });
212 assert_eq!(file.line_col(5), LineCol { line: 3, col: 1 });
213 assert_eq!(file.line_col(6), LineCol { line: 4, col: 1 });
214 }
215
216 #[test]
217 fn line_col_counts_chars_not_bytes() {
218 assert_eq!(single("α = 1").line_col(3), LineCol { line: 1, col: 3 });
220 }
221
222 #[test]
223 fn line_col_at_end_of_input() {
224 let file = single("a\nb");
225 assert_eq!(file.line_col(file.end()), LineCol { line: 2, col: 2 });
226 }
227
228 #[test]
229 fn overlay_loader_prefers_memory() {
230 let path = PathBuf::from("/nonexistent/test.xur");
231 let mut overrides = HashMap::new();
232 overrides.insert(path.clone(), "memory content".into());
233 let loader = OverlayFileLoader::new(overrides);
234
235 assert_eq!(loader.read_file(&path).unwrap(), "memory content");
236 assert!(
237 loader
238 .read_file(Path::new("/nonexistent/other.xur"))
239 .is_err()
240 );
241 }
242
243 #[test]
244 fn files_occupy_disjoint_positions() {
245 let mut map = SourceMap::new();
246 let a = map.add_file("a.xur", "let a");
247 let b = map.add_file("b.xur", "let bb");
248 assert_eq!(a.span(), Span::new(0, 5));
249 assert_eq!(b.span(), Span::new(6, 12));
250 assert_eq!(map.lookup_file(5).name, "a.xur");
251 assert_eq!(map.lookup_file(6).name, "b.xur");
252 assert_eq!(map.slice(Span::new(10, 12)), "bb");
253 assert_eq!(b.line_col(10), LineCol { line: 1, col: 5 });
254 assert_eq!(map.describe_pos(Span::new(10, 12)), "b.xur:1:5");
255 }
256}