tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

159 lignes · 5023 octetsBrut · Historique
1//! Source files, spans, and position conversion; and the time spent per
2//! compiler phase ([`timings`]), which the front end, the back end and the
3//! build all record. This is the leaf every compiler crate shares.
4//!
5//! Offsets are UTF-8 byte offsets ([`TextSize`]) everywhere in the compiler.
6//! Line/column pairs are computed on demand: UTF-8 columns for terminal
7//! diagnostics, UTF-16 columns for the LSP (its default position encoding).
8
9pub mod timings;
10
11use std::sync::Arc;
12
13pub use text_size::{TextRange, TextSize};
14
15/// Identifies a file in a [`SourceDb`].
16#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
17pub struct FileId(u32);
18
19/// A range of bytes in one file.
20#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
21pub struct Span {
22 pub file: FileId,
23 pub range: TextRange,
24}
25
26/// A zero-based line and column.
27#[derive(Copy, Clone, PartialEq, Eq, Debug)]
28pub struct LineCol {
29 pub line: u32,
30 pub col: u32,
31}
32
33pub struct SourceFile {
34 path: String,
35 text: Arc<str>,
36 /// Offset of the first byte of every line.
37 line_starts: Vec<TextSize>,
38}
39
40impl SourceFile {
41 pub fn new(path: impl Into<String>, text: impl Into<Arc<str>>) -> Self {
42 let text: Arc<str> = text.into();
43 let line_starts = std::iter::once(0)
44 .chain(text.match_indices('\n').map(|(i, _)| i + 1))
45 .map(|i| TextSize::new(i as u32))
46 .collect();
47 SourceFile {
48 path: path.into(),
49 text,
50 line_starts,
51 }
52 }
53
54 pub fn path(&self) -> &str {
55 &self.path
56 }
57
58 pub fn text(&self) -> &Arc<str> {
59 &self.text
60 }
61
62 fn line_of(&self, offset: TextSize) -> usize {
63 self.line_starts.partition_point(|&start| start <= offset) - 1
64 }
65
66 /// Line and column (in UTF-8 bytes) of `offset`.
67 pub fn line_col(&self, offset: TextSize) -> LineCol {
68 let line = self.line_of(offset);
69 LineCol {
70 line: line as u32,
71 col: u32::from(offset - self.line_starts[line]),
72 }
73 }
74
75 /// Line and column (in UTF-16 code units) of `offset`, as the LSP expects.
76 pub fn line_col_utf16(&self, offset: TextSize) -> LineCol {
77 let line = self.line_of(offset);
78 let start = usize::from(self.line_starts[line]);
79 let col = self.text[start..usize::from(offset)].encode_utf16().count();
80 LineCol {
81 line: line as u32,
82 col: col as u32,
83 }
84 }
85
86 /// Byte offset of a UTF-16 line/column. Columns past the end of the line
87 /// clamp to it, as LSP clients may send them.
88 pub fn offset_utf16(&self, pos: LineCol) -> Option<TextSize> {
89 let start = usize::from(*self.line_starts.get(pos.line as usize)?);
90 let end = self
91 .line_starts
92 .get(pos.line as usize + 1)
93 .map_or(self.text.len(), |&s| usize::from(s));
94 let mut units = 0;
95 for (i, ch) in self.text[start..end].char_indices() {
96 if units >= pos.col as usize || ch == '\n' {
97 return Some(TextSize::new((start + i) as u32));
98 }
99 units += ch.len_utf16();
100 }
101 Some(TextSize::new(end as u32))
102 }
103}
104
105/// All source files known to one compilation or LSP session.
106#[derive(Default)]
107pub struct SourceDb {
108 files: Vec<SourceFile>,
109}
110
111impl SourceDb {
112 pub fn add(&mut self, file: SourceFile) -> FileId {
113 self.files.push(file);
114 FileId(self.files.len() as u32 - 1)
115 }
116
117 pub fn get(&self, id: FileId) -> &SourceFile {
118 &self.files[id.0 as usize]
119 }
120
121 /// Replace a file's text (an editor change), keeping its id and path.
122 pub fn set_text(&mut self, id: FileId, text: impl Into<Arc<str>>) {
123 let file = &mut self.files[id.0 as usize];
124 *file = SourceFile::new(std::mem::take(&mut file.path), text);
125 }
126
127 pub fn iter(&self) -> impl Iterator<Item = (FileId, &SourceFile)> {
128 self.files
129 .iter()
130 .enumerate()
131 .map(|(i, f)| (FileId(i as u32), f))
132 }
133}
134
135#[cfg(test)]
136mod tests {
137 use super::*;
138
139 #[test]
140 fn line_col_counts_bytes_and_utf16_units() {
141 let f = SourceFile::new("t.lse", "ab\né😀x\n");
142 let x = TextSize::new("ab\né😀".len() as u32);
143 assert_eq!(f.line_col(x), LineCol { line: 1, col: 6 });
144 assert_eq!(f.line_col_utf16(x), LineCol { line: 1, col: 3 });
145 assert_eq!(f.line_col(TextSize::new(0)), LineCol { line: 0, col: 0 });
146 }
147
148 #[test]
149 fn utf16_round_trip_and_clamping() {
150 let f = SourceFile::new("t.lse", "ab\né😀x\nlast");
151 for offset in [0, 1, 3, 5, 9, 10, 11, 15] {
152 let offset = TextSize::new(offset);
153 assert_eq!(f.offset_utf16(f.line_col_utf16(offset)), Some(offset));
154 }
155 let past_end = LineCol { line: 0, col: 99 };
156 assert_eq!(f.offset_utf16(past_end), Some(TextSize::new(2)));
157 assert_eq!(f.offset_utf16(LineCol { line: 7, col: 0 }), None);
158 }
159}