//! Source files, spans, and position conversion; and the time spent per //! compiler phase ([`timings`]), which the front end, the back end and the //! build all record. This is the leaf every compiler crate shares. //! //! Offsets are UTF-8 byte offsets ([`TextSize`]) everywhere in the compiler. //! Line/column pairs are computed on demand: UTF-8 columns for terminal //! diagnostics, UTF-16 columns for the LSP (its default position encoding). pub mod timings; use std::sync::Arc; pub use text_size::{TextRange, TextSize}; /// Identifies a file in a [`SourceDb`]. #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] pub struct FileId(u32); /// A range of bytes in one file. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub struct Span { pub file: FileId, pub range: TextRange, } /// A zero-based line and column. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub struct LineCol { pub line: u32, pub col: u32, } pub struct SourceFile { path: String, text: Arc, /// Offset of the first byte of every line. line_starts: Vec, } impl SourceFile { pub fn new(path: impl Into, text: impl Into>) -> Self { let text: Arc = text.into(); let line_starts = std::iter::once(0) .chain(text.match_indices('\n').map(|(i, _)| i + 1)) .map(|i| TextSize::new(i as u32)) .collect(); SourceFile { path: path.into(), text, line_starts, } } pub fn path(&self) -> &str { &self.path } pub fn text(&self) -> &Arc { &self.text } fn line_of(&self, offset: TextSize) -> usize { self.line_starts.partition_point(|&start| start <= offset) - 1 } /// Line and column (in UTF-8 bytes) of `offset`. pub fn line_col(&self, offset: TextSize) -> LineCol { let line = self.line_of(offset); LineCol { line: line as u32, col: u32::from(offset - self.line_starts[line]), } } /// Line and column (in UTF-16 code units) of `offset`, as the LSP expects. pub fn line_col_utf16(&self, offset: TextSize) -> LineCol { let line = self.line_of(offset); let start = usize::from(self.line_starts[line]); let col = self.text[start..usize::from(offset)].encode_utf16().count(); LineCol { line: line as u32, col: col as u32, } } /// Byte offset of a UTF-16 line/column. Columns past the end of the line /// clamp to it, as LSP clients may send them. pub fn offset_utf16(&self, pos: LineCol) -> Option { let start = usize::from(*self.line_starts.get(pos.line as usize)?); let end = self .line_starts .get(pos.line as usize + 1) .map_or(self.text.len(), |&s| usize::from(s)); let mut units = 0; for (i, ch) in self.text[start..end].char_indices() { if units >= pos.col as usize || ch == '\n' { return Some(TextSize::new((start + i) as u32)); } units += ch.len_utf16(); } Some(TextSize::new(end as u32)) } } /// All source files known to one compilation or LSP session. #[derive(Default)] pub struct SourceDb { files: Vec, } impl SourceDb { pub fn add(&mut self, file: SourceFile) -> FileId { self.files.push(file); FileId(self.files.len() as u32 - 1) } pub fn get(&self, id: FileId) -> &SourceFile { &self.files[id.0 as usize] } /// Replace a file's text (an editor change), keeping its id and path. pub fn set_text(&mut self, id: FileId, text: impl Into>) { let file = &mut self.files[id.0 as usize]; *file = SourceFile::new(std::mem::take(&mut file.path), text); } pub fn iter(&self) -> impl Iterator { self.files .iter() .enumerate() .map(|(i, f)| (FileId(i as u32), f)) } } #[cfg(test)] mod tests { use super::*; #[test] fn line_col_counts_bytes_and_utf16_units() { let f = SourceFile::new("t.lse", "ab\né😀x\n"); let x = TextSize::new("ab\né😀".len() as u32); assert_eq!(f.line_col(x), LineCol { line: 1, col: 6 }); assert_eq!(f.line_col_utf16(x), LineCol { line: 1, col: 3 }); assert_eq!(f.line_col(TextSize::new(0)), LineCol { line: 0, col: 0 }); } #[test] fn utf16_round_trip_and_clamping() { let f = SourceFile::new("t.lse", "ab\né😀x\nlast"); for offset in [0, 1, 3, 5, 9, 10, 11, 15] { let offset = TextSize::new(offset); assert_eq!(f.offset_utf16(f.line_col_utf16(offset)), Some(offset)); } let past_end = LineCol { line: 0, col: 99 }; assert_eq!(f.offset_utf16(past_end), Some(TextSize::new(2))); assert_eq!(f.offset_utf16(LineCol { line: 7, col: 0 }), None); } }