#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct FileId(pub u32);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Span {
pub file: FileId,
pub start: u32,
pub end: u32,
}
impl Span {
pub const fn new(file: FileId, start: u32, end: u32) -> Self {
Self { file, start, end }
}
pub fn cover(self, other: Self) -> Self {
if self.file != other.file {
return self;
}
Self::new(
self.file,
self.start.min(other.start),
self.end.max(other.end),
)
}
pub fn slice(self, text: &str) -> Option<&str> {
text.get(self.start as usize..self.end as usize)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Location<'a> {
pub name: &'a str,
pub line: usize,
pub column: usize,
}
#[derive(Debug)]
struct File {
name: String,
text: String,
lines: Vec<usize>,
}
#[derive(Debug, Default)]
pub struct SourceMap {
files: Vec<File>,
}
impl SourceMap {
pub fn new() -> Self {
Self::default()
}
pub(crate) fn next_file_id(&self) -> Option<FileId> {
u32::try_from(self.files.len()).ok().map(FileId)
}
pub fn add(&mut self, name: impl Into<String>, text: impl Into<String>) -> Option<FileId> {
let text = text.into();
u32::try_from(text.len()).ok()?;
let id = FileId(u32::try_from(self.files.len()).ok()?);
let mut lines = vec![0];
let mut bytes = text.bytes().enumerate().peekable();
while let Some((index, byte)) = bytes.next() {
if byte == b'\r' && bytes.peek().is_some_and(|(_, next)| *next == b'\n') {
bytes.next();
lines.push(index + 2);
} else if matches!(byte, b'\r' | b'\n') {
lines.push(index + 1);
}
}
self.files.push(File {
name: name.into(),
text,
lines,
});
Some(id)
}
pub fn source(&self, id: FileId) -> Option<&str> {
Some(&self.files.get(id.0 as usize)?.text)
}
pub fn location(&self, span: Span) -> Option<Location<'_>> {
let file = self.files.get(span.file.0 as usize)?;
let offset = span.start as usize;
let line = file.lines.partition_point(|start| *start <= offset);
let prefix = file.text.get(file.lines[line - 1]..offset)?;
Some(Location {
name: &file.name,
line,
column: prefix.chars().count() + 1,
})
}
}