use camino::Utf8PathBuf;
use crate::IndexVec;
use crate::span::{FileId, LineCol, Span};
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub enum SourceName {
Real(Utf8PathBuf),
Anon(String),
}
impl std::fmt::Display for SourceName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SourceName::Real(path) => write!(f, "{path}"),
SourceName::Anon(label) => write!(f, "<{label}>"),
}
}
}
#[derive(Clone, Debug)]
pub struct SourceFile {
id: FileId,
name: SourceName,
text: String,
line_starts: Vec<u32>,
}
impl SourceFile {
pub const fn id(&self) -> FileId {
self.id
}
pub const fn name(&self) -> &SourceName {
&self.name
}
pub fn text(&self) -> &str {
&self.text
}
pub fn len(&self) -> u32 {
u32::try_from(self.text.len()).expect("source length fits in u32")
}
pub fn is_empty(&self) -> bool {
self.text.is_empty()
}
pub fn line_count(&self) -> usize {
self.line_starts.len()
}
pub fn line_col(&self, offset: u32) -> LineCol {
let position = crate::widen(offset);
assert!(
position <= self.text.len(),
"offset {position} lies past the end of {} ({} bytes)",
self.name,
self.text.len(),
);
let line_index = self.line_index(offset);
let line_start = crate::widen(self.line_starts[line_index]);
let prefix = self
.text
.get(line_start..position)
.unwrap_or_else(|| panic!("offset {position} is not a character boundary"));
LineCol {
line: u32::try_from(line_index + 1).expect("line number fits in u32"),
column: u32::try_from(prefix.chars().count() + 1).expect("column fits in u32"),
}
}
pub fn offset(&self, at: LineCol) -> Option<u32> {
let index = crate::widen(at.line).checked_sub(1)?;
let column = crate::widen(at.column).checked_sub(1)?;
let start = crate::widen(*self.line_starts.get(index)?);
let end = self
.line_starts
.get(index + 1)
.map_or(self.text.len(), |next| crate::widen(*next));
let line = &self.text[start..end];
let within = line
.char_indices()
.map(|(at, _)| at)
.chain((end == self.text.len()).then_some(line.len()))
.nth(column)?;
u32::try_from(start + within).ok()
}
pub fn line_index(&self, offset: u32) -> usize {
match self.line_starts.binary_search(&offset) {
Ok(exact) => exact,
Err(next) => next - 1,
}
}
pub fn line_text(&self, index: usize) -> &str {
let start = crate::widen(self.line_starts[index]);
let end = self
.line_starts
.get(index + 1)
.map_or(self.text.len(), |next| crate::widen(*next));
let line = &self.text[start..end];
let line = line.strip_suffix('\n').unwrap_or(line);
line.strip_suffix('\r').unwrap_or(line)
}
pub fn snippet(&self, span: Span) -> &str {
assert_eq!(span.file(), self.id, "span names another file");
self.text.get(span.range()).unwrap_or_else(|| {
panic!(
"span {span:?} does not cover whole characters of {}",
self.name
)
})
}
fn new(id: FileId, name: SourceName, text: String) -> Self {
let mut line_starts = vec![0_u32];
for (offset, byte) in text.bytes().enumerate() {
if byte == b'\n' && offset + 1 < text.len() {
line_starts.push(u32::try_from(offset + 1).expect("line start offset fits in u32"));
}
}
Self {
id,
name,
text,
line_starts,
}
}
}
#[derive(Clone, Debug, Default)]
pub struct SourceMap {
files: IndexVec<FileId, SourceFile>,
}
impl SourceMap {
pub fn new() -> Self {
Self::default()
}
pub fn add(&mut self, name: SourceName, text: String) -> FileId {
assert!(
u32::try_from(text.len()).is_ok(),
"source {name} is larger than the u32 offset range",
);
let id = self.files.next_index();
self.files.push(SourceFile::new(id, name, text));
id
}
pub fn file(&self, id: FileId) -> &SourceFile {
self.files
.get(id)
.unwrap_or_else(|| panic!("{id:?} does not belong to this source map"))
}
pub fn get(&self, id: FileId) -> Option<&SourceFile> {
self.files.get(id)
}
pub fn snippet(&self, span: Span) -> &str {
self.file(span.file()).snippet(span)
}
pub fn line_col(&self, span: Span) -> LineCol {
self.file(span.file()).line_col(span.lo())
}
pub fn len(&self) -> usize {
self.files.len()
}
pub fn is_empty(&self) -> bool {
self.files.is_empty()
}
pub fn iter(&self) -> impl Iterator<Item = &SourceFile> {
self.files.iter()
}
}
#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod tests {
use super::{SourceFile, SourceMap, SourceName};
use crate::Idx as _;
use crate::span::{FileId, LineCol, Span};
use camino::Utf8PathBuf;
fn map_with(text: &str) -> (SourceMap, FileId) {
let mut map = SourceMap::new();
let id = map.add(SourceName::Anon("fixture".to_owned()), text.to_owned());
(map, id)
}
#[test]
fn a_source_name_renders_for_a_reader() {
assert_eq!(
SourceName::Real(Utf8PathBuf::from("a/b.flow")).to_string(),
"a/b.flow"
);
assert_eq!(SourceName::Anon("stdin".to_owned()).to_string(), "<stdin>");
}
#[test]
fn an_offset_is_found_from_the_line_and_column_it_is_at() {
let (map, id) = map_with("a\u{e9}b\ncd");
let file = map.file(id);
for offset in [0, 1, 3, 4, 5, 6, 7] {
assert_eq!(file.offset(file.line_col(offset)), Some(offset));
}
let at = |line, column| LineCol { line, column };
assert_eq!(file.offset(at(1, 5)), None, "past the line break");
assert_eq!(file.offset(at(2, 4)), None, "past the file's end");
assert_eq!(file.offset(at(3, 1)), None);
assert_eq!(file.offset(at(0, 1)), None);
assert_eq!(file.offset(at(1, 0)), None);
}
#[test]
fn a_file_reports_the_text_it_was_added_with() {
let (map, id) = map_with("flow main() {}\n");
let file = map.file(id);
assert_eq!(file.id(), id);
assert_eq!(file.name(), &SourceName::Anon("fixture".to_owned()));
assert_eq!(file.text(), "flow main() {}\n");
assert_eq!(file.len(), 15);
assert!(!file.is_empty());
}
#[test]
fn an_empty_file_still_has_one_line() {
let (map, id) = map_with("");
let file = map.file(id);
assert!(file.is_empty());
assert_eq!(file.len(), 0);
assert_eq!(file.line_count(), 1);
assert_eq!(file.line_text(0), "");
assert_eq!(file.line_col(0), LineCol { line: 1, column: 1 });
}
#[test]
fn a_trailing_newline_opens_no_extra_line() {
let (map, id) = map_with("one\ntwo\n");
let file = map.file(id);
assert_eq!(file.line_count(), 2);
assert_eq!(file.line_text(0), "one");
assert_eq!(file.line_text(1), "two");
}
#[test]
fn a_missing_trailing_newline_leaves_the_last_line_whole() {
let (map, id) = map_with("one\ntwo");
let file = map.file(id);
assert_eq!(file.line_count(), 2);
assert_eq!(file.line_text(1), "two");
}
#[test]
fn a_carriage_return_is_not_part_of_the_line() {
let (map, id) = map_with("one\r\ntwo\r\n");
let file = map.file(id);
assert_eq!(file.line_count(), 2);
assert_eq!(file.line_text(0), "one");
assert_eq!(file.line_text(1), "two");
}
#[test]
fn a_blank_line_between_two_lines_is_its_own_line() {
let (map, id) = map_with("one\n\ntwo\n");
let file = map.file(id);
assert_eq!(file.line_count(), 3);
assert_eq!(file.line_text(1), "");
}
#[test]
fn a_position_maps_to_its_one_based_line_and_column() {
let (map, id) = map_with("one\ntwo\nthree");
let file = map.file(id);
assert_eq!(file.line_col(0), LineCol { line: 1, column: 1 });
assert_eq!(file.line_col(2), LineCol { line: 1, column: 3 });
assert_eq!(file.line_col(3), LineCol { line: 1, column: 4 });
assert_eq!(file.line_col(4), LineCol { line: 2, column: 1 });
assert_eq!(file.line_col(8), LineCol { line: 3, column: 1 });
assert_eq!(file.line_col(13), LineCol { line: 3, column: 6 });
}
#[test]
fn a_column_counts_characters_rather_than_bytes() {
let (map, id) = map_with("héllo");
let file = map.file(id);
assert_eq!(file.len(), 6);
assert_eq!(file.line_col(3), LineCol { line: 1, column: 3 });
assert_eq!(file.line_col(6), LineCol { line: 1, column: 6 });
}
#[test]
fn a_span_reads_back_as_the_text_it_covers() {
let (map, id) = map_with("flow main() {}\n");
let extent = Span::from_bounds(id, 5, 9);
assert_eq!(map.file(id).snippet(extent), "main");
assert_eq!(map.snippet(extent), "main");
assert_eq!(map.line_col(extent), LineCol { line: 1, column: 6 });
}
#[test]
fn a_map_holds_its_files_in_the_order_they_were_added() {
let mut map = SourceMap::default();
assert!(map.is_empty());
assert_eq!(map.len(), 0);
let first = map.add(SourceName::Anon("a".to_owned()), "one".to_owned());
let second = map.add(
SourceName::Real(Utf8PathBuf::from("b.flow")),
"two".to_owned(),
);
assert_eq!(map.len(), 2);
assert!(!map.is_empty());
assert_eq!(first, FileId::from_usize(0));
assert_eq!(second, FileId::from_usize(1));
assert_eq!(
map.iter().map(SourceFile::text).collect::<Vec<_>>(),
["one", "two"]
);
assert_eq!(map.get(first).map(SourceFile::text), Some("one"));
assert!(map.get(FileId::from_usize(2)).is_none());
}
#[test]
#[should_panic(expected = "does not belong to this source map")]
fn reading_a_foreign_file_id_is_a_defect() {
let (map, _) = map_with("one");
let _ = map.file(FileId::from_usize(1));
}
#[test]
#[should_panic(expected = "lies past the end of")]
fn a_position_past_the_end_is_a_defect() {
let (map, id) = map_with("one");
let _ = map.file(id).line_col(4);
}
#[test]
#[should_panic(expected = "is not a character boundary")]
fn a_position_inside_a_character_is_a_defect() {
let (map, id) = map_with("é");
let _ = map.file(id).line_col(1);
}
#[test]
#[should_panic(expected = "span names another file")]
fn reading_a_span_of_another_file_is_a_defect() {
let (map, id) = map_with("one");
let _ = map
.file(id)
.snippet(Span::from_bounds(FileId::from_usize(9), 0, 1));
}
#[test]
#[should_panic(expected = "does not cover whole characters")]
fn a_span_cutting_a_character_is_a_defect() {
let (map, id) = map_with("é");
let _ = map.file(id).snippet(Span::from_bounds(id, 0, 1));
}
}