use crate::{BytePos, CharPos, Span};
use arc_swap::ArcSwapOption;
use once_map::OnceMap;
use solar_data_structures::{
map::FxBuildHasher,
sync::{MappedRwLockReadGuard, RwLock, RwLockReadGuard},
};
use std::{
fmt,
io::{self, Read},
ops::Range,
path::{Path, PathBuf},
sync::{Arc, OnceLock},
};
mod analyze;
mod file;
pub use file::*;
mod file_resolver;
pub(crate) use file_resolver::absolute_path;
pub use file_resolver::{FileResolver, ResolveError, apply_import_remappings};
#[cfg(test)]
mod tests;
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum SpanLinesError {
DistinctSources(Box<DistinctSources>),
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum SpanSnippetError {
IllFormedSpan(Span),
DistinctSources(Box<DistinctSources>),
MalformedForSourcemap(MalformedSourceMapPositions),
SourceNotAvailable { filename: FileName },
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct DistinctSources {
pub begin: (FileName, BytePos),
pub end: (FileName, BytePos),
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct MalformedSourceMapPositions {
pub name: FileName,
pub source_len: usize,
pub begin_pos: BytePos,
pub end_pos: BytePos,
}
#[derive(Clone, Debug)]
pub struct WithSourceFile<T, F = Arc<SourceFile>> {
pub file: F,
pub data: T,
}
impl<T, F> std::ops::Deref for WithSourceFile<T, F> {
type Target = T;
#[inline]
fn deref(&self) -> &Self::Target {
&self.data
}
}
impl<T, F> std::ops::DerefMut for WithSourceFile<T, F> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.data
}
}
impl<T: Clone> WithSourceFile<T, &Arc<SourceFile>> {
pub fn to_owned(&self) -> WithSourceFile<T> {
WithSourceFile { file: self.file.clone(), data: self.data.clone() }
}
}
impl<T> WithSourceFile<T, &Arc<SourceFile>> {
pub fn into_owned(self) -> WithSourceFile<T> {
WithSourceFile { file: self.file.clone(), data: self.data }
}
}
#[derive(Clone, Debug)]
pub struct Loc {
pub line: usize,
pub col: CharPos,
pub col_display: usize,
}
impl Default for Loc {
fn default() -> Self {
Self { line: 0, col: CharPos(0), col_display: 0 }
}
}
#[derive(Clone, Debug, Default)]
pub struct SpanLoc {
pub lo: Loc,
pub hi: Loc,
}
#[derive(Debug)]
pub struct SourceFileAndLine<F = Arc<SourceFile>> {
pub sf: F,
pub line: usize,
}
#[derive(Debug)]
pub struct SourceFileAndBytePos<F = Arc<SourceFile>> {
pub sf: F,
pub pos: BytePos,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct LineInfo {
pub line_index: usize,
pub start_col: CharPos,
pub end_col: CharPos,
}
pub type FileLines<F = Arc<SourceFile>> = WithSourceFile<Vec<LineInfo>, F>;
pub trait FileLoader: Send + Sync + 'static {
fn canonicalize_path(&self, path: &Path) -> io::Result<PathBuf>;
fn load_stdin(&self) -> io::Result<String>;
fn load_file(&self, path: &Path) -> io::Result<String>;
fn load_binary_file(&self, path: &Path) -> io::Result<Vec<u8>>;
}
pub struct RealFileLoader;
#[allow(clippy::disallowed_methods)] impl FileLoader for RealFileLoader {
fn canonicalize_path(&self, path: &Path) -> io::Result<PathBuf> {
crate::canonicalize(path)
}
fn load_stdin(&self) -> io::Result<String> {
let mut src = String::new();
io::stdin().read_to_string(&mut src)?;
Ok(src)
}
fn load_file(&self, path: &Path) -> io::Result<String> {
std::fs::read_to_string(path)
}
fn load_binary_file(&self, path: &Path) -> io::Result<Vec<u8>> {
std::fs::read(path)
}
}
#[derive(Debug)]
pub(crate) struct SourceRoots {
pub(crate) base_path: Option<PathBuf>,
pub(crate) include_paths: Vec<PathBuf>,
current_dir: Option<PathBuf>,
}
impl SourceRoots {
pub(crate) fn source_unit_name<'a>(&self, path: &'a Path) -> &'a Path {
let roots = self.base_path.iter().chain(&self.include_paths);
file_resolver::source_unit_name(path, roots, self.current_dir.as_deref())
}
}
#[derive(derive_more::Debug)]
pub struct SourceMap {
source_files: RwLock<Vec<Arc<SourceFile>>>,
#[debug(skip)]
name_to_file: OnceMap<FileName, Arc<SourceFile>, FxBuildHasher>,
roots: ArcSwapOption<SourceRoots>,
#[debug(skip)]
file_loader: OnceLock<Box<dyn FileLoader>>,
}
impl Default for SourceMap {
fn default() -> Self {
Self::empty()
}
}
impl SourceMap {
pub fn empty() -> Self {
Self {
source_files: Default::default(),
name_to_file: Default::default(),
roots: Default::default(),
file_loader: Default::default(),
}
}
pub fn clear(&mut self) {
let _ = self.take();
}
#[must_use]
pub fn take(&mut self) -> Vec<Arc<SourceFile>> {
self.name_to_file.clear();
std::mem::take(self.source_files.get_mut())
}
pub fn set_file_loader(&self, file_loader: impl FileLoader) {
if let Err(_prev) = self.file_loader.set(Box::new(file_loader)) {
warn!("file loader already set");
}
}
pub fn file_loader(&self) -> &dyn FileLoader {
self.file_loader.get().map(std::ops::Deref::deref).unwrap_or(&RealFileLoader)
}
pub(crate) fn set_roots(
&self,
base_path: Option<PathBuf>,
include_paths: Vec<PathBuf>,
current_dir: Option<PathBuf>,
) {
self.roots.store(Some(Arc::new(SourceRoots { base_path, include_paths, current_dir })));
}
pub(crate) fn roots(&self) -> arc_swap::Guard<Option<Arc<SourceRoots>>> {
self.roots.load()
}
pub fn is_empty(&self) -> bool {
self.files().is_empty()
}
pub fn parse_file_name(&self, s: &str) -> FileName {
match s {
"stdin" | "<stdin>" => FileName::Stdin,
s if s.starts_with('<') && s.ends_with('>') => {
FileName::Custom(s[1..s.len() - 1].to_string())
}
s => {
if let Some(file) = FileResolver::new(self).get_file(s.as_ref()).or_else(|| {
let files = self.files();
files
.iter()
.find(|file| self.filename_for_diagnostics(&file.name).to_string() == s)
.cloned()
}) {
file.name.clone()
} else {
FileName::Custom(s.to_string())
}
}
}
}
pub fn get_file(&self, path: impl Into<FileName>) -> Option<Arc<SourceFile>> {
self.get_file_ref(&path.into())
}
pub fn get_file_ref(&self, filename: &FileName) -> Option<Arc<SourceFile>> {
self.name_to_file.get_cloned(filename)
}
pub fn load_file(&self, path: &Path) -> io::Result<Arc<SourceFile>> {
self.load_file_with_name(path.into(), path)
}
pub fn load_file_with_name(&self, name: FileName, path: &Path) -> io::Result<Arc<SourceFile>> {
self.new_source_file_with(name, || self.file_loader().load_file(path))
}
pub fn load_stdin(&self) -> io::Result<Arc<SourceFile>> {
self.new_source_file_with(FileName::Stdin, || self.file_loader().load_stdin())
}
pub fn new_source_file(
&self,
name: impl Into<FileName>,
src: impl Into<String>,
) -> io::Result<Arc<SourceFile>> {
self.new_source_file_with(name.into(), || Ok(src.into()))
}
pub fn new_source_file_shared(
&self,
name: impl Into<FileName>,
src: Arc<String>,
) -> io::Result<Arc<SourceFile>> {
self.name_to_file.try_insert_cloned(name.into(), |name| {
let file = SourceFile::new(name.clone(), src)?;
self.append_source_file(file)
})
}
#[instrument(level = "debug", skip_all, fields(filename = %filename.display()))]
pub fn new_source_file_with(
&self,
filename: FileName,
get_src: impl FnOnce() -> io::Result<String>,
) -> io::Result<Arc<SourceFile>> {
self.name_to_file.try_insert_cloned(filename, |name| {
let file = SourceFile::new(name.clone(), Arc::new(get_src()?))?;
self.append_source_file(file)
})
}
fn append_source_file(&self, mut file: SourceFile) -> io::Result<Arc<SourceFile>> {
trace!(name=%file.name.display(), len=file.src.len(), loc=file.count_lines(), "adding to source map");
let source_files = &mut *self.source_files.write();
file.start_pos = BytePos(if let Some(last_file) = source_files.last() {
last_file.end_position().0.checked_add(1).ok_or(OffsetOverflowError(()))?
} else {
0
});
let file = Arc::new(file);
source_files.push(file.clone());
Ok(file)
}
pub fn files(&self) -> SourceMapFiles<'_> {
SourceMapFiles(RwLockReadGuard::map(self.source_files.read(), std::ops::Deref::deref))
}
pub fn filename_for_diagnostics<'a>(&self, filename: &'a FileName) -> FileNameDisplay<'a> {
FileNameDisplay { inner: filename, roots: self.roots() }
}
pub fn is_multiline(&self, span: Span) -> bool {
self.files().is_multiline(span)
}
pub fn span_to_snippet(&self, span: Span) -> Result<String, SpanSnippetError> {
self.files().span_to_snippet(span).map(str::to_owned)
}
pub fn span_to_prev_source(&self, sp: Span) -> Result<String, SpanSnippetError> {
self.files().span_to_prev_source(sp).map(str::to_owned)
}
pub fn lookup_byte_offset(&self, bpos: BytePos) -> SourceFileAndBytePos {
let files = self.files();
let SourceFileAndBytePos { sf, pos } = files.lookup_byte_offset(bpos);
SourceFileAndBytePos { sf: sf.clone(), pos }
}
pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize {
self.files().lookup_source_file_idx(pos)
}
pub fn lookup_source_file(&self, pos: BytePos) -> Arc<SourceFile> {
self.files().lookup_source_file(pos).clone()
}
pub fn lookup_char_pos(&self, pos: BytePos) -> WithSourceFile<Loc> {
self.files().lookup_char_pos(pos).into_owned()
}
pub fn lookup_line(&self, pos: BytePos) -> Result<SourceFileAndLine, Arc<SourceFile>> {
self.files()
.lookup_line(pos)
.map(|SourceFileAndLine { sf, line }| SourceFileAndLine { sf: sf.clone(), line })
.map_err(Arc::clone)
}
pub fn is_valid_span(&self, sp: Span) -> Result<WithSourceFile<SpanLoc>, SpanLinesError> {
self.files().is_valid_span(sp).map(|source| source.into_owned())
}
pub fn is_line_before_span_empty(&self, sp: Span) -> bool {
self.files().is_line_before_span_empty(sp)
}
pub fn span_to_lines(&self, sp: Span) -> Result<FileLines, SpanLinesError> {
self.files().span_to_lines(sp).map(|source| source.into_owned())
}
pub fn span_to_range(&self, sp: Span) -> Result<Range<usize>, SpanSnippetError> {
self.files().span_to_range(sp)
}
pub fn span_to_source(
&self,
sp: Span,
) -> Result<WithSourceFile<Range<usize>>, SpanSnippetError> {
self.files().span_to_source(sp).map(|source| source.into_owned())
}
pub fn span_to_diagnostic_string(&self, sp: Span) -> impl fmt::Display {
let (source_file, loc) = self.span_to_location_info(sp);
fmt::from_fn(move |f| {
let file_name = match &source_file {
Some(sf) => self.filename_for_diagnostics(&sf.name),
None => return f.write_str("no-location"),
};
let lo_line = loc.lo.line;
let lo_col = loc.lo.col.0 + 1;
let hi_line = loc.hi.line;
let hi_col = loc.hi.col.0 + 1;
write!(f, "{file_name}:{lo_line}:{lo_col}: {hi_line}:{hi_col}")
})
}
pub fn span_to_location_info(&self, sp: Span) -> (Option<Arc<SourceFile>>, SpanLoc) {
let files = self.files();
let (file, loc) = files.span_to_location_info(sp);
(file.cloned(), loc)
}
}
pub struct SourceMapFiles<'a>(MappedRwLockReadGuard<'a, [Arc<SourceFile>]>);
impl std::ops::Deref for SourceMapFiles<'_> {
type Target = [Arc<SourceFile>];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl SourceMapFiles<'_> {
pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize {
assert!(!self.is_empty(), "attempted to lookup source file in empty `SourceMap`");
self.partition_point(|file| file.start_pos <= pos) - 1
}
pub fn lookup_source_file(&self, pos: BytePos) -> &Arc<SourceFile> {
&self[self.lookup_source_file_idx(pos)]
}
pub fn lookup_byte_offset(&self, pos: BytePos) -> SourceFileAndBytePos<&Arc<SourceFile>> {
let sf = self.lookup_source_file(pos);
SourceFileAndBytePos { sf, pos: pos - sf.start_pos }
}
pub fn lookup_char_pos(&self, pos: BytePos) -> WithSourceFile<Loc, &Arc<SourceFile>> {
let file = self.lookup_source_file(pos);
let (line, col, col_display) = file.lookup_file_pos_with_col_display(pos);
WithSourceFile { file, data: Loc { line, col, col_display } }
}
pub fn lookup_line(
&self,
pos: BytePos,
) -> Result<SourceFileAndLine<&Arc<SourceFile>>, &Arc<SourceFile>> {
let sf = self.lookup_source_file(pos);
sf.lookup_line(sf.relative_position(pos))
.map(|line| SourceFileAndLine { sf, line })
.ok_or(sf)
}
pub fn is_multiline(&self, span: Span) -> bool {
let (f, end) = self.lookup_span_files(span);
if f.start_pos != end.start_pos {
return true;
}
let lo = f.relative_position(span.lo());
let hi = f.relative_position(span.hi());
f.lookup_line(lo) != f.lookup_line(hi)
}
pub fn is_valid_span(
&self,
sp: Span,
) -> Result<WithSourceFile<SpanLoc, &Arc<SourceFile>>, SpanLinesError> {
let (begin, end) = self.lookup_span_files(sp);
if begin.start_pos != end.start_pos {
return Err(SpanLinesError::DistinctSources(Box::new(DistinctSources {
begin: (begin.name.clone(), begin.start_pos),
end: (end.name.clone(), end.start_pos),
})));
}
let (line, col, col_display) = begin.lookup_file_pos_with_col_display(sp.lo());
let lo = Loc { line, col, col_display };
let (line, col, col_display) = begin.lookup_file_pos_with_col_display(sp.hi());
let hi = Loc { line, col, col_display };
Ok(WithSourceFile { file: begin, data: SpanLoc { lo, hi } })
}
pub fn span_to_lines(&self, sp: Span) -> Result<FileLines<&Arc<SourceFile>>, SpanLinesError> {
let WithSourceFile { file, data: SpanLoc { lo, hi } } = self.is_valid_span(sp)?;
assert!(hi.line >= lo.line);
if sp.is_dummy() {
return Ok(FileLines { file, data: Vec::new() });
}
let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
let mut start_col = lo.col;
let hi_line = hi.line.saturating_sub(1);
for line_index in lo.line.saturating_sub(1)..hi_line {
let line_len = file.get_line(line_index).map_or(0, |s| s.chars().count());
lines.push(LineInfo { line_index, start_col, end_col: CharPos::from_usize(line_len) });
start_col = CharPos::from_usize(0);
}
lines.push(LineInfo { line_index: hi_line, start_col, end_col: hi.col });
Ok(FileLines { file, data: lines })
}
pub fn span_to_source(
&self,
sp: Span,
) -> Result<WithSourceFile<Range<usize>, &Arc<SourceFile>>, SpanSnippetError> {
let (begin, end) = self.lookup_span_files(sp);
if begin.start_pos != end.start_pos {
return Err(SpanSnippetError::DistinctSources(Box::new(DistinctSources {
begin: (begin.name.clone(), begin.start_pos),
end: (end.name.clone(), end.start_pos),
})));
}
let begin_pos = sp.lo() - begin.start_pos;
let end_pos = sp.hi() - begin.start_pos;
let start_index = begin_pos.to_usize();
let end_index = end_pos.to_usize();
let source_len = begin.source_len.to_usize();
if start_index > end_index || end_index > source_len {
return Err(SpanSnippetError::MalformedForSourcemap(MalformedSourceMapPositions {
name: begin.name.clone(),
source_len,
begin_pos,
end_pos,
}));
}
Ok(WithSourceFile { file: begin, data: start_index..end_index })
}
pub fn span_to_snippet(&self, span: Span) -> Result<&str, SpanSnippetError> {
let WithSourceFile { file, data: range } = self.span_to_source(span)?;
file.src.get(range).ok_or(SpanSnippetError::IllFormedSpan(span))
}
pub fn span_to_prev_source(&self, sp: Span) -> Result<&str, SpanSnippetError> {
let WithSourceFile { file, data: range } = self.span_to_source(sp)?;
file.src.get(..range.start).ok_or(SpanSnippetError::IllFormedSpan(sp))
}
pub fn is_line_before_span_empty(&self, sp: Span) -> bool {
self.span_to_prev_source(sp)
.is_ok_and(|s| s.rsplit_once('\n').unwrap_or(("", s)).1.trim_start().is_empty())
}
pub fn span_to_range(&self, sp: Span) -> Result<Range<usize>, SpanSnippetError> {
self.span_to_source(sp).map(|source| source.data)
}
pub fn span_to_location_info(&self, sp: Span) -> (Option<&Arc<SourceFile>>, SpanLoc) {
if sp.is_dummy() || self.is_empty() {
return Default::default();
}
let Ok(WithSourceFile { file, data }) = self.is_valid_span(sp) else {
return Default::default();
};
(Some(file), data)
}
fn lookup_span_files(&self, sp: Span) -> (&Arc<SourceFile>, &Arc<SourceFile>) {
let begin = self.lookup_source_file(sp.lo());
let end = if (begin.start_pos..=begin.end_position()).contains(&sp.hi()) {
begin
} else {
self.lookup_source_file(sp.hi())
};
(begin, end)
}
}