solar_interface/source_map/
mod.rs1use crate::{BytePos, CharPos, Span};
4use arc_swap::ArcSwapOption;
5use once_map::OnceMap;
6use solar_data_structures::{
7 map::FxBuildHasher,
8 sync::{MappedRwLockReadGuard, RwLock, RwLockReadGuard},
9};
10use std::{
11 fmt,
12 io::{self, Read},
13 ops::Range,
14 path::{Path, PathBuf},
15 sync::{Arc, OnceLock},
16};
17
18mod analyze;
19
20mod file;
21pub use file::*;
22
23mod file_resolver;
24pub(crate) use file_resolver::absolute_path;
25pub use file_resolver::{FileResolver, ResolveError, apply_import_remappings};
26
27#[cfg(test)]
28mod tests;
29
30#[derive(Clone, PartialEq, Eq, Debug)]
31pub enum SpanLinesError {
32 DistinctSources(Box<DistinctSources>),
33}
34
35#[derive(Clone, PartialEq, Eq, Debug)]
40pub enum SpanSnippetError {
41 IllFormedSpan(Span),
42 DistinctSources(Box<DistinctSources>),
43 MalformedForSourcemap(MalformedSourceMapPositions),
44 SourceNotAvailable { filename: FileName },
45}
46
47#[derive(Clone, PartialEq, Eq, Debug)]
48pub struct DistinctSources {
49 pub begin: (FileName, BytePos),
50 pub end: (FileName, BytePos),
51}
52
53#[derive(Clone, PartialEq, Eq, Debug)]
54pub struct MalformedSourceMapPositions {
55 pub name: FileName,
56 pub source_len: usize,
57 pub begin_pos: BytePos,
58 pub end_pos: BytePos,
59}
60
61#[derive(Clone, Debug)]
63pub struct WithSourceFile<T, F = Arc<SourceFile>> {
64 pub file: F,
65 pub data: T,
66}
67
68impl<T, F> std::ops::Deref for WithSourceFile<T, F> {
69 type Target = T;
70
71 #[inline]
72 fn deref(&self) -> &Self::Target {
73 &self.data
74 }
75}
76
77impl<T, F> std::ops::DerefMut for WithSourceFile<T, F> {
78 #[inline]
79 fn deref_mut(&mut self) -> &mut Self::Target {
80 &mut self.data
81 }
82}
83
84impl<T: Clone> WithSourceFile<T, &Arc<SourceFile>> {
85 pub fn to_owned(&self) -> WithSourceFile<T> {
87 WithSourceFile { file: self.file.clone(), data: self.data.clone() }
88 }
89}
90
91impl<T> WithSourceFile<T, &Arc<SourceFile>> {
92 pub fn into_owned(self) -> WithSourceFile<T> {
94 WithSourceFile { file: self.file.clone(), data: self.data }
95 }
96}
97
98#[derive(Clone, Debug)]
100pub struct Loc {
101 pub line: usize,
103 pub col: CharPos,
105 pub col_display: usize,
107}
108
109impl Default for Loc {
110 fn default() -> Self {
111 Self { line: 0, col: CharPos(0), col_display: 0 }
112 }
113}
114
115#[derive(Clone, Debug, Default)]
120pub struct SpanLoc {
121 pub lo: Loc,
123 pub hi: Loc,
125}
126
127#[derive(Debug)]
129pub struct SourceFileAndLine<F = Arc<SourceFile>> {
130 pub sf: F,
131 pub line: usize,
133}
134
135#[derive(Debug)]
136pub struct SourceFileAndBytePos<F = Arc<SourceFile>> {
137 pub sf: F,
138 pub pos: BytePos,
139}
140
141#[derive(Copy, Clone, Debug, PartialEq, Eq)]
142pub struct LineInfo {
143 pub line_index: usize,
145
146 pub start_col: CharPos,
148
149 pub end_col: CharPos,
151}
152
153pub type FileLines<F = Arc<SourceFile>> = WithSourceFile<Vec<LineInfo>, F>;
154
155pub trait FileLoader: Send + Sync + 'static {
161 fn canonicalize_path(&self, path: &Path) -> io::Result<PathBuf>;
162 fn load_stdin(&self) -> io::Result<String>;
163 fn load_file(&self, path: &Path) -> io::Result<String>;
164 fn load_binary_file(&self, path: &Path) -> io::Result<Vec<u8>>;
165}
166
167pub struct RealFileLoader;
169
170#[allow(clippy::disallowed_methods)] impl FileLoader for RealFileLoader {
172 fn canonicalize_path(&self, path: &Path) -> io::Result<PathBuf> {
173 crate::canonicalize(path)
174 }
175
176 fn load_stdin(&self) -> io::Result<String> {
177 let mut src = String::new();
178 io::stdin().read_to_string(&mut src)?;
179 Ok(src)
180 }
181
182 fn load_file(&self, path: &Path) -> io::Result<String> {
183 std::fs::read_to_string(path)
184 }
185
186 fn load_binary_file(&self, path: &Path) -> io::Result<Vec<u8>> {
187 std::fs::read(path)
188 }
189}
190
191#[derive(Debug)]
194pub(crate) struct SourceRoots {
195 pub(crate) base_path: Option<PathBuf>,
196 pub(crate) include_paths: Vec<PathBuf>,
197 current_dir: Option<PathBuf>,
198}
199
200impl SourceRoots {
201 pub(crate) fn source_unit_name<'a>(&self, path: &'a Path) -> &'a Path {
203 let roots = self.base_path.iter().chain(&self.include_paths);
204 file_resolver::source_unit_name(path, roots, self.current_dir.as_deref())
205 }
206}
207
208#[derive(derive_more::Debug)]
210pub struct SourceMap {
211 source_files: RwLock<Vec<Arc<SourceFile>>>,
213 #[debug(skip)]
214 id_to_file: OnceMap<SourceFileId, Arc<SourceFile>, FxBuildHasher>,
215
216 roots: ArcSwapOption<SourceRoots>,
217 #[debug(skip)]
218 file_loader: OnceLock<Box<dyn FileLoader>>,
219}
220
221impl Default for SourceMap {
222 fn default() -> Self {
223 Self::empty()
224 }
225}
226
227impl SourceMap {
228 pub fn empty() -> Self {
230 Self {
231 source_files: Default::default(),
232 id_to_file: Default::default(),
233 roots: Default::default(),
234 file_loader: Default::default(),
235 }
236 }
237
238 pub fn clear(&mut self) {
240 let _ = self.take();
241 }
242
243 #[must_use]
245 pub fn take(&mut self) -> Vec<Arc<SourceFile>> {
246 self.id_to_file.clear();
247 std::mem::take(self.source_files.get_mut())
248 }
249
250 pub fn set_file_loader(&self, file_loader: impl FileLoader) {
255 if let Err(_prev) = self.file_loader.set(Box::new(file_loader)) {
256 warn!("file loader already set");
257 }
258 }
259
260 pub fn file_loader(&self) -> &dyn FileLoader {
264 self.file_loader.get().map(std::ops::Deref::deref).unwrap_or(&RealFileLoader)
265 }
266
267 pub(crate) fn set_roots(
272 &self,
273 base_path: Option<PathBuf>,
274 include_paths: Vec<PathBuf>,
275 current_dir: Option<PathBuf>,
276 ) {
277 self.roots.store(Some(Arc::new(SourceRoots { base_path, include_paths, current_dir })));
278 }
279
280 pub(crate) fn roots(&self) -> arc_swap::Guard<Option<Arc<SourceRoots>>> {
281 self.roots.load()
282 }
283
284 pub fn is_empty(&self) -> bool {
286 self.files().is_empty()
287 }
288
289 pub fn parse_file_name(&self, s: &str) -> FileName {
291 match s {
292 "stdin" | "<stdin>" => FileName::Stdin,
293 s if s.starts_with('<') && s.ends_with('>') => {
294 FileName::Custom(s[1..s.len() - 1].to_string())
295 }
296 s => {
297 if let Some(file) = FileResolver::new(self).get_file(s.as_ref()).or_else(|| {
298 let files = self.files();
299 files
300 .iter()
301 .find(|file| self.filename_for_diagnostics(&file.name).to_string() == s)
302 .cloned()
303 }) {
304 file.name.clone()
305 } else {
306 FileName::Custom(s.to_string())
307 }
308 }
309 }
310 }
311
312 pub fn get_file(&self, path: impl Into<FileName>) -> Option<Arc<SourceFile>> {
315 self.get_file_ref(&path.into())
316 }
317
318 pub fn get_file_ref(&self, filename: &FileName) -> Option<Arc<SourceFile>> {
321 self.id_to_file.get_cloned(&SourceFileId::new(filename))
322 }
323
324 pub fn load_file(&self, path: &Path) -> io::Result<Arc<SourceFile>> {
326 self.load_file_with_name(path.into(), path)
327 }
328
329 pub fn load_file_with_name(&self, name: FileName, path: &Path) -> io::Result<Arc<SourceFile>> {
331 self.new_source_file_with(name, || self.file_loader().load_file(path))
332 }
333
334 pub fn load_stdin(&self) -> io::Result<Arc<SourceFile>> {
336 self.new_source_file_with(FileName::Stdin, || self.file_loader().load_stdin())
337 }
338
339 pub fn new_source_file(
343 &self,
344 name: impl Into<FileName>,
345 src: impl Into<String>,
346 ) -> io::Result<Arc<SourceFile>> {
347 self.new_source_file_with(name.into(), || Ok(src.into()))
348 }
349
350 pub fn new_source_file_shared(
352 &self,
353 name: impl Into<FileName>,
354 src: Arc<String>,
355 ) -> io::Result<Arc<SourceFile>> {
356 let filename = name.into();
357 let id = SourceFileId::new(&filename);
358 self.id_to_file.try_insert_cloned(id, |&id| {
359 let file = SourceFile::new(filename, id, src)?;
360 self.append_source_file(file)
361 })
362 }
363
364 #[instrument(level = "debug", skip_all, fields(filename = %filename.display()))]
374 pub fn new_source_file_with(
375 &self,
376 filename: FileName,
377 get_src: impl FnOnce() -> io::Result<String>,
378 ) -> io::Result<Arc<SourceFile>> {
379 let id = SourceFileId::new(&filename);
380 self.id_to_file.try_insert_cloned(id, |&id| {
381 let file = SourceFile::new(filename, id, Arc::new(get_src()?))?;
382 self.append_source_file(file)
383 })
384 }
385
386 fn append_source_file(&self, mut file: SourceFile) -> io::Result<Arc<SourceFile>> {
387 trace!(name=%file.name.display(), len=file.src.len(), loc=file.count_lines(), "adding to source map");
388
389 let source_files = &mut *self.source_files.write();
390 file.start_pos = BytePos(if let Some(last_file) = source_files.last() {
391 last_file.end_position().0.checked_add(1).ok_or(OffsetOverflowError(()))?
394 } else {
395 0
396 });
397
398 let file = Arc::new(file);
399 source_files.push(file.clone());
400
401 Ok(file)
402 }
403
404 pub fn files(&self) -> SourceMapFiles<'_> {
406 SourceMapFiles(RwLockReadGuard::map(self.source_files.read(), std::ops::Deref::deref))
407 }
408
409 pub fn filename_for_diagnostics<'a>(&self, filename: &'a FileName) -> FileNameDisplay<'a> {
411 FileNameDisplay { inner: filename, roots: self.roots() }
412 }
413
414 pub fn is_multiline(&self, span: Span) -> bool {
416 self.files().is_multiline(span)
417 }
418
419 pub fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
421 self.files().span_to_snippet(span).map(str::to_owned)
422 }
423
424 pub fn span_to_prev_source(&self, sp: Span) -> Result<String, SpanSnippetError> {
426 self.files().span_to_prev_source(sp).map(str::to_owned)
427 }
428
429 pub fn lookup_byte_offset(&self, bpos: BytePos) -> SourceFileAndBytePos {
431 let files = self.files();
432 let SourceFileAndBytePos { sf, pos } = files.lookup_byte_offset(bpos);
433 SourceFileAndBytePos { sf: sf.clone(), pos }
434 }
435
436 pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize {
440 self.files().lookup_source_file_idx(pos)
441 }
442
443 pub fn lookup_source_file(&self, pos: BytePos) -> Arc<SourceFile> {
445 self.files().lookup_source_file(pos).clone()
446 }
447
448 pub fn lookup_char_pos(&self, pos: BytePos) -> WithSourceFile<Loc> {
450 self.files().lookup_char_pos(pos).into_owned()
451 }
452
453 pub fn lookup_line(&self, pos: BytePos) -> Result<SourceFileAndLine, Arc<SourceFile>> {
455 self.files()
456 .lookup_line(pos)
457 .map(|SourceFileAndLine { sf, line }| SourceFileAndLine { sf: sf.clone(), line })
458 .map_err(Arc::clone)
459 }
460
461 pub fn is_valid_span(&self, sp: Span) -> Result<WithSourceFile<SpanLoc>, SpanLinesError> {
462 self.files().is_valid_span(sp).map(|source| source.into_owned())
463 }
464
465 pub fn is_line_before_span_empty(&self, sp: Span) -> bool {
466 self.files().is_line_before_span_empty(sp)
467 }
468
469 pub fn span_to_lines(&self, sp: Span) -> Result<FileLines, SpanLinesError> {
471 self.files().span_to_lines(sp).map(|source| source.into_owned())
472 }
473
474 pub fn span_to_range(&self, sp: Span) -> Result<Range<usize>, SpanSnippetError> {
478 self.files().span_to_range(sp)
479 }
480
481 pub fn span_to_source(
483 &self,
484 sp: Span,
485 ) -> Result<WithSourceFile<Range<usize>>, SpanSnippetError> {
486 self.files().span_to_source(sp).map(|source| source.into_owned())
487 }
488
489 pub fn span_to_diagnostic_string(&self, sp: Span) -> impl fmt::Display {
493 let (source_file, loc) = self.span_to_location_info(sp);
494 fmt::from_fn(move |f| {
495 let file_name = match &source_file {
496 Some(sf) => self.filename_for_diagnostics(&sf.name),
497 None => return f.write_str("no-location"),
498 };
499 let lo_line = loc.lo.line;
500 let lo_col = loc.lo.col.0 + 1;
501 let hi_line = loc.hi.line;
502 let hi_col = loc.hi.col.0 + 1;
503 write!(f, "{file_name}:{lo_line}:{lo_col}: {hi_line}:{hi_col}")
504 })
505 }
506
507 pub fn span_to_location_info(&self, sp: Span) -> (Option<Arc<SourceFile>>, SpanLoc) {
511 let files = self.files();
512 let (file, loc) = files.span_to_location_info(sp);
513 (file.cloned(), loc)
514 }
515}
516
517pub struct SourceMapFiles<'a>(MappedRwLockReadGuard<'a, [Arc<SourceFile>]>);
523
524impl std::ops::Deref for SourceMapFiles<'_> {
525 type Target = [Arc<SourceFile>];
526
527 fn deref(&self) -> &Self::Target {
528 &self.0
529 }
530}
531
532impl SourceMapFiles<'_> {
533 pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize {
535 assert!(!self.is_empty(), "attempted to lookup source file in empty `SourceMap`");
536 self.partition_point(|file| file.start_pos <= pos) - 1
537 }
538
539 pub fn lookup_source_file(&self, pos: BytePos) -> &Arc<SourceFile> {
541 &self[self.lookup_source_file_idx(pos)]
542 }
543
544 pub fn lookup_byte_offset(&self, pos: BytePos) -> SourceFileAndBytePos<&Arc<SourceFile>> {
546 let sf = self.lookup_source_file(pos);
547 SourceFileAndBytePos { sf, pos: pos - sf.start_pos }
548 }
549
550 pub fn lookup_char_pos(&self, pos: BytePos) -> WithSourceFile<Loc, &Arc<SourceFile>> {
552 let file = self.lookup_source_file(pos);
553 let (line, col, col_display) = file.lookup_file_pos_with_col_display(pos);
554 WithSourceFile { file, data: Loc { line, col, col_display } }
555 }
556
557 pub fn lookup_line(
559 &self,
560 pos: BytePos,
561 ) -> Result<SourceFileAndLine<&Arc<SourceFile>>, &Arc<SourceFile>> {
562 let sf = self.lookup_source_file(pos);
563 sf.lookup_line(sf.relative_position(pos))
564 .map(|line| SourceFileAndLine { sf, line })
565 .ok_or(sf)
566 }
567
568 pub fn is_multiline(&self, span: Span) -> bool {
570 let (f, end) = self.lookup_span_files(span);
571 if f.start_pos != end.start_pos {
572 return true;
573 }
574 let lo = f.relative_position(span.lo());
575 let hi = f.relative_position(span.hi());
576 f.lookup_line(lo) != f.lookup_line(hi)
577 }
578
579 pub fn is_valid_span(
581 &self,
582 sp: Span,
583 ) -> Result<WithSourceFile<SpanLoc, &Arc<SourceFile>>, SpanLinesError> {
584 let (begin, end) = self.lookup_span_files(sp);
585 if begin.start_pos != end.start_pos {
586 return Err(SpanLinesError::DistinctSources(Box::new(DistinctSources {
587 begin: (begin.name.clone(), begin.start_pos),
588 end: (end.name.clone(), end.start_pos),
589 })));
590 }
591 let (line, col, col_display) = begin.lookup_file_pos_with_col_display(sp.lo());
592 let lo = Loc { line, col, col_display };
593 let (line, col, col_display) = begin.lookup_file_pos_with_col_display(sp.hi());
594 let hi = Loc { line, col, col_display };
595 Ok(WithSourceFile { file: begin, data: SpanLoc { lo, hi } })
596 }
597
598 pub fn span_to_lines(&self, sp: Span) -> Result<FileLines<&Arc<SourceFile>>, SpanLinesError> {
600 let WithSourceFile { file, data: SpanLoc { lo, hi } } = self.is_valid_span(sp)?;
601 assert!(hi.line >= lo.line);
602
603 if sp.is_dummy() {
604 return Ok(FileLines { file, data: Vec::new() });
605 }
606
607 let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
608
609 let mut start_col = lo.col;
612
613 let hi_line = hi.line.saturating_sub(1);
621 for line_index in lo.line.saturating_sub(1)..hi_line {
622 let line_len = file.get_line(line_index).map_or(0, |s| s.chars().count());
623 lines.push(LineInfo { line_index, start_col, end_col: CharPos::from_usize(line_len) });
624 start_col = CharPos::from_usize(0);
625 }
626
627 lines.push(LineInfo { line_index: hi_line, start_col, end_col: hi.col });
629
630 Ok(FileLines { file, data: lines })
631 }
632
633 pub fn span_to_source(
635 &self,
636 sp: Span,
637 ) -> Result<WithSourceFile<Range<usize>, &Arc<SourceFile>>, SpanSnippetError> {
638 let (begin, end) = self.lookup_span_files(sp);
639 if begin.start_pos != end.start_pos {
640 return Err(SpanSnippetError::DistinctSources(Box::new(DistinctSources {
641 begin: (begin.name.clone(), begin.start_pos),
642 end: (end.name.clone(), end.start_pos),
643 })));
644 }
645
646 let begin_pos = sp.lo() - begin.start_pos;
647 let end_pos = sp.hi() - begin.start_pos;
648 let start_index = begin_pos.to_usize();
649 let end_index = end_pos.to_usize();
650 let source_len = begin.source_len.to_usize();
651
652 if start_index > end_index || end_index > source_len {
653 return Err(SpanSnippetError::MalformedForSourcemap(MalformedSourceMapPositions {
654 name: begin.name.clone(),
655 source_len,
656 begin_pos,
657 end_pos,
658 }));
659 }
660
661 Ok(WithSourceFile { file: begin, data: start_index..end_index })
662 }
663
664 pub fn span_to_snippet(&self, span: Span) -> Result<&str, SpanSnippetError> {
666 let WithSourceFile { file, data: range } = self.span_to_source(span)?;
667 file.src.get(range).ok_or(SpanSnippetError::IllFormedSpan(span))
668 }
669
670 pub fn span_to_prev_source(&self, sp: Span) -> Result<&str, SpanSnippetError> {
672 let WithSourceFile { file, data: range } = self.span_to_source(sp)?;
673 file.src.get(..range.start).ok_or(SpanSnippetError::IllFormedSpan(sp))
674 }
675
676 pub fn is_line_before_span_empty(&self, sp: Span) -> bool {
678 self.span_to_prev_source(sp)
679 .is_ok_and(|s| s.rsplit_once('\n').unwrap_or(("", s)).1.trim_start().is_empty())
680 }
681
682 pub fn span_to_range(&self, sp: Span) -> Result<Range<usize>, SpanSnippetError> {
684 self.span_to_source(sp).map(|source| source.data)
685 }
686
687 pub fn span_to_location_info(&self, sp: Span) -> (Option<&Arc<SourceFile>>, SpanLoc) {
689 if sp.is_dummy() || self.is_empty() {
690 return Default::default();
691 }
692 let Ok(WithSourceFile { file, data }) = self.is_valid_span(sp) else {
693 return Default::default();
694 };
695 (Some(file), data)
696 }
697
698 fn lookup_span_files(&self, sp: Span) -> (&Arc<SourceFile>, &Arc<SourceFile>) {
699 let begin = self.lookup_source_file(sp.lo());
700 let end = if (begin.start_pos..=begin.end_position()).contains(&sp.hi()) {
701 begin
702 } else {
703 self.lookup_source_file(sp.hi())
704 };
705 (begin, end)
706 }
707}