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 fn current_directory(&self) -> io::Result<PathBuf>;
111}
112
113pub struct RealFileLoader;
115
116impl FileLoader for RealFileLoader {
117 fn file_exists(&self, path: &Path) -> bool {
118 path.exists()
119 }
120
121 fn read_file(&self, path: &Path) -> io::Result<String> {
122 let mut file = File::open(path)?;
123 let size = file.metadata().map(|metadata| metadata.len()).ok().unwrap_or(0);
124
125 if size > SourceFile::MAX_FILE_SIZE.into() {
126 return Err(io::Error::other(format!(
127 "text files larger than {} bytes are unsupported",
128 SourceFile::MAX_FILE_SIZE
129 )));
130 }
131 let mut contents = String::new();
132 file.read_to_string(&mut contents)?;
133 Ok(contents)
134 }
135
136 fn read_binary_file(&self, path: &Path) -> io::Result<Arc<[u8]>> {
137 let mut file = fs::File::open(path)?;
138 let len = file.metadata()?.len();
139
140 let mut bytes = Arc::new_uninit_slice(len as usize);
141 let mut buf = BorrowedBuf::from(Arc::get_mut(&mut bytes).unwrap());
142 match file.read_buf_exact(buf.unfilled()) {
143 Ok(()) => {}
144 Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => {
145 drop(bytes);
146 return fs::read(path).map(Vec::into);
147 }
148 Err(e) => return Err(e),
149 }
150 let bytes = unsafe { bytes.assume_init() };
153
154 let mut probe = [0u8; 32];
164 let n = loop {
165 match file.read(&mut probe) {
166 Ok(0) => return Ok(bytes),
167 Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
168 Err(e) => return Err(e),
169 Ok(n) => break n,
170 }
171 };
172 let mut bytes: Vec<u8> = bytes.iter().copied().chain(probe[..n].iter().copied()).collect();
173 file.read_to_end(&mut bytes)?;
174 Ok(bytes.into())
175 }
176
177 fn current_directory(&self) -> io::Result<PathBuf> {
178 std::env::current_dir()
179 }
180}
181
182#[derive(Default)]
187struct SourceMapFiles {
188 source_files: monotonic::MonotonicVec<Arc<SourceFile>>,
189 stable_id_to_source_file: UnhashMap<StableSourceFileId, Arc<SourceFile>>,
190}
191
192pub struct SourceMapInputs {
194 pub file_loader: Box<dyn FileLoader + Send + Sync>,
195 pub path_mapping: FilePathMapping,
196 pub hash_kind: SourceFileHashAlgorithm,
197 pub checksum_hash_kind: Option<SourceFileHashAlgorithm>,
198}
199
200pub struct SourceMap {
201 files: RwLock<SourceMapFiles>,
202 file_loader: IntoDynSyncSend<Box<dyn FileLoader + Sync + Send>>,
203
204 path_mapping: FilePathMapping,
207
208 working_dir: RealFileName,
210
211 hash_kind: SourceFileHashAlgorithm,
213
214 checksum_hash_kind: Option<SourceFileHashAlgorithm>,
219}
220
221impl SourceMap {
222 pub fn new(path_mapping: FilePathMapping) -> SourceMap {
223 Self::with_inputs(SourceMapInputs {
224 file_loader: Box::new(RealFileLoader),
225 path_mapping,
226 hash_kind: SourceFileHashAlgorithm::Md5,
227 checksum_hash_kind: None,
228 })
229 }
230
231 pub fn with_inputs(
232 SourceMapInputs { file_loader, path_mapping, hash_kind, checksum_hash_kind }: SourceMapInputs,
233 ) -> SourceMap {
234 let cwd = file_loader
235 .current_directory()
236 .expect("expecting a current working directory to exist");
237 let working_dir = path_mapping.to_real_filename(&RealFileName::empty(), &cwd);
238 debug!(?working_dir);
239 SourceMap {
240 files: Default::default(),
241 working_dir,
242 file_loader: IntoDynSyncSend(file_loader),
243 path_mapping,
244 hash_kind,
245 checksum_hash_kind,
246 }
247 }
248
249 pub fn path_mapping(&self) -> &FilePathMapping {
250 &self.path_mapping
251 }
252
253 pub fn working_dir(&self) -> &RealFileName {
254 &self.working_dir
255 }
256
257 pub fn file_exists(&self, path: &Path) -> bool {
258 self.file_loader.file_exists(path)
259 }
260
261 pub fn load_file(&self, path: &Path) -> io::Result<Arc<SourceFile>> {
262 let src = self.file_loader.read_file(path)?;
263 let filename = FileName::Real(self.path_mapping.to_real_filename(&self.working_dir, path));
264 Ok(self.new_source_file(filename, src))
265 }
266
267 pub fn load_binary_file(&self, path: &Path) -> io::Result<(Arc<[u8]>, Span)> {
272 let bytes = self.file_loader.read_binary_file(path)?;
273
274 let text = std::str::from_utf8(&bytes).unwrap_or("").to_string();
280 let filename = FileName::Real(self.path_mapping.to_real_filename(&self.working_dir, path));
281 let file = self.new_source_file(filename, text);
282 Ok((
283 bytes,
284 Span::new(
285 file.start_pos,
286 BytePos(file.start_pos.0 + file.normalized_source_len.0),
287 SyntaxContext::root(),
288 None,
289 ),
290 ))
291 }
292
293 pub fn files(&self) -> MappedReadGuard<'_, monotonic::MonotonicVec<Arc<SourceFile>>> {
296 ReadGuard::map(self.files.borrow(), |files| &files.source_files)
297 }
298
299 pub fn source_file_by_stable_id(
300 &self,
301 stable_id: StableSourceFileId,
302 ) -> Option<Arc<SourceFile>> {
303 self.files.borrow().stable_id_to_source_file.get(&stable_id).cloned()
304 }
305
306 fn register_source_file(
307 &self,
308 file_id: StableSourceFileId,
309 mut file: SourceFile,
310 ) -> Result<Arc<SourceFile>, OffsetOverflowError> {
311 let mut files = self.files.borrow_mut();
312
313 file.start_pos = BytePos(if let Some(last_file) = files.source_files.last() {
314 last_file.end_position().0.checked_add(1).ok_or(OffsetOverflowError)?
317 } else {
318 0
319 });
320
321 let file = Arc::new(file);
322 files.source_files.push(Arc::clone(&file));
323 files.stable_id_to_source_file.insert(file_id, Arc::clone(&file));
324
325 Ok(file)
326 }
327
328 pub fn new_source_file(&self, filename: FileName, src: String) -> Arc<SourceFile> {
332 self.try_new_source_file(filename, src).unwrap_or_else(|OffsetOverflowError| {
333 eprintln!(
334 "fatal error: rustc does not support text files larger than {} bytes",
335 SourceFile::MAX_FILE_SIZE
336 );
337 crate::fatal_error::FatalError.raise()
338 })
339 }
340
341 fn try_new_source_file(
342 &self,
343 filename: FileName,
344 src: String,
345 ) -> Result<Arc<SourceFile>, OffsetOverflowError> {
346 let stable_id = StableSourceFileId::from_filename_in_current_crate(&filename);
351 match self.source_file_by_stable_id(stable_id) {
352 Some(lrc_sf) => Ok(lrc_sf),
353 None => {
354 let source_file =
355 SourceFile::new(filename, src, self.hash_kind, self.checksum_hash_kind)?;
356
357 debug_assert_eq!(source_file.stable_id, stable_id);
360
361 self.register_source_file(stable_id, source_file)
362 }
363 }
364 }
365
366 pub fn new_imported_source_file(
371 &self,
372 filename: FileName,
373 src_hash: SourceFileHash,
374 checksum_hash: Option<SourceFileHash>,
375 stable_id: StableSourceFileId,
376 normalized_source_len: u32,
377 unnormalized_source_len: u32,
378 cnum: CrateNum,
379 file_local_lines: FreezeLock<SourceFileLines>,
380 multibyte_chars: Vec<MultiByteChar>,
381 normalized_pos: Vec<NormalizedPos>,
382 metadata_index: u32,
383 ) -> Arc<SourceFile> {
384 let normalized_source_len = RelativeBytePos::from_u32(normalized_source_len);
385
386 let source_file = SourceFile {
387 name: filename,
388 src: None,
389 src_hash,
390 checksum_hash,
391 external_src: FreezeLock::new(ExternalSource::Foreign {
392 kind: ExternalSourceKind::AbsentOk,
393 metadata_index,
394 }),
395 start_pos: BytePos(0),
396 normalized_source_len,
397 unnormalized_source_len,
398 lines: file_local_lines,
399 multibyte_chars,
400 normalized_pos,
401 stable_id,
402 cnum,
403 };
404
405 self.register_source_file(stable_id, source_file)
406 .expect("not enough address space for imported source file")
407 }
408
409 pub fn doctest_offset_line(&self, file: &FileName, orig: usize) -> usize {
411 match file {
412 FileName::DocTest(_, offset) => {
413 if *offset < 0 {
414 orig - (-(*offset)) as usize
415 } else {
416 orig + *offset as usize
417 }
418 }
419 _ => orig,
420 }
421 }
422
423 pub fn lookup_source_file(&self, pos: BytePos) -> Arc<SourceFile> {
425 let idx = self.lookup_source_file_idx(pos);
426 Arc::clone(&(*self.files.borrow().source_files)[idx])
427 }
428
429 pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
431 let sf = self.lookup_source_file(pos);
432 let (line, col, col_display) = sf.lookup_file_pos_with_col_display(pos);
433 Loc { file: sf, line, col, col_display }
434 }
435
436 pub fn lookup_line(&self, pos: BytePos) -> Result<SourceFileAndLine, Arc<SourceFile>> {
438 let f = self.lookup_source_file(pos);
439
440 let pos = f.relative_position(pos);
441 match f.lookup_line(pos) {
442 Some(line) => Ok(SourceFileAndLine { sf: f, line }),
443 None => Err(f),
444 }
445 }
446
447 pub fn span_to_string(&self, sp: Span, display_scope: RemapPathScopeComponents) -> String {
448 self.span_to_string_ext(sp, display_scope, false)
449 }
450
451 pub fn span_to_short_string(
452 &self,
453 sp: Span,
454 display_scope: RemapPathScopeComponents,
455 ) -> String {
456 self.span_to_string_ext(sp, display_scope, true)
457 }
458
459 fn span_to_string_ext(
460 &self,
461 sp: Span,
462 display_scope: RemapPathScopeComponents,
463 short: bool,
464 ) -> String {
465 let (source_file, lo_line, lo_col, hi_line, hi_col) = self.span_to_location_info(sp);
466
467 let file_name = match source_file {
468 Some(sf) => {
469 if short { sf.name.short() } else { sf.name.display(display_scope) }.to_string()
470 }
471 None => return "no-location".to_string(),
472 };
473
474 format!(
475 "{file_name}:{lo_line}:{lo_col}{}",
476 if short { String::new() } else { format!(": {hi_line}:{hi_col}") }
477 )
478 }
479
480 pub fn span_to_location_info(
481 &self,
482 sp: Span,
483 ) -> (Option<Arc<SourceFile>>, usize, usize, usize, usize) {
484 if self.files.borrow().source_files.is_empty() || sp.is_dummy() {
485 return (None, 0, 0, 0, 0);
486 }
487
488 let lo = self.lookup_char_pos(sp.lo());
489 let hi = self.lookup_char_pos(sp.hi());
490 (Some(lo.file), lo.line, lo.col.to_usize() + 1, hi.line, hi.col.to_usize() + 1)
491 }
492
493 pub fn span_to_diagnostic_string(&self, sp: Span) -> String {
497 self.span_to_string(sp, RemapPathScopeComponents::DIAGNOSTICS)
498 }
499
500 pub fn span_to_filename(&self, sp: Span) -> FileName {
501 self.lookup_char_pos(sp.lo()).file.name.clone()
502 }
503
504 pub fn filename_for_diagnostics<'a>(&self, filename: &'a FileName) -> FileNameDisplay<'a> {
505 filename.display(RemapPathScopeComponents::DIAGNOSTICS)
506 }
507
508 pub fn is_multiline(&self, sp: Span) -> bool {
509 let lo = self.lookup_source_file_idx(sp.lo());
510 let hi = self.lookup_source_file_idx(sp.hi());
511 if lo != hi {
512 return true;
513 }
514 let f = Arc::clone(&(*self.files.borrow().source_files)[lo]);
515 let lo = f.relative_position(sp.lo());
516 let hi = f.relative_position(sp.hi());
517 f.lookup_line(lo) != f.lookup_line(hi)
518 }
519
520 #[instrument(skip(self), level = "trace")]
521 pub fn is_valid_span(&self, sp: Span) -> Result<(Loc, Loc), SpanLinesError> {
522 let lo = self.lookup_char_pos(sp.lo());
523 trace!(?lo);
524 let hi = self.lookup_char_pos(sp.hi());
525 trace!(?hi);
526 if lo.file.start_pos != hi.file.start_pos {
527 return Err(SpanLinesError::DistinctSources(Box::new(DistinctSources {
528 begin: (lo.file.name.clone(), lo.file.start_pos),
529 end: (hi.file.name.clone(), hi.file.start_pos),
530 })));
531 }
532 Ok((lo, hi))
533 }
534
535 pub fn is_line_before_span_empty(&self, sp: Span) -> bool {
536 match self.span_to_prev_source(sp) {
537 Ok(s) => s.rsplit_once('\n').unwrap_or(("", &s)).1.trim_start().is_empty(),
538 Err(_) => false,
539 }
540 }
541
542 pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
543 debug!("span_to_lines(sp={:?})", sp);
544 let (lo, hi) = self.is_valid_span(sp)?;
545 assert!(hi.line >= lo.line);
546
547 if sp.is_dummy() {
548 return Ok(FileLines { file: lo.file, lines: Vec::new() });
549 }
550
551 let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
552
553 let mut start_col = lo.col;
556
557 let hi_line = hi.line.saturating_sub(1);
565 for line_index in lo.line.saturating_sub(1)..hi_line {
566 let line_len = lo.file.get_line(line_index).map_or(0, |s| s.chars().count());
567 lines.push(LineInfo { line_index, start_col, end_col: CharPos::from_usize(line_len) });
568 start_col = CharPos::from_usize(0);
569 }
570
571 lines.push(LineInfo { line_index: hi_line, start_col, end_col: hi.col });
573
574 Ok(FileLines { file: lo.file, lines })
575 }
576
577 pub fn span_to_source<F, T>(&self, sp: Span, extract_source: F) -> Result<T, SpanSnippetError>
581 where
582 F: Fn(&str, usize, usize) -> Result<T, SpanSnippetError>,
583 {
584 let local_begin = self.lookup_byte_offset(sp.lo());
585 let local_end = self.lookup_byte_offset(sp.hi());
586
587 if local_begin.sf.start_pos != local_end.sf.start_pos {
588 Err(SpanSnippetError::DistinctSources(Box::new(DistinctSources {
589 begin: (local_begin.sf.name.clone(), local_begin.sf.start_pos),
590 end: (local_end.sf.name.clone(), local_end.sf.start_pos),
591 })))
592 } else {
593 self.ensure_source_file_source_present(&local_begin.sf);
594
595 let start_index = local_begin.pos.to_usize();
596 let end_index = local_end.pos.to_usize();
597 let source_len = local_begin.sf.normalized_source_len.to_usize();
598
599 if start_index > end_index || end_index > source_len {
600 return Err(SpanSnippetError::MalformedForSourcemap(MalformedSourceMapPositions {
601 name: local_begin.sf.name.clone(),
602 source_len,
603 begin_pos: local_begin.pos,
604 end_pos: local_end.pos,
605 }));
606 }
607
608 if let Some(ref src) = local_begin.sf.src {
609 extract_source(src, start_index, end_index)
610 } else if let Some(src) = local_begin.sf.external_src.read().get_source() {
611 extract_source(src, start_index, end_index)
612 } else {
613 Err(SpanSnippetError::SourceNotAvailable { filename: local_begin.sf.name.clone() })
614 }
615 }
616 }
617
618 pub fn is_span_accessible(&self, sp: Span) -> bool {
619 self.span_to_source(sp, |src, start_index, end_index| {
620 Ok(src.get(start_index..end_index).is_some())
621 })
622 .is_ok_and(|is_accessible| is_accessible)
623 }
624
625 pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
627 self.span_to_source(sp, |src, start_index, end_index| {
628 src.get(start_index..end_index)
629 .map(|s| s.to_string())
630 .ok_or(SpanSnippetError::IllFormedSpan(sp))
631 })
632 }
633
634 pub fn span_to_margin(&self, sp: Span) -> Option<usize> {
635 Some(self.indentation_before(sp)?.len())
636 }
637
638 pub fn indentation_before(&self, sp: Span) -> Option<String> {
639 self.span_to_source(sp, |src, start_index, _| {
640 let before = &src[..start_index];
641 let last_line = before.rsplit_once('\n').map_or(before, |(_, last)| last);
642 Ok(last_line
643 .split_once(|c: char| !c.is_whitespace())
644 .map_or(last_line, |(indent, _)| indent)
645 .to_string())
646 })
647 .ok()
648 }
649
650 pub fn span_to_prev_source(&self, sp: Span) -> Result<String, SpanSnippetError> {
652 self.span_to_source(sp, |src, start_index, _| {
653 src.get(..start_index).map(|s| s.to_string()).ok_or(SpanSnippetError::IllFormedSpan(sp))
654 })
655 }
656
657 pub fn span_extend_to_prev_char(&self, sp: Span, c: char, accept_newlines: bool) -> Span {
660 if let Ok(prev_source) = self.span_to_prev_source(sp) {
661 let prev_source = prev_source.rsplit(c).next().unwrap_or("");
662 if !prev_source.is_empty() && (accept_newlines || !prev_source.contains('\n')) {
663 return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32));
664 }
665 }
666
667 sp
668 }
669
670 pub fn span_extend_to_prev_char_before(
673 &self,
674 sp: Span,
675 c: char,
676 accept_newlines: bool,
677 ) -> Span {
678 if let Ok(prev_source) = self.span_to_prev_source(sp) {
679 let prev_source = prev_source.rsplit(c).next().unwrap_or("");
680 if accept_newlines || !prev_source.contains('\n') {
681 return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32 - 1_u32));
682 }
683 }
684
685 sp
686 }
687
688 pub fn span_extend_to_prev_str(
692 &self,
693 sp: Span,
694 pat: &str,
695 accept_newlines: bool,
696 include_whitespace: bool,
697 ) -> Option<Span> {
698 let prev_source = self.span_to_prev_source(sp).ok()?;
703 for ws in &[" ", "\t", "\n"] {
704 let pat = pat.to_owned() + ws;
705 if let Some(pat_pos) = prev_source.rfind(&pat) {
706 let just_after_pat_pos = pat_pos + pat.len() - 1;
707 let just_after_pat_plus_ws = if include_whitespace {
708 just_after_pat_pos
709 + prev_source[just_after_pat_pos..]
710 .find(|c: char| !c.is_whitespace())
711 .unwrap_or(0)
712 } else {
713 just_after_pat_pos
714 };
715 let len = prev_source.len() - just_after_pat_plus_ws;
716 let prev_source = &prev_source[just_after_pat_plus_ws..];
717 if accept_newlines || !prev_source.trim_start().contains('\n') {
718 return Some(sp.with_lo(BytePos(sp.lo().0 - len as u32)));
719 }
720 }
721 }
722
723 None
724 }
725
726 pub fn span_to_next_source(&self, sp: Span) -> Result<String, SpanSnippetError> {
728 self.span_to_source(sp, |src, _, end_index| {
729 src.get(end_index..).map(|s| s.to_string()).ok_or(SpanSnippetError::IllFormedSpan(sp))
730 })
731 }
732
733 pub fn span_extend_while(
735 &self,
736 span: Span,
737 f: impl Fn(char) -> bool,
738 ) -> Result<Span, SpanSnippetError> {
739 self.span_to_source(span, |s, _start, end| {
740 let n = s[end..].char_indices().find(|&(_, c)| !f(c)).map_or(s.len() - end, |(i, _)| i);
741 Ok(span.with_hi(span.hi() + BytePos(n as u32)))
742 })
743 }
744
745 pub fn span_extend_while_whitespace(&self, span: Span) -> Span {
748 self.span_extend_while(span, char::is_whitespace).unwrap_or(span)
749 }
750
751 pub fn span_extend_prev_while(
753 &self,
754 span: Span,
755 f: impl Fn(char) -> bool,
756 ) -> Result<Span, SpanSnippetError> {
757 self.span_to_source(span, |s, start, _end| {
758 let n = s[..start]
759 .char_indices()
760 .rfind(|&(_, c)| !f(c))
761 .map_or(start, |(i, _)| start - i - 1);
762 Ok(span.with_lo(span.lo() - BytePos(n as u32)))
763 })
764 }
765
766 pub fn span_extend_to_next_char(&self, sp: Span, c: char, accept_newlines: bool) -> Span {
768 if let Ok(next_source) = self.span_to_next_source(sp) {
769 let next_source = next_source.split(c).next().unwrap_or("");
770 if !next_source.is_empty() && (accept_newlines || !next_source.contains('\n')) {
771 return sp.with_hi(BytePos(sp.hi().0 + next_source.len() as u32));
772 }
773 }
774
775 sp
776 }
777
778 pub fn span_extend_to_line(&self, sp: Span) -> Span {
780 self.span_extend_to_prev_char(self.span_extend_to_next_char(sp, '\n', true), '\n', true)
781 }
782
783 pub fn span_until_char(&self, sp: Span, c: char) -> Span {
786 match self.span_to_snippet(sp) {
787 Ok(snippet) => {
788 let snippet = snippet.split(c).next().unwrap_or("").trim_end();
789 if !snippet.is_empty() && !snippet.contains('\n') {
790 sp.with_hi(BytePos(sp.lo().0 + snippet.len() as u32))
791 } else {
792 sp
793 }
794 }
795 _ => sp,
796 }
797 }
798
799 pub fn span_wrapped_by_angle_or_parentheses(&self, span: Span) -> bool {
804 self.span_to_source(span, |src, start_index, end_index| {
805 if src.get(start_index..end_index).is_none() {
806 return Ok(false);
807 }
808 let end_src = &src[end_index..];
810 let mut i = 0;
811 let mut found_right_parentheses = false;
812 let mut found_right_angle = false;
813 while let Some(cc) = end_src.chars().nth(i) {
814 if cc == ' ' {
815 i = i + 1;
816 } else if cc == '>' {
817 found_right_angle = true;
819 break;
820 } else if cc == ')' {
821 found_right_parentheses = true;
822 break;
823 } else {
824 return Ok(false);
826 }
827 }
828 i = start_index;
830 let start_src = &src[0..start_index];
831 while let Some(cc) = start_src.chars().nth(i) {
832 if cc == ' ' {
833 if i == 0 {
834 return Ok(false);
835 }
836 i = i - 1;
837 } else if cc == '<' {
838 if !found_right_angle {
840 return Ok(false);
842 }
843 break;
844 } else if cc == '(' {
845 if !found_right_parentheses {
846 return Ok(false);
848 }
849 break;
850 } else {
851 return Ok(false);
853 }
854 }
855 Ok(true)
856 })
857 .is_ok_and(|is_accessible| is_accessible)
858 }
859
860 pub fn span_through_char(&self, sp: Span, c: char) -> Span {
863 if let Ok(snippet) = self.span_to_snippet(sp)
864 && let Some(offset) = snippet.find(c)
865 {
866 return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32));
867 }
868 sp
869 }
870
871 pub fn span_until_non_whitespace(&self, sp: Span) -> Span {
876 let mut whitespace_found = false;
877
878 self.span_take_while(sp, |c| {
879 if !whitespace_found && c.is_whitespace() {
880 whitespace_found = true;
881 }
882
883 !whitespace_found || c.is_whitespace()
884 })
885 }
886
887 pub fn span_until_whitespace(&self, sp: Span) -> Span {
892 self.span_take_while(sp, |c| !c.is_whitespace())
893 }
894
895 pub fn span_take_while<P>(&self, sp: Span, predicate: P) -> Span
897 where
898 P: for<'r> FnMut(&'r char) -> bool,
899 {
900 if let Ok(snippet) = self.span_to_snippet(sp) {
901 let offset = snippet.chars().take_while(predicate).map(|c| c.len_utf8()).sum::<usize>();
902
903 sp.with_hi(BytePos(sp.lo().0 + (offset as u32)))
904 } else {
905 sp
906 }
907 }
908
909 pub fn guess_head_span(&self, sp: Span) -> Span {
915 self.span_until_char(sp, '{')
918 }
919
920 pub fn start_point(&self, sp: Span) -> Span {
922 let width = {
923 let sp = sp.data();
924 let local_begin = self.lookup_byte_offset(sp.lo);
925 let start_index = local_begin.pos.to_usize();
926 let src = local_begin.sf.external_src.read();
927
928 let snippet = if let Some(ref src) = local_begin.sf.src {
929 Some(&src[start_index..])
930 } else {
931 src.get_source().map(|src| &src[start_index..])
932 };
933
934 match snippet {
935 None => 1,
936 Some(snippet) => match snippet.chars().next() {
937 None => 1,
938 Some(c) => c.len_utf8(),
939 },
940 }
941 };
942
943 sp.with_hi(BytePos(sp.lo().0 + width as u32))
944 }
945
946 pub fn end_point(&self, sp: Span) -> Span {
948 let sp = sp.data();
949 let pos = sp.hi.0;
950
951 let width = self.find_width_of_character_at_span(sp, false);
952 let corrected_end_position = pos.checked_sub(width).unwrap_or(pos);
953
954 let end_point = BytePos(cmp::max(corrected_end_position, sp.lo.0));
955 sp.with_lo(end_point)
956 }
957
958 pub fn next_point(&self, sp: Span) -> Span {
965 if sp.is_dummy() {
966 return sp;
967 }
968
969 let sp = sp.data();
970 let start_of_next_point = sp.hi.0;
971 let width = self.find_width_of_character_at_span(sp, true);
972 let end_of_next_point =
976 start_of_next_point.checked_add(width).unwrap_or(start_of_next_point);
977
978 let end_of_next_point = BytePos(cmp::max(start_of_next_point + 1, end_of_next_point));
979 Span::new(BytePos(start_of_next_point), end_of_next_point, sp.ctxt, None)
980 }
981
982 pub fn span_look_ahead(&self, span: Span, expect: &str, limit: Option<usize>) -> Option<Span> {
984 let mut sp = span;
985 for _ in 0..limit.unwrap_or(100_usize) {
986 sp = self.next_point(sp);
987 if let Ok(ref snippet) = self.span_to_snippet(sp) {
988 if snippet == expect {
989 return Some(sp);
990 }
991 if snippet.chars().any(|c| !c.is_whitespace()) {
992 break;
993 }
994 }
995 }
996 None
997 }
998
999 #[instrument(skip(self, sp))]
1002 fn find_width_of_character_at_span(&self, sp: SpanData, forwards: bool) -> u32 {
1003 if sp.lo == sp.hi && !forwards {
1004 debug!("early return empty span");
1005 return 1;
1006 }
1007
1008 let local_begin = self.lookup_byte_offset(sp.lo);
1009 let local_end = self.lookup_byte_offset(sp.hi);
1010 debug!("local_begin=`{:?}`, local_end=`{:?}`", local_begin, local_end);
1011
1012 if local_begin.sf.start_pos != local_end.sf.start_pos {
1013 debug!("begin and end are in different files");
1014 return 1;
1015 }
1016
1017 let start_index = local_begin.pos.to_usize();
1018 let end_index = local_end.pos.to_usize();
1019 debug!("start_index=`{:?}`, end_index=`{:?}`", start_index, end_index);
1020
1021 if (!forwards && end_index == usize::MIN) || (forwards && start_index == usize::MAX) {
1024 debug!("start or end of span, cannot be multibyte");
1025 return 1;
1026 }
1027
1028 let source_len = local_begin.sf.normalized_source_len.to_usize();
1029 debug!("source_len=`{:?}`", source_len);
1030 if start_index > end_index || end_index > source_len - 1 {
1032 debug!("source indexes are malformed");
1033 return 1;
1034 }
1035
1036 let src = local_begin.sf.external_src.read();
1037
1038 let snippet = if let Some(src) = &local_begin.sf.src {
1039 src
1040 } else if let Some(src) = src.get_source() {
1041 src
1042 } else {
1043 return 1;
1044 };
1045
1046 if forwards {
1047 (snippet.ceil_char_boundary(end_index + 1) - end_index) as u32
1048 } else {
1049 (end_index - snippet.floor_char_boundary(end_index - 1)) as u32
1050 }
1051 }
1052
1053 pub fn get_source_file(&self, filename: &FileName) -> Option<Arc<SourceFile>> {
1054 for sf in self.files.borrow().source_files.iter() {
1055 if *filename == sf.name {
1056 return Some(Arc::clone(&sf));
1057 }
1058 }
1059 None
1060 }
1061
1062 pub fn lookup_byte_offset(&self, bpos: BytePos) -> SourceFileAndBytePos {
1064 let idx = self.lookup_source_file_idx(bpos);
1065 let sf = Arc::clone(&(*self.files.borrow().source_files)[idx]);
1066 let offset = bpos - sf.start_pos;
1067 SourceFileAndBytePos { sf, pos: offset }
1068 }
1069
1070 pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize {
1074 self.files.borrow().source_files.partition_point(|x| x.start_pos <= pos) - 1
1075 }
1076
1077 pub fn count_lines(&self) -> usize {
1078 self.files().iter().fold(0, |a, f| a + f.count_lines())
1079 }
1080
1081 pub fn ensure_source_file_source_present(&self, source_file: &SourceFile) -> bool {
1082 source_file.add_external_src(|| {
1083 let FileName::Real(ref name) = source_file.name else {
1084 return None;
1085 };
1086
1087 let local_path: Cow<'_, Path> = match name.local_path() {
1088 Some(local) => local.into(),
1089 None => {
1090 let maybe_remapped_path = name.path(RemapPathScopeComponents::DIAGNOSTICS);
1097 self.path_mapping
1098 .reverse_map_prefix_heuristically(maybe_remapped_path)
1099 .map(Cow::from)
1100 .unwrap_or(maybe_remapped_path.into())
1101 }
1102 };
1103
1104 self.file_loader.read_file(&local_path).ok()
1105 })
1106 }
1107
1108 pub fn is_imported(&self, sp: Span) -> bool {
1109 let source_file_index = self.lookup_source_file_idx(sp.lo());
1110 let source_file = &self.files()[source_file_index];
1111 source_file.is_imported()
1112 }
1113
1114 pub fn stmt_span(&self, stmt_span: Span, block_span: Span) -> Span {
1118 if !stmt_span.from_expansion() {
1119 return stmt_span;
1120 }
1121 let mac_call = original_sp(stmt_span, block_span);
1122 self.mac_call_stmt_semi_span(mac_call).map_or(mac_call, |s| mac_call.with_hi(s.hi()))
1123 }
1124
1125 pub fn mac_call_stmt_semi_span(&self, mac_call: Span) -> Option<Span> {
1133 let span = self.span_extend_while_whitespace(mac_call);
1134 let span = self.next_point(span);
1135 if self.span_to_snippet(span).as_deref() == Ok(";") { Some(span) } else { None }
1136 }
1137}
1138
1139pub fn get_source_map() -> Option<Arc<SourceMap>> {
1140 with_session_globals(|session_globals| session_globals.source_map.clone())
1141}
1142
1143#[derive(Clone)]
1144pub struct FilePathMapping {
1145 mapping: Vec<(PathBuf, PathBuf)>,
1146 filename_remapping_scopes: RemapPathScopeComponents,
1147}
1148
1149impl FilePathMapping {
1150 pub fn empty() -> FilePathMapping {
1151 FilePathMapping::new(Vec::new(), RemapPathScopeComponents::empty())
1152 }
1153
1154 pub fn new(
1155 mapping: Vec<(PathBuf, PathBuf)>,
1156 filename_remapping_scopes: RemapPathScopeComponents,
1157 ) -> FilePathMapping {
1158 FilePathMapping { mapping, filename_remapping_scopes }
1159 }
1160
1161 fn map_prefix<'a>(&'a self, path: impl Into<Cow<'a, Path>>) -> (Cow<'a, Path>, bool) {
1165 let path = path.into();
1166 if path.as_os_str().is_empty() {
1167 return (path, false);
1170 }
1171
1172 return remap_path_prefix(&self.mapping, path);
1173
1174 #[instrument(level = "debug", skip(mapping), ret)]
1175 fn remap_path_prefix<'a>(
1176 mapping: &'a [(PathBuf, PathBuf)],
1177 path: Cow<'a, Path>,
1178 ) -> (Cow<'a, Path>, bool) {
1179 for (from, to) in mapping.iter().rev() {
1183 debug!("Trying to apply {from:?} => {to:?}");
1184
1185 if let Ok(rest) = path.strip_prefix(from) {
1186 let remapped = if rest.as_os_str().is_empty() {
1187 to.into()
1194 } else {
1195 to.join(rest).into()
1196 };
1197 debug!("Match - remapped");
1198
1199 return (remapped, true);
1200 } else {
1201 debug!("No match - prefix {from:?} does not match");
1202 }
1203 }
1204
1205 debug!("not remapped");
1206 (path, false)
1207 }
1208 }
1209
1210 pub fn to_real_filename<'a>(
1215 &self,
1216 working_directory: &RealFileName,
1217 local_path: impl Into<Cow<'a, Path>>,
1218 ) -> RealFileName {
1219 let local_path = local_path.into();
1220
1221 let (remapped_path, mut was_remapped) = self.map_prefix(&*local_path);
1222 debug!(?local_path, ?remapped_path, ?was_remapped, ?self.filename_remapping_scopes);
1223
1224 let local = InnerRealFileName {
1227 name: local_path.to_path_buf(),
1228 working_directory: working_directory
1229 .local_path()
1230 .expect("working directory should be local")
1231 .to_path_buf(),
1232 embeddable_name: if local_path.is_absolute() {
1233 local_path.to_path_buf()
1234 } else {
1235 working_directory
1236 .local_path()
1237 .expect("working directory should be local")
1238 .to_path_buf()
1239 .join(&local_path)
1240 },
1241 };
1242
1243 RealFileName {
1244 maybe_remapped: InnerRealFileName {
1245 working_directory: working_directory.maybe_remapped.name.clone(),
1246 embeddable_name: if remapped_path.is_absolute() || was_remapped {
1247 was_remapped = was_remapped || working_directory.was_remapped();
1250
1251 remapped_path.to_path_buf()
1252 } else {
1253 let (abs_path, abs_was_remapped) = self.map_prefix(
1255 working_directory.maybe_remapped.name.clone().join(&remapped_path),
1256 );
1257
1258 was_remapped = abs_was_remapped || working_directory.was_remapped();
1261
1262 abs_path.to_path_buf()
1263 },
1264 name: remapped_path.to_path_buf(),
1265 },
1266 local: Some(local),
1267 scopes: if was_remapped {
1268 self.filename_remapping_scopes
1269 } else {
1270 RemapPathScopeComponents::empty()
1271 },
1272 }
1273 }
1274
1275 #[instrument(level = "debug", skip(self), ret)]
1287 fn reverse_map_prefix_heuristically(&self, path: &Path) -> Option<PathBuf> {
1288 let mut found = None;
1289
1290 for (from, to) in self.mapping.iter() {
1291 let has_normal_component = to.components().any(|c| match c {
1292 path::Component::Normal(s) => !s.is_empty(),
1293 _ => false,
1294 });
1295
1296 if !has_normal_component {
1297 continue;
1298 }
1299
1300 let Ok(rest) = path.strip_prefix(to) else {
1301 continue;
1302 };
1303
1304 if found.is_some() {
1305 return None;
1306 }
1307
1308 found = Some(from.join(rest));
1309 }
1310
1311 found
1312 }
1313}