1use std::fs::File;
13use std::io::{self, BorrowedBuf, Read};
14use std::{fs, path};
15
16use rustc_data_structures::sync::{IntoDynSyncSend, MappedReadGuard, ReadGuard, RwLock};
17use rustc_data_structures::unhash::UnhashMap;
18use rustc_macros::{Decodable, Encodable};
19use tracing::{debug, instrument, trace};
20
21use crate::*;
22
23#[cfg(test)]
24mod tests;
25
26pub fn original_sp(sp: Span, enclosing_sp: Span) -> Span {
30 let ctxt = sp.ctxt();
31 if ctxt.is_root() {
32 return sp;
33 }
34
35 let enclosing_ctxt = enclosing_sp.ctxt();
36 let expn_data1 = ctxt.outer_expn_data();
37 if !enclosing_ctxt.is_root()
38 && expn_data1.call_site == enclosing_ctxt.outer_expn_data().call_site
39 {
40 sp
41 } else {
42 original_sp(expn_data1.call_site, enclosing_sp)
43 }
44}
45
46mod monotonic {
47 use std::ops::{Deref, DerefMut};
48
49 pub struct MonotonicVec<T>(Vec<T>);
55 impl<T> MonotonicVec<T> {
56 pub(super) fn push(&mut self, val: T) {
57 self.0.push(val);
58 }
59 }
60
61 impl<T> Default for MonotonicVec<T> {
62 fn default() -> Self {
63 MonotonicVec(vec![])
64 }
65 }
66
67 impl<T> Deref for MonotonicVec<T> {
68 type Target = Vec<T>;
69 fn deref(&self) -> &Self::Target {
70 &self.0
71 }
72 }
73
74 impl<T> !DerefMut for MonotonicVec<T> {}
75}
76
77#[derive(Clone, Encodable, Decodable, Debug, Copy, PartialEq, Hash, HashStable_Generic)]
78pub struct Spanned<T> {
79 pub node: T,
80 pub span: Span,
81}
82
83pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
84 Spanned { node: t, span: sp }
85}
86
87pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
88 respan(DUMMY_SP, t)
89}
90
91pub trait FileLoader {
97 fn file_exists(&self, path: &Path) -> bool;
99
100 fn read_file(&self, path: &Path) -> io::Result<String>;
104
105 fn read_binary_file(&self, path: &Path) -> io::Result<Arc<[u8]>>;
108}
109
110pub struct RealFileLoader;
112
113impl FileLoader for RealFileLoader {
114 fn file_exists(&self, path: &Path) -> bool {
115 path.exists()
116 }
117
118 fn read_file(&self, path: &Path) -> io::Result<String> {
119 let mut file = File::open(path)?;
120 let size = file.metadata().map(|metadata| metadata.len()).ok().unwrap_or(0);
121
122 if size > SourceFile::MAX_FILE_SIZE.into() {
123 return Err(io::Error::other(format!(
124 "text files larger than {} bytes are unsupported",
125 SourceFile::MAX_FILE_SIZE
126 )));
127 }
128 let mut contents = String::new();
129 file.read_to_string(&mut contents)?;
130 Ok(contents)
131 }
132
133 fn read_binary_file(&self, path: &Path) -> io::Result<Arc<[u8]>> {
134 let mut file = fs::File::open(path)?;
135 let len = file.metadata()?.len();
136
137 let mut bytes = Arc::new_uninit_slice(len as usize);
138 let mut buf = BorrowedBuf::from(Arc::get_mut(&mut bytes).unwrap());
139 match file.read_buf_exact(buf.unfilled()) {
140 Ok(()) => {}
141 Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => {
142 drop(bytes);
143 return fs::read(path).map(Vec::into);
144 }
145 Err(e) => return Err(e),
146 }
147 let bytes = unsafe { bytes.assume_init() };
150
151 let mut probe = [0u8; 32];
161 let n = loop {
162 match file.read(&mut probe) {
163 Ok(0) => return Ok(bytes),
164 Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
165 Err(e) => return Err(e),
166 Ok(n) => break n,
167 }
168 };
169 let mut bytes: Vec<u8> = bytes.iter().copied().chain(probe[..n].iter().copied()).collect();
170 file.read_to_end(&mut bytes)?;
171 Ok(bytes.into())
172 }
173}
174
175#[derive(Default)]
180struct SourceMapFiles {
181 source_files: monotonic::MonotonicVec<Arc<SourceFile>>,
182 stable_id_to_source_file: UnhashMap<StableSourceFileId, Arc<SourceFile>>,
183}
184
185pub struct SourceMapInputs {
187 pub file_loader: Box<dyn FileLoader + Send + Sync>,
188 pub path_mapping: FilePathMapping,
189 pub hash_kind: SourceFileHashAlgorithm,
190 pub checksum_hash_kind: Option<SourceFileHashAlgorithm>,
191}
192
193pub struct SourceMap {
194 files: RwLock<SourceMapFiles>,
195 file_loader: IntoDynSyncSend<Box<dyn FileLoader + Sync + Send>>,
196
197 path_mapping: FilePathMapping,
200
201 hash_kind: SourceFileHashAlgorithm,
203
204 checksum_hash_kind: Option<SourceFileHashAlgorithm>,
209}
210
211impl SourceMap {
212 pub fn new(path_mapping: FilePathMapping) -> SourceMap {
213 Self::with_inputs(SourceMapInputs {
214 file_loader: Box::new(RealFileLoader),
215 path_mapping,
216 hash_kind: SourceFileHashAlgorithm::Md5,
217 checksum_hash_kind: None,
218 })
219 }
220
221 pub fn with_inputs(
222 SourceMapInputs { file_loader, path_mapping, hash_kind, checksum_hash_kind }: SourceMapInputs,
223 ) -> SourceMap {
224 SourceMap {
225 files: Default::default(),
226 file_loader: IntoDynSyncSend(file_loader),
227 path_mapping,
228 hash_kind,
229 checksum_hash_kind,
230 }
231 }
232
233 pub fn path_mapping(&self) -> &FilePathMapping {
234 &self.path_mapping
235 }
236
237 pub fn file_exists(&self, path: &Path) -> bool {
238 self.file_loader.file_exists(path)
239 }
240
241 pub fn load_file(&self, path: &Path) -> io::Result<Arc<SourceFile>> {
242 let src = self.file_loader.read_file(path)?;
243 let filename = path.to_owned().into();
244 Ok(self.new_source_file(filename, src))
245 }
246
247 pub fn load_binary_file(&self, path: &Path) -> io::Result<(Arc<[u8]>, Span)> {
252 let bytes = self.file_loader.read_binary_file(path)?;
253
254 let text = std::str::from_utf8(&bytes).unwrap_or("").to_string();
260 let file = self.new_source_file(path.to_owned().into(), text);
261 Ok((
262 bytes,
263 Span::new(
264 file.start_pos,
265 BytePos(file.start_pos.0 + file.source_len.0),
266 SyntaxContext::root(),
267 None,
268 ),
269 ))
270 }
271
272 pub fn files(&self) -> MappedReadGuard<'_, monotonic::MonotonicVec<Arc<SourceFile>>> {
275 ReadGuard::map(self.files.borrow(), |files| &files.source_files)
276 }
277
278 pub fn source_file_by_stable_id(
279 &self,
280 stable_id: StableSourceFileId,
281 ) -> Option<Arc<SourceFile>> {
282 self.files.borrow().stable_id_to_source_file.get(&stable_id).cloned()
283 }
284
285 fn register_source_file(
286 &self,
287 file_id: StableSourceFileId,
288 mut file: SourceFile,
289 ) -> Result<Arc<SourceFile>, OffsetOverflowError> {
290 let mut files = self.files.borrow_mut();
291
292 file.start_pos = BytePos(if let Some(last_file) = files.source_files.last() {
293 last_file.end_position().0.checked_add(1).ok_or(OffsetOverflowError)?
296 } else {
297 0
298 });
299
300 let file = Arc::new(file);
301 files.source_files.push(Arc::clone(&file));
302 files.stable_id_to_source_file.insert(file_id, Arc::clone(&file));
303
304 Ok(file)
305 }
306
307 pub fn new_source_file(&self, filename: FileName, src: String) -> Arc<SourceFile> {
311 self.try_new_source_file(filename, src).unwrap_or_else(|OffsetOverflowError| {
312 eprintln!(
313 "fatal error: rustc does not support text files larger than {} bytes",
314 SourceFile::MAX_FILE_SIZE
315 );
316 crate::fatal_error::FatalError.raise()
317 })
318 }
319
320 fn try_new_source_file(
321 &self,
322 filename: FileName,
323 src: String,
324 ) -> Result<Arc<SourceFile>, OffsetOverflowError> {
325 let (filename, _) = self.path_mapping.map_filename_prefix(&filename);
329
330 let stable_id = StableSourceFileId::from_filename_in_current_crate(&filename);
331 match self.source_file_by_stable_id(stable_id) {
332 Some(lrc_sf) => Ok(lrc_sf),
333 None => {
334 let source_file =
335 SourceFile::new(filename, src, self.hash_kind, self.checksum_hash_kind)?;
336
337 debug_assert_eq!(source_file.stable_id, stable_id);
340
341 self.register_source_file(stable_id, source_file)
342 }
343 }
344 }
345
346 pub fn new_imported_source_file(
351 &self,
352 filename: FileName,
353 src_hash: SourceFileHash,
354 checksum_hash: Option<SourceFileHash>,
355 stable_id: StableSourceFileId,
356 source_len: u32,
357 cnum: CrateNum,
358 file_local_lines: FreezeLock<SourceFileLines>,
359 multibyte_chars: Vec<MultiByteChar>,
360 normalized_pos: Vec<NormalizedPos>,
361 metadata_index: u32,
362 ) -> Arc<SourceFile> {
363 let source_len = RelativeBytePos::from_u32(source_len);
364
365 let source_file = SourceFile {
366 name: filename,
367 src: None,
368 src_hash,
369 checksum_hash,
370 external_src: FreezeLock::new(ExternalSource::Foreign {
371 kind: ExternalSourceKind::AbsentOk,
372 metadata_index,
373 }),
374 start_pos: BytePos(0),
375 source_len,
376 lines: file_local_lines,
377 multibyte_chars,
378 normalized_pos,
379 stable_id,
380 cnum,
381 };
382
383 self.register_source_file(stable_id, source_file)
384 .expect("not enough address space for imported source file")
385 }
386
387 pub fn doctest_offset_line(&self, file: &FileName, orig: usize) -> usize {
389 match file {
390 FileName::DocTest(_, offset) => {
391 if *offset < 0 {
392 orig - (-(*offset)) as usize
393 } else {
394 orig + *offset as usize
395 }
396 }
397 _ => orig,
398 }
399 }
400
401 pub fn lookup_source_file(&self, pos: BytePos) -> Arc<SourceFile> {
403 let idx = self.lookup_source_file_idx(pos);
404 Arc::clone(&(*self.files.borrow().source_files)[idx])
405 }
406
407 pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
409 let sf = self.lookup_source_file(pos);
410 let (line, col, col_display) = sf.lookup_file_pos_with_col_display(pos);
411 Loc { file: sf, line, col, col_display }
412 }
413
414 pub fn lookup_line(&self, pos: BytePos) -> Result<SourceFileAndLine, Arc<SourceFile>> {
416 let f = self.lookup_source_file(pos);
417
418 let pos = f.relative_position(pos);
419 match f.lookup_line(pos) {
420 Some(line) => Ok(SourceFileAndLine { sf: f, line }),
421 None => Err(f),
422 }
423 }
424
425 pub fn span_to_string(
426 &self,
427 sp: Span,
428 filename_display_pref: FileNameDisplayPreference,
429 ) -> String {
430 let (source_file, lo_line, lo_col, hi_line, hi_col) = self.span_to_location_info(sp);
431
432 let file_name = match source_file {
433 Some(sf) => sf.name.display(filename_display_pref).to_string(),
434 None => return "no-location".to_string(),
435 };
436
437 format!(
438 "{file_name}:{lo_line}:{lo_col}{}",
439 if let FileNameDisplayPreference::Short = filename_display_pref {
440 String::new()
441 } else {
442 format!(": {hi_line}:{hi_col}")
443 }
444 )
445 }
446
447 pub fn span_to_location_info(
448 &self,
449 sp: Span,
450 ) -> (Option<Arc<SourceFile>>, usize, usize, usize, usize) {
451 if self.files.borrow().source_files.is_empty() || sp.is_dummy() {
452 return (None, 0, 0, 0, 0);
453 }
454
455 let lo = self.lookup_char_pos(sp.lo());
456 let hi = self.lookup_char_pos(sp.hi());
457 (Some(lo.file), lo.line, lo.col.to_usize() + 1, hi.line, hi.col.to_usize() + 1)
458 }
459
460 pub fn span_to_embeddable_string(&self, sp: Span) -> String {
462 self.span_to_string(sp, FileNameDisplayPreference::Remapped)
463 }
464
465 pub fn span_to_diagnostic_string(&self, sp: Span) -> String {
469 self.span_to_string(sp, self.path_mapping.filename_display_for_diagnostics)
470 }
471
472 pub fn span_to_filename(&self, sp: Span) -> FileName {
473 self.lookup_char_pos(sp.lo()).file.name.clone()
474 }
475
476 pub fn filename_for_diagnostics<'a>(&self, filename: &'a FileName) -> FileNameDisplay<'a> {
477 filename.display(self.path_mapping.filename_display_for_diagnostics)
478 }
479
480 pub fn is_multiline(&self, sp: Span) -> bool {
481 let lo = self.lookup_source_file_idx(sp.lo());
482 let hi = self.lookup_source_file_idx(sp.hi());
483 if lo != hi {
484 return true;
485 }
486 let f = Arc::clone(&(*self.files.borrow().source_files)[lo]);
487 let lo = f.relative_position(sp.lo());
488 let hi = f.relative_position(sp.hi());
489 f.lookup_line(lo) != f.lookup_line(hi)
490 }
491
492 #[instrument(skip(self), level = "trace")]
493 pub fn is_valid_span(&self, sp: Span) -> Result<(Loc, Loc), SpanLinesError> {
494 let lo = self.lookup_char_pos(sp.lo());
495 trace!(?lo);
496 let hi = self.lookup_char_pos(sp.hi());
497 trace!(?hi);
498 if lo.file.start_pos != hi.file.start_pos {
499 return Err(SpanLinesError::DistinctSources(Box::new(DistinctSources {
500 begin: (lo.file.name.clone(), lo.file.start_pos),
501 end: (hi.file.name.clone(), hi.file.start_pos),
502 })));
503 }
504 Ok((lo, hi))
505 }
506
507 pub fn is_line_before_span_empty(&self, sp: Span) -> bool {
508 match self.span_to_prev_source(sp) {
509 Ok(s) => s.rsplit_once('\n').unwrap_or(("", &s)).1.trim_start().is_empty(),
510 Err(_) => false,
511 }
512 }
513
514 pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
515 debug!("span_to_lines(sp={:?})", sp);
516 let (lo, hi) = self.is_valid_span(sp)?;
517 assert!(hi.line >= lo.line);
518
519 if sp.is_dummy() {
520 return Ok(FileLines { file: lo.file, lines: Vec::new() });
521 }
522
523 let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
524
525 let mut start_col = lo.col;
528
529 let hi_line = hi.line.saturating_sub(1);
537 for line_index in lo.line.saturating_sub(1)..hi_line {
538 let line_len = lo.file.get_line(line_index).map_or(0, |s| s.chars().count());
539 lines.push(LineInfo { line_index, start_col, end_col: CharPos::from_usize(line_len) });
540 start_col = CharPos::from_usize(0);
541 }
542
543 lines.push(LineInfo { line_index: hi_line, start_col, end_col: hi.col });
545
546 Ok(FileLines { file: lo.file, lines })
547 }
548
549 pub fn span_to_source<F, T>(&self, sp: Span, extract_source: F) -> Result<T, SpanSnippetError>
553 where
554 F: Fn(&str, usize, usize) -> Result<T, SpanSnippetError>,
555 {
556 let local_begin = self.lookup_byte_offset(sp.lo());
557 let local_end = self.lookup_byte_offset(sp.hi());
558
559 if local_begin.sf.start_pos != local_end.sf.start_pos {
560 Err(SpanSnippetError::DistinctSources(Box::new(DistinctSources {
561 begin: (local_begin.sf.name.clone(), local_begin.sf.start_pos),
562 end: (local_end.sf.name.clone(), local_end.sf.start_pos),
563 })))
564 } else {
565 self.ensure_source_file_source_present(&local_begin.sf);
566
567 let start_index = local_begin.pos.to_usize();
568 let end_index = local_end.pos.to_usize();
569 let source_len = local_begin.sf.source_len.to_usize();
570
571 if start_index > end_index || end_index > source_len {
572 return Err(SpanSnippetError::MalformedForSourcemap(MalformedSourceMapPositions {
573 name: local_begin.sf.name.clone(),
574 source_len,
575 begin_pos: local_begin.pos,
576 end_pos: local_end.pos,
577 }));
578 }
579
580 if let Some(ref src) = local_begin.sf.src {
581 extract_source(src, start_index, end_index)
582 } else if let Some(src) = local_begin.sf.external_src.read().get_source() {
583 extract_source(src, start_index, end_index)
584 } else {
585 Err(SpanSnippetError::SourceNotAvailable { filename: local_begin.sf.name.clone() })
586 }
587 }
588 }
589
590 pub fn is_span_accessible(&self, sp: Span) -> bool {
591 self.span_to_source(sp, |src, start_index, end_index| {
592 Ok(src.get(start_index..end_index).is_some())
593 })
594 .is_ok_and(|is_accessible| is_accessible)
595 }
596
597 pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
599 self.span_to_source(sp, |src, start_index, end_index| {
600 src.get(start_index..end_index)
601 .map(|s| s.to_string())
602 .ok_or(SpanSnippetError::IllFormedSpan(sp))
603 })
604 }
605
606 pub fn span_to_margin(&self, sp: Span) -> Option<usize> {
607 Some(self.indentation_before(sp)?.len())
608 }
609
610 pub fn indentation_before(&self, sp: Span) -> Option<String> {
611 self.span_to_source(sp, |src, start_index, _| {
612 let before = &src[..start_index];
613 let last_line = before.rsplit_once('\n').map_or(before, |(_, last)| last);
614 Ok(last_line
615 .split_once(|c: char| !c.is_whitespace())
616 .map_or(last_line, |(indent, _)| indent)
617 .to_string())
618 })
619 .ok()
620 }
621
622 pub fn span_to_prev_source(&self, sp: Span) -> Result<String, SpanSnippetError> {
624 self.span_to_source(sp, |src, start_index, _| {
625 src.get(..start_index).map(|s| s.to_string()).ok_or(SpanSnippetError::IllFormedSpan(sp))
626 })
627 }
628
629 pub fn span_extend_to_prev_char(&self, sp: Span, c: char, accept_newlines: bool) -> Span {
632 if let Ok(prev_source) = self.span_to_prev_source(sp) {
633 let prev_source = prev_source.rsplit(c).next().unwrap_or("");
634 if !prev_source.is_empty() && (accept_newlines || !prev_source.contains('\n')) {
635 return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32));
636 }
637 }
638
639 sp
640 }
641
642 pub fn span_extend_to_prev_char_before(
645 &self,
646 sp: Span,
647 c: char,
648 accept_newlines: bool,
649 ) -> Span {
650 if let Ok(prev_source) = self.span_to_prev_source(sp) {
651 let prev_source = prev_source.rsplit(c).next().unwrap_or("");
652 if accept_newlines || !prev_source.contains('\n') {
653 return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32 - 1_u32));
654 }
655 }
656
657 sp
658 }
659
660 pub fn span_extend_to_prev_str(
664 &self,
665 sp: Span,
666 pat: &str,
667 accept_newlines: bool,
668 include_whitespace: bool,
669 ) -> Option<Span> {
670 let prev_source = self.span_to_prev_source(sp).ok()?;
675 for ws in &[" ", "\t", "\n"] {
676 let pat = pat.to_owned() + ws;
677 if let Some(pat_pos) = prev_source.rfind(&pat) {
678 let just_after_pat_pos = pat_pos + pat.len() - 1;
679 let just_after_pat_plus_ws = if include_whitespace {
680 just_after_pat_pos
681 + prev_source[just_after_pat_pos..]
682 .find(|c: char| !c.is_whitespace())
683 .unwrap_or(0)
684 } else {
685 just_after_pat_pos
686 };
687 let len = prev_source.len() - just_after_pat_plus_ws;
688 let prev_source = &prev_source[just_after_pat_plus_ws..];
689 if accept_newlines || !prev_source.trim_start().contains('\n') {
690 return Some(sp.with_lo(BytePos(sp.lo().0 - len as u32)));
691 }
692 }
693 }
694
695 None
696 }
697
698 pub fn span_to_next_source(&self, sp: Span) -> Result<String, SpanSnippetError> {
700 self.span_to_source(sp, |src, _, end_index| {
701 src.get(end_index..).map(|s| s.to_string()).ok_or(SpanSnippetError::IllFormedSpan(sp))
702 })
703 }
704
705 pub fn span_extend_while(
707 &self,
708 span: Span,
709 f: impl Fn(char) -> bool,
710 ) -> Result<Span, SpanSnippetError> {
711 self.span_to_source(span, |s, _start, end| {
712 let n = s[end..].char_indices().find(|&(_, c)| !f(c)).map_or(s.len() - end, |(i, _)| i);
713 Ok(span.with_hi(span.hi() + BytePos(n as u32)))
714 })
715 }
716
717 pub fn span_extend_while_whitespace(&self, span: Span) -> Span {
720 self.span_extend_while(span, char::is_whitespace).unwrap_or(span)
721 }
722
723 pub fn span_extend_prev_while(
725 &self,
726 span: Span,
727 f: impl Fn(char) -> bool,
728 ) -> Result<Span, SpanSnippetError> {
729 self.span_to_source(span, |s, start, _end| {
730 let n = s[..start]
731 .char_indices()
732 .rfind(|&(_, c)| !f(c))
733 .map_or(start, |(i, _)| start - i - 1);
734 Ok(span.with_lo(span.lo() - BytePos(n as u32)))
735 })
736 }
737
738 pub fn span_extend_to_next_char(&self, sp: Span, c: char, accept_newlines: bool) -> Span {
740 if let Ok(next_source) = self.span_to_next_source(sp) {
741 let next_source = next_source.split(c).next().unwrap_or("");
742 if !next_source.is_empty() && (accept_newlines || !next_source.contains('\n')) {
743 return sp.with_hi(BytePos(sp.hi().0 + next_source.len() as u32));
744 }
745 }
746
747 sp
748 }
749
750 pub fn span_extend_to_line(&self, sp: Span) -> Span {
752 self.span_extend_to_prev_char(self.span_extend_to_next_char(sp, '\n', true), '\n', true)
753 }
754
755 pub fn span_until_char(&self, sp: Span, c: char) -> Span {
758 match self.span_to_snippet(sp) {
759 Ok(snippet) => {
760 let snippet = snippet.split(c).next().unwrap_or("").trim_end();
761 if !snippet.is_empty() && !snippet.contains('\n') {
762 sp.with_hi(BytePos(sp.lo().0 + snippet.len() as u32))
763 } else {
764 sp
765 }
766 }
767 _ => sp,
768 }
769 }
770
771 pub fn span_wrapped_by_angle_or_parentheses(&self, span: Span) -> bool {
776 self.span_to_source(span, |src, start_index, end_index| {
777 if src.get(start_index..end_index).is_none() {
778 return Ok(false);
779 }
780 let end_src = &src[end_index..];
782 let mut i = 0;
783 let mut found_right_parentheses = false;
784 let mut found_right_angle = false;
785 while let Some(cc) = end_src.chars().nth(i) {
786 if cc == ' ' {
787 i = i + 1;
788 } else if cc == '>' {
789 found_right_angle = true;
791 break;
792 } else if cc == ')' {
793 found_right_parentheses = true;
794 break;
795 } else {
796 return Ok(false);
798 }
799 }
800 i = start_index;
802 let start_src = &src[0..start_index];
803 while let Some(cc) = start_src.chars().nth(i) {
804 if cc == ' ' {
805 if i == 0 {
806 return Ok(false);
807 }
808 i = i - 1;
809 } else if cc == '<' {
810 if !found_right_angle {
812 return Ok(false);
814 }
815 break;
816 } else if cc == '(' {
817 if !found_right_parentheses {
818 return Ok(false);
820 }
821 break;
822 } else {
823 return Ok(false);
825 }
826 }
827 Ok(true)
828 })
829 .is_ok_and(|is_accessible| is_accessible)
830 }
831
832 pub fn span_through_char(&self, sp: Span, c: char) -> Span {
835 if let Ok(snippet) = self.span_to_snippet(sp)
836 && let Some(offset) = snippet.find(c)
837 {
838 return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32));
839 }
840 sp
841 }
842
843 pub fn span_until_non_whitespace(&self, sp: Span) -> Span {
848 let mut whitespace_found = false;
849
850 self.span_take_while(sp, |c| {
851 if !whitespace_found && c.is_whitespace() {
852 whitespace_found = true;
853 }
854
855 !whitespace_found || c.is_whitespace()
856 })
857 }
858
859 pub fn span_until_whitespace(&self, sp: Span) -> Span {
864 self.span_take_while(sp, |c| !c.is_whitespace())
865 }
866
867 pub fn span_take_while<P>(&self, sp: Span, predicate: P) -> Span
869 where
870 P: for<'r> FnMut(&'r char) -> bool,
871 {
872 if let Ok(snippet) = self.span_to_snippet(sp) {
873 let offset = snippet.chars().take_while(predicate).map(|c| c.len_utf8()).sum::<usize>();
874
875 sp.with_hi(BytePos(sp.lo().0 + (offset as u32)))
876 } else {
877 sp
878 }
879 }
880
881 pub fn guess_head_span(&self, sp: Span) -> Span {
887 self.span_until_char(sp, '{')
890 }
891
892 pub fn start_point(&self, sp: Span) -> Span {
894 let width = {
895 let sp = sp.data();
896 let local_begin = self.lookup_byte_offset(sp.lo);
897 let start_index = local_begin.pos.to_usize();
898 let src = local_begin.sf.external_src.read();
899
900 let snippet = if let Some(ref src) = local_begin.sf.src {
901 Some(&src[start_index..])
902 } else {
903 src.get_source().map(|src| &src[start_index..])
904 };
905
906 match snippet {
907 None => 1,
908 Some(snippet) => match snippet.chars().next() {
909 None => 1,
910 Some(c) => c.len_utf8(),
911 },
912 }
913 };
914
915 sp.with_hi(BytePos(sp.lo().0 + width as u32))
916 }
917
918 pub fn end_point(&self, sp: Span) -> Span {
920 let sp = sp.data();
921 let pos = sp.hi.0;
922
923 let width = self.find_width_of_character_at_span(sp, false);
924 let corrected_end_position = pos.checked_sub(width).unwrap_or(pos);
925
926 let end_point = BytePos(cmp::max(corrected_end_position, sp.lo.0));
927 sp.with_lo(end_point)
928 }
929
930 pub fn next_point(&self, sp: Span) -> Span {
937 if sp.is_dummy() {
938 return sp;
939 }
940
941 let sp = sp.data();
942 let start_of_next_point = sp.hi.0;
943 let width = self.find_width_of_character_at_span(sp, true);
944 let end_of_next_point =
948 start_of_next_point.checked_add(width).unwrap_or(start_of_next_point);
949
950 let end_of_next_point = BytePos(cmp::max(start_of_next_point + 1, end_of_next_point));
951 Span::new(BytePos(start_of_next_point), end_of_next_point, sp.ctxt, None)
952 }
953
954 pub fn span_look_ahead(&self, span: Span, expect: &str, limit: Option<usize>) -> Option<Span> {
956 let mut sp = span;
957 for _ in 0..limit.unwrap_or(100_usize) {
958 sp = self.next_point(sp);
959 if let Ok(ref snippet) = self.span_to_snippet(sp) {
960 if snippet == expect {
961 return Some(sp);
962 }
963 if snippet.chars().any(|c| !c.is_whitespace()) {
964 break;
965 }
966 }
967 }
968 None
969 }
970
971 #[instrument(skip(self, sp))]
974 fn find_width_of_character_at_span(&self, sp: SpanData, forwards: bool) -> u32 {
975 if sp.lo == sp.hi && !forwards {
976 debug!("early return empty span");
977 return 1;
978 }
979
980 let local_begin = self.lookup_byte_offset(sp.lo);
981 let local_end = self.lookup_byte_offset(sp.hi);
982 debug!("local_begin=`{:?}`, local_end=`{:?}`", local_begin, local_end);
983
984 if local_begin.sf.start_pos != local_end.sf.start_pos {
985 debug!("begin and end are in different files");
986 return 1;
987 }
988
989 let start_index = local_begin.pos.to_usize();
990 let end_index = local_end.pos.to_usize();
991 debug!("start_index=`{:?}`, end_index=`{:?}`", start_index, end_index);
992
993 if (!forwards && end_index == usize::MIN) || (forwards && start_index == usize::MAX) {
996 debug!("start or end of span, cannot be multibyte");
997 return 1;
998 }
999
1000 let source_len = local_begin.sf.source_len.to_usize();
1001 debug!("source_len=`{:?}`", source_len);
1002 if start_index > end_index || end_index > source_len - 1 {
1004 debug!("source indexes are malformed");
1005 return 1;
1006 }
1007
1008 let src = local_begin.sf.external_src.read();
1009
1010 let snippet = if let Some(src) = &local_begin.sf.src {
1011 src
1012 } else if let Some(src) = src.get_source() {
1013 src
1014 } else {
1015 return 1;
1016 };
1017
1018 if forwards {
1019 (snippet.ceil_char_boundary(end_index + 1) - end_index) as u32
1020 } else {
1021 (end_index - snippet.floor_char_boundary(end_index - 1)) as u32
1022 }
1023 }
1024
1025 pub fn get_source_file(&self, filename: &FileName) -> Option<Arc<SourceFile>> {
1026 let filename = self.path_mapping().map_filename_prefix(filename).0;
1028 for sf in self.files.borrow().source_files.iter() {
1029 if filename == sf.name {
1030 return Some(Arc::clone(&sf));
1031 }
1032 }
1033 None
1034 }
1035
1036 pub fn lookup_byte_offset(&self, bpos: BytePos) -> SourceFileAndBytePos {
1038 let idx = self.lookup_source_file_idx(bpos);
1039 let sf = Arc::clone(&(*self.files.borrow().source_files)[idx]);
1040 let offset = bpos - sf.start_pos;
1041 SourceFileAndBytePos { sf, pos: offset }
1042 }
1043
1044 pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize {
1048 self.files.borrow().source_files.partition_point(|x| x.start_pos <= pos) - 1
1049 }
1050
1051 pub fn count_lines(&self) -> usize {
1052 self.files().iter().fold(0, |a, f| a + f.count_lines())
1053 }
1054
1055 pub fn ensure_source_file_source_present(&self, source_file: &SourceFile) -> bool {
1056 source_file.add_external_src(|| {
1057 let FileName::Real(ref name) = source_file.name else {
1058 return None;
1059 };
1060
1061 let local_path: Cow<'_, Path> = match name {
1062 RealFileName::LocalPath(local_path) => local_path.into(),
1063 RealFileName::Remapped { local_path: Some(local_path), .. } => local_path.into(),
1064 RealFileName::Remapped { local_path: None, virtual_name } => {
1065 self.path_mapping.reverse_map_prefix_heuristically(virtual_name)?.into()
1071 }
1072 };
1073
1074 self.file_loader.read_file(&local_path).ok()
1075 })
1076 }
1077
1078 pub fn is_imported(&self, sp: Span) -> bool {
1079 let source_file_index = self.lookup_source_file_idx(sp.lo());
1080 let source_file = &self.files()[source_file_index];
1081 source_file.is_imported()
1082 }
1083
1084 pub fn stmt_span(&self, stmt_span: Span, block_span: Span) -> Span {
1088 if !stmt_span.from_expansion() {
1089 return stmt_span;
1090 }
1091 let mac_call = original_sp(stmt_span, block_span);
1092 self.mac_call_stmt_semi_span(mac_call).map_or(mac_call, |s| mac_call.with_hi(s.hi()))
1093 }
1094
1095 pub fn mac_call_stmt_semi_span(&self, mac_call: Span) -> Option<Span> {
1103 let span = self.span_extend_while_whitespace(mac_call);
1104 let span = self.next_point(span);
1105 if self.span_to_snippet(span).as_deref() == Ok(";") { Some(span) } else { None }
1106 }
1107}
1108
1109pub fn get_source_map() -> Option<Arc<SourceMap>> {
1110 with_session_globals(|session_globals| session_globals.source_map.clone())
1111}
1112
1113#[derive(Clone)]
1114pub struct FilePathMapping {
1115 mapping: Vec<(PathBuf, PathBuf)>,
1116 filename_display_for_diagnostics: FileNameDisplayPreference,
1117 filename_embeddable_preference: FileNameEmbeddablePreference,
1118}
1119
1120impl FilePathMapping {
1121 pub fn empty() -> FilePathMapping {
1122 FilePathMapping::new(
1123 Vec::new(),
1124 FileNameDisplayPreference::Local,
1125 FileNameEmbeddablePreference::RemappedOnly,
1126 )
1127 }
1128
1129 pub fn new(
1130 mapping: Vec<(PathBuf, PathBuf)>,
1131 filename_display_for_diagnostics: FileNameDisplayPreference,
1132 filename_embeddable_preference: FileNameEmbeddablePreference,
1133 ) -> FilePathMapping {
1134 FilePathMapping {
1135 mapping,
1136 filename_display_for_diagnostics,
1137 filename_embeddable_preference,
1138 }
1139 }
1140
1141 pub fn map_prefix<'a>(&'a self, path: impl Into<Cow<'a, Path>>) -> (Cow<'a, Path>, bool) {
1145 let path = path.into();
1146 if path.as_os_str().is_empty() {
1147 return (path, false);
1150 }
1151
1152 return remap_path_prefix(&self.mapping, path);
1153
1154 #[instrument(level = "debug", skip(mapping), ret)]
1155 fn remap_path_prefix<'a>(
1156 mapping: &'a [(PathBuf, PathBuf)],
1157 path: Cow<'a, Path>,
1158 ) -> (Cow<'a, Path>, bool) {
1159 for (from, to) in mapping.iter().rev() {
1163 debug!("Trying to apply {from:?} => {to:?}");
1164
1165 if let Ok(rest) = path.strip_prefix(from) {
1166 let remapped = if rest.as_os_str().is_empty() {
1167 to.into()
1174 } else {
1175 to.join(rest).into()
1176 };
1177 debug!("Match - remapped");
1178
1179 return (remapped, true);
1180 } else {
1181 debug!("No match - prefix {from:?} does not match");
1182 }
1183 }
1184
1185 debug!("not remapped");
1186 (path, false)
1187 }
1188 }
1189
1190 fn map_filename_prefix(&self, file: &FileName) -> (FileName, bool) {
1191 match file {
1192 FileName::Real(realfile) if let RealFileName::LocalPath(local_path) = realfile => {
1193 let (mapped_path, mapped) = self.map_prefix(local_path);
1194 let realfile = if mapped {
1195 RealFileName::Remapped {
1196 local_path: Some(local_path.clone()),
1197 virtual_name: mapped_path.into_owned(),
1198 }
1199 } else {
1200 realfile.clone()
1201 };
1202 (FileName::Real(realfile), mapped)
1203 }
1204 FileName::Real(_) => unreachable!("attempted to remap an already remapped filename"),
1205 other => (other.clone(), false),
1206 }
1207 }
1208
1209 pub fn to_real_filename<'a>(&self, local_path: impl Into<Cow<'a, Path>>) -> RealFileName {
1213 let local_path = local_path.into();
1214 if let (remapped_path, true) = self.map_prefix(&*local_path) {
1215 RealFileName::Remapped {
1216 virtual_name: remapped_path.into_owned(),
1217 local_path: Some(local_path.into_owned()),
1218 }
1219 } else {
1220 RealFileName::LocalPath(local_path.into_owned())
1221 }
1222 }
1223
1224 pub fn to_embeddable_absolute_path(
1230 &self,
1231 file_path: RealFileName,
1232 working_directory: &RealFileName,
1233 ) -> RealFileName {
1234 match file_path {
1235 RealFileName::Remapped { local_path, virtual_name } => {
1238 RealFileName::Remapped {
1239 local_path: match self.filename_embeddable_preference {
1240 FileNameEmbeddablePreference::RemappedOnly => None,
1241 FileNameEmbeddablePreference::LocalAndRemapped => local_path,
1242 },
1243 virtual_name,
1247 }
1248 }
1249
1250 RealFileName::LocalPath(unmapped_file_path) => {
1251 let (new_path, was_remapped) = self.map_prefix(&unmapped_file_path);
1253 if was_remapped {
1254 return RealFileName::Remapped {
1256 virtual_name: new_path.into_owned(),
1257 local_path: match self.filename_embeddable_preference {
1259 FileNameEmbeddablePreference::RemappedOnly => None,
1260 FileNameEmbeddablePreference::LocalAndRemapped => {
1261 Some(unmapped_file_path)
1262 }
1263 },
1264 };
1265 }
1266
1267 if new_path.is_absolute() {
1268 return RealFileName::LocalPath(new_path.into_owned());
1272 }
1273
1274 debug_assert!(new_path.is_relative());
1275 let unmapped_file_path_rel = new_path;
1276
1277 match working_directory {
1278 RealFileName::LocalPath(unmapped_working_dir_abs) => {
1279 let unmapped_file_path_abs =
1280 unmapped_working_dir_abs.join(unmapped_file_path_rel);
1281
1282 let (file_path_abs, was_remapped) =
1286 self.map_prefix(&unmapped_file_path_abs);
1287 if was_remapped {
1288 RealFileName::Remapped {
1289 virtual_name: file_path_abs.into_owned(),
1290 local_path: match self.filename_embeddable_preference {
1291 FileNameEmbeddablePreference::RemappedOnly => None,
1292 FileNameEmbeddablePreference::LocalAndRemapped => {
1293 Some(unmapped_file_path_abs)
1294 }
1295 },
1296 }
1297 } else {
1298 RealFileName::LocalPath(file_path_abs.into_owned())
1301 }
1302 }
1303 RealFileName::Remapped {
1304 local_path,
1305 virtual_name: remapped_working_dir_abs,
1306 } => {
1307 RealFileName::Remapped {
1310 virtual_name: Path::new(remapped_working_dir_abs)
1311 .join(&unmapped_file_path_rel),
1312 local_path: match self.filename_embeddable_preference {
1313 FileNameEmbeddablePreference::RemappedOnly => None,
1314 FileNameEmbeddablePreference::LocalAndRemapped => local_path
1315 .as_ref()
1316 .map(|local_path| local_path.join(unmapped_file_path_rel)),
1317 },
1318 }
1319 }
1320 }
1321 }
1322 }
1323 }
1324
1325 #[instrument(level = "debug", skip(self), ret)]
1337 fn reverse_map_prefix_heuristically(&self, path: &Path) -> Option<PathBuf> {
1338 let mut found = None;
1339
1340 for (from, to) in self.mapping.iter() {
1341 let has_normal_component = to.components().any(|c| match c {
1342 path::Component::Normal(s) => !s.is_empty(),
1343 _ => false,
1344 });
1345
1346 if !has_normal_component {
1347 continue;
1348 }
1349
1350 let Ok(rest) = path.strip_prefix(to) else {
1351 continue;
1352 };
1353
1354 if found.is_some() {
1355 return None;
1356 }
1357
1358 found = Some(from.join(rest));
1359 }
1360
1361 found
1362 }
1363}