solar_interface/source_map/
file.rs1use crate::{BytePos, CharPos, pos::RelativeBytePos};
2use std::{
3 fmt, io,
4 ops::{Range, RangeInclusive},
5 path::{Path, PathBuf},
6 sync::Arc,
7};
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11pub struct MultiByteChar {
12 pub pos: RelativeBytePos,
14 pub bytes: u8,
16}
17
18#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
23pub enum FileName {
24 Real(PathBuf),
26 Stdin,
28 Custom(String),
30}
31
32impl PartialEq<Path> for FileName {
33 fn eq(&self, other: &Path) -> bool {
34 match self {
35 Self::Real(p) => p == other,
36 _ => false,
37 }
38 }
39}
40
41impl PartialEq<&Path> for FileName {
42 fn eq(&self, other: &&Path) -> bool {
43 match self {
44 Self::Real(p) => p == *other,
45 _ => false,
46 }
47 }
48}
49
50impl PartialEq<PathBuf> for FileName {
51 fn eq(&self, other: &PathBuf) -> bool {
52 match self {
53 Self::Real(p) => p == other,
54 _ => false,
55 }
56 }
57}
58
59impl From<PathBuf> for FileName {
60 fn from(p: PathBuf) -> Self {
61 Self::Real(p)
62 }
63}
64
65impl From<&PathBuf> for FileName {
66 fn from(p: &PathBuf) -> Self {
67 Self::Real(p.clone())
68 }
69}
70
71impl From<&Path> for FileName {
72 fn from(p: &Path) -> Self {
73 Self::Real(p.to_path_buf())
74 }
75}
76
77impl From<String> for FileName {
78 fn from(s: String) -> Self {
79 Self::Custom(s)
80 }
81}
82
83impl From<&Self> for FileName {
84 fn from(s: &Self) -> Self {
85 s.clone()
86 }
87}
88
89impl FileName {
90 pub fn parse(sm: &crate::SourceMap, s: &str) -> Self {
94 sm.parse_file_name(s)
95 }
96
97 pub fn real(path: impl Into<PathBuf>) -> Self {
99 Self::Real(path.into())
100 }
101
102 pub fn custom(s: impl Into<String>) -> Self {
104 Self::Custom(s.into())
105 }
106
107 #[inline]
109 pub fn display(&self) -> FileNameDisplay<'_> {
110 let roots = crate::SessionGlobals::try_with(|g| g.map(|g| g.source_map.roots()))
111 .unwrap_or_else(|| arc_swap::Guard::from_inner(None));
112 FileNameDisplay { inner: self, roots }
113 }
114
115 #[inline]
117 pub fn as_real(&self) -> Option<&Path> {
118 match self {
119 Self::Real(path) => Some(path),
120 _ => None,
121 }
122 }
123}
124
125pub struct FileNameDisplay<'a> {
129 pub(crate) inner: &'a FileName,
130 pub(crate) roots: arc_swap::Guard<Option<Arc<super::SourceRoots>>>,
131}
132
133impl fmt::Display for FileNameDisplay<'_> {
134 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135 match self.inner {
136 FileName::Real(path) => {
137 let path = match &*self.roots {
138 Some(roots) => roots.source_unit_name(path),
139 None => path,
140 };
141 path.display().fmt(f)
142 }
143 FileName::Stdin => f.write_str("<stdin>"),
144 FileName::Custom(s) => write!(f, "<{s}>"),
145 }
146 }
147}
148
149#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
150pub(crate) struct SourceFileId(u64);
151
152impl SourceFileId {
153 pub(crate) fn new(filename: &FileName) -> Self {
154 use std::hash::{Hash, Hasher};
155 let mut hasher = solar_data_structures::map::FxHasher::with_seed(0);
156 filename.hash(&mut hasher);
157 Self(hasher.finish())
158 }
159}
160
161#[derive(Debug)]
163pub struct OffsetOverflowError(pub(crate) ());
164
165impl fmt::Display for OffsetOverflowError {
166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167 f.write_str("files larger than 4GiB are not supported")
168 }
169}
170
171impl std::error::Error for OffsetOverflowError {}
172
173impl From<OffsetOverflowError> for io::Error {
174 fn from(e: OffsetOverflowError) -> Self {
175 Self::new(io::ErrorKind::FileTooLarge, e)
176 }
177}
178
179#[derive(Clone, derive_more::Debug)]
181#[non_exhaustive]
182pub struct SourceFile {
183 pub name: FileName,
187 #[debug(skip)]
189 pub src: Arc<String>,
190 pub start_pos: BytePos,
192 pub source_len: RelativeBytePos,
194 #[debug(skip)]
196 lines: Vec<RelativeBytePos>,
197 #[debug(skip)]
199 pub multibyte_chars: Vec<MultiByteChar>,
200}
201
202impl PartialEq for SourceFile {
203 fn eq(&self, other: &Self) -> bool {
204 self.start_pos == other.start_pos
205 }
206}
207
208impl Eq for SourceFile {}
209
210impl std::hash::Hash for SourceFile {
211 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
212 self.start_pos.hash(state);
213 }
214}
215
216impl SourceFile {
217 pub(crate) fn new(
219 name: FileName,
220 id: SourceFileId,
221 mut src: Arc<String>,
222 ) -> Result<Self, OffsetOverflowError> {
223 debug_assert_eq!(id, SourceFileId::new(&name));
229 let source_len = src.len();
230 let source_len = u32::try_from(source_len).map_err(|_| OffsetOverflowError(()))?;
231
232 let (lines, multibyte_chars) = super::analyze::analyze_source_file(&src);
233
234 if let Some(src) = Arc::get_mut(&mut src) {
235 src.shrink_to_fit();
236 }
237
238 Ok(Self {
239 name,
240 src,
241 start_pos: BytePos::from_u32(0),
242 source_len: RelativeBytePos::from_u32(source_len),
243 lines,
244 multibyte_chars,
245 })
246 }
247
248 pub fn lines(&self) -> &[RelativeBytePos] {
249 &self.lines
250 }
251
252 pub fn count_lines(&self) -> usize {
253 self.lines().len()
254 }
255
256 #[inline]
257 pub fn absolute_position(&self, pos: RelativeBytePos) -> BytePos {
258 BytePos::from_u32(pos.to_u32() + self.start_pos.to_u32())
259 }
260
261 #[inline]
262 pub fn relative_position(&self, pos: BytePos) -> RelativeBytePos {
263 RelativeBytePos::from_u32(pos.to_u32() - self.start_pos.to_u32())
264 }
265
266 #[inline]
267 pub fn end_position(&self) -> BytePos {
268 self.absolute_position(self.source_len)
269 }
270
271 pub fn lookup_line(&self, pos: RelativeBytePos) -> Option<usize> {
276 self.lines().partition_point(|x| x <= &pos).checked_sub(1)
277 }
278
279 pub fn line_bounds(&self, line_index: usize) -> Range<BytePos> {
280 if self.is_empty() {
281 return self.start_pos..self.start_pos;
282 }
283
284 let lines = self.lines();
285 assert!(line_index < lines.len());
286 if line_index == (lines.len() - 1) {
287 self.absolute_position(lines[line_index])..self.end_position()
288 } else {
289 self.absolute_position(lines[line_index])..self.absolute_position(lines[line_index + 1])
290 }
291 }
292
293 pub fn line_position(&self, line_number: usize) -> Option<usize> {
296 self.lines().get(line_number).map(|x| x.to_usize())
297 }
298
299 pub(crate) fn bytepos_to_file_charpos(&self, bpos: RelativeBytePos) -> CharPos {
301 let mut total_extra_bytes = 0;
303
304 for mbc in self.multibyte_chars.iter() {
305 if mbc.pos < bpos {
306 total_extra_bytes += mbc.bytes as u32 - 1;
309 assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
312 } else {
313 break;
314 }
315 }
316
317 assert!(total_extra_bytes <= bpos.to_u32());
318 CharPos(bpos.to_usize() - total_extra_bytes as usize)
319 }
320
321 pub fn lookup_file_pos(&self, pos: RelativeBytePos) -> (usize, CharPos) {
323 let chpos = self.bytepos_to_file_charpos(pos);
324 match self.lookup_line(pos) {
325 Some(a) => {
326 let line = a + 1; let linebpos = self.lines()[a];
328 let linechpos = self.bytepos_to_file_charpos(linebpos);
329 let col = chpos - linechpos;
330 assert!(chpos >= linechpos);
331 (line, col)
332 }
333 None => (0, chpos),
334 }
335 }
336
337 pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) {
340 let pos = self.relative_position(pos);
341 let (line, col_or_chpos) = self.lookup_file_pos(pos);
342 if line > 0 {
343 let Some(code) = self.get_line(line - 1) else {
344 debug!("couldn't find line {line} in {:?}", self.name);
352 return (line, col_or_chpos, col_or_chpos.0);
353 };
354 let display_col = code.chars().take(col_or_chpos.0).map(char_width).sum();
355 (line, col_or_chpos, display_col)
356 } else {
357 (0, col_or_chpos, col_or_chpos.0)
359 }
360 }
361
362 pub fn get_line(&self, line_number: usize) -> Option<&str> {
365 fn get_until_newline(src: &str, begin: usize) -> &str {
366 let slice = &src[begin..];
370 match slice.find('\n') {
371 Some(e) => &slice[..e],
372 None => slice,
373 }
374 }
375
376 let start = self.lines().get(line_number)?.to_usize();
377 Some(get_until_newline(&self.src, start))
378 }
379
380 pub fn get_lines(&self, range: RangeInclusive<usize>) -> Option<&str> {
383 fn get_until_newline(src: &str, start: usize, end: usize) -> &str {
384 match src[end..].find('\n') {
385 Some(e) => &src[start..end + e + 1],
386 None => &src[start..],
387 }
388 }
389
390 let (start, end) = range.into_inner();
391 let lines = self.lines();
392 let start = lines.get(start)?.to_usize();
393 let end = lines.get(end)?.to_usize();
394 Some(get_until_newline(&self.src, start, end))
395 }
396
397 #[inline]
402 pub fn contains(&self, byte_pos: BytePos) -> bool {
403 byte_pos >= self.start_pos && byte_pos <= self.end_position()
404 }
405
406 #[inline]
407 pub fn is_empty(&self) -> bool {
408 self.source_len.to_u32() == 0
409 }
410
411 pub fn original_relative_byte_pos(&self, pos: BytePos) -> RelativeBytePos {
414 let pos = self.relative_position(pos);
415 RelativeBytePos::from_u32(pos.0)
416 }
417}
418
419pub fn char_width(ch: char) -> usize {
420 match ch {
421 '\t' => 4,
422 _ => unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1),
423 }
424}