Skip to main content

rustc_span/
source_map.rs

1//! Types for tracking pieces of source code within a crate.
2//!
3//! The [`SourceMap`] tracks all the source code used within a single crate, mapping
4//! from integer byte positions to the original source code location. Each bit
5//! of source parsed during crate parsing (typically files, in-memory strings,
6//! or various bits of macro expansion) cover a continuous range of bytes in the
7//! `SourceMap` and are represented by [`SourceFile`]s. Byte positions are stored in
8//! [`Span`] and used pervasively in the compiler. They are absolute positions
9//! within the `SourceMap`, which upon request can be converted to line and column
10//! information, source code snippets, etc.
11
12use 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_lexer::{FrontmatterAllowed, TokenKind, tokenize};
19use tracing::{debug, instrument, trace};
20
21use crate::*;
22
23#[cfg(test)]
24mod tests;
25
26/// Returns the span itself if it doesn't come from a macro expansion,
27/// otherwise return the call site span up to the `enclosing_sp` by
28/// following the `expn_data` chain.
29pub 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    /// A `MonotonicVec` is a `Vec` which can only be grown.
50    /// Once inserted, an element can never be removed or swapped,
51    /// guaranteeing that any indices into a `MonotonicVec` are stable
52    // This is declared in its own module to ensure that the private
53    // field is inaccessible
54    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(::alloc::vec::Vec::new()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// _____________________________________________________________________________
78// SourceFile, MultiByteChar, FileName, FileLines
79//
80
81/// An abstraction over the fs operations used by the Parser.
82pub trait FileLoader {
83    /// Query the existence of a file.
84    fn file_exists(&self, path: &Path) -> bool;
85
86    /// Read the contents of a UTF-8 file into memory.
87    /// This function must return a String because we normalize
88    /// source files, which may require resizing.
89    fn read_file(&self, path: &Path) -> io::Result<String>;
90
91    /// Read the contents of a potentially non-UTF-8 file into memory.
92    /// We don't normalize binary files, so we can start in an Arc.
93    fn read_binary_file(&self, path: &Path) -> io::Result<Arc<[u8]>>;
94
95    /// Current working directory
96    fn current_directory(&self) -> io::Result<PathBuf>;
97}
98
99/// A FileLoader that uses std::fs to load real files.
100pub struct RealFileLoader;
101
102impl FileLoader for RealFileLoader {
103    fn file_exists(&self, path: &Path) -> bool {
104        path.exists()
105    }
106
107    fn read_file(&self, path: &Path) -> io::Result<String> {
108        let mut file = File::open(path)?;
109        let size = file.metadata().map(|metadata| metadata.len()).ok().unwrap_or(0);
110
111        if size > SourceFile::MAX_FILE_SIZE.into() {
112            return Err(io::Error::other(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("text files larger than {0} bytes are unsupported",
                SourceFile::MAX_FILE_SIZE))
    })format!(
113                "text files larger than {} bytes are unsupported",
114                SourceFile::MAX_FILE_SIZE
115            )));
116        }
117        let mut contents = String::new();
118        file.read_to_string(&mut contents)?;
119        Ok(contents)
120    }
121
122    fn read_binary_file(&self, path: &Path) -> io::Result<Arc<[u8]>> {
123        let mut file = fs::File::open(path)?;
124        let len = file.metadata()?.len();
125
126        let mut bytes = Arc::new_uninit_slice(len as usize);
127        let mut buf = BorrowedBuf::from(Arc::get_mut(&mut bytes).unwrap());
128        match file.read_buf_exact(buf.unfilled()) {
129            Ok(()) => {}
130            Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => {
131                drop(bytes);
132                return fs::read(path).map(Vec::into);
133            }
134            Err(e) => return Err(e),
135        }
136        // SAFETY: If the read_buf_exact call returns Ok(()), then we have
137        // read len bytes and initialized the buffer.
138        let bytes = unsafe { bytes.assume_init() };
139
140        // At this point, we've read all the bytes that filesystem metadata reported exist.
141        // But we are not guaranteed to be at the end of the file, because we did not attempt to do
142        // a read with a non-zero-sized buffer and get Ok(0).
143        // So we do small read to a fixed-size buffer. If the read returns no bytes then we're
144        // already done, and we just return the Arc we built above.
145        // If the read returns bytes however, we just fall back to reading into a Vec then turning
146        // that into an Arc, losing our nice peak memory behavior. This fallback code path should
147        // be rarely exercised.
148
149        let mut probe = [0u8; 32];
150        let n = loop {
151            match file.read(&mut probe) {
152                Ok(0) => return Ok(bytes),
153                Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
154                Err(e) => return Err(e),
155                Ok(n) => break n,
156            }
157        };
158        let mut bytes: Vec<u8> = bytes.iter().copied().chain(probe[..n].iter().copied()).collect();
159        file.read_to_end(&mut bytes)?;
160        Ok(bytes.into())
161    }
162
163    fn current_directory(&self) -> io::Result<PathBuf> {
164        std::env::current_dir()
165    }
166}
167
168// _____________________________________________________________________________
169// SourceMap
170//
171
172#[derive(#[automatically_derived]impl ::core::default::Default for SourceMapFiles {
    #[inline]
    fn default() -> Self {
        SourceMapFiles {
            source_files: ::core::default::Default::default(),
            stable_id_to_source_file: ::core::default::Default::default(),
        }
    }
}Default)]
173struct SourceMapFiles {
174    source_files: monotonic::MonotonicVec<Arc<SourceFile>>,
175    stable_id_to_source_file: UnhashMap<StableSourceFileId, Arc<SourceFile>>,
176}
177
178impl std::fmt::Debug for SourceMapFiles {
179    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
180        let SourceMapFiles { source_files, stable_id_to_source_file: _ } = self;
181
182        f.debug_list()
183            .entries(
184                source_files.iter().map(|f| f.name.prefer_remapped_unconditionally().to_string()),
185            )
186            .finish()
187    }
188}
189
190/// Used to construct a `SourceMap` with `SourceMap::with_inputs`.
191pub struct SourceMapInputs {
192    pub file_loader: Box<dyn FileLoader + Send + Sync>,
193    pub path_mapping: FilePathMapping,
194    pub hash_kind: SourceFileHashAlgorithm,
195    pub checksum_hash_kind: Option<SourceFileHashAlgorithm>,
196}
197
198pub struct SourceMap {
199    files: RwLock<SourceMapFiles>,
200    file_loader: IntoDynSyncSend<Box<dyn FileLoader + Sync + Send>>,
201
202    // This is used to apply the file path remapping as specified via
203    // `--remap-path-prefix` to all `SourceFile`s allocated within this `SourceMap`.
204    path_mapping: FilePathMapping,
205
206    /// Current working directory
207    working_dir: RealFileName,
208
209    /// The algorithm used for hashing the contents of each source file.
210    hash_kind: SourceFileHashAlgorithm,
211
212    /// Similar to `hash_kind`, however this algorithm is used for checksums to determine if a crate is fresh.
213    /// `cargo` is the primary user of these.
214    ///
215    /// If this is equal to `hash_kind` then the checksum won't be computed twice.
216    checksum_hash_kind: Option<SourceFileHashAlgorithm>,
217}
218
219impl std::fmt::Debug for SourceMap {
220    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
221        let SourceMap {
222            files,
223            file_loader,
224            path_mapping,
225            working_dir,
226            hash_kind,
227            checksum_hash_kind,
228        } = self;
229
230        f.debug_struct("SourceMap")
231            .field("files", files)
232            .field("file_loader", &format_args!("<file_loader@{0:p}>", file_loader)format_args!("<file_loader@{file_loader:p}>"))
233            .field("path_mapping", path_mapping)
234            .field("working_dir", working_dir)
235            .field("hash_kind", hash_kind)
236            .field("checksum_hash_kind", checksum_hash_kind)
237            .finish()
238    }
239}
240
241impl SourceMap {
242    pub fn new(path_mapping: FilePathMapping) -> SourceMap {
243        Self::with_inputs(SourceMapInputs {
244            file_loader: Box::new(RealFileLoader),
245            path_mapping,
246            hash_kind: SourceFileHashAlgorithm::Md5,
247            checksum_hash_kind: None,
248        })
249    }
250
251    pub fn with_inputs(
252        SourceMapInputs { file_loader, path_mapping, hash_kind, checksum_hash_kind }: SourceMapInputs,
253    ) -> SourceMap {
254        let cwd = file_loader
255            .current_directory()
256            .expect("expecting a current working directory to exist");
257        let working_dir = path_mapping.to_real_filename(&RealFileName::empty(), &cwd);
258        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs:258",
                        "rustc_span::source_map", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs"),
                        ::tracing_core::__macro_support::Option::Some(258u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_span::source_map"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("working_dir")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("working_dir");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&working_dir)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?working_dir);
259        SourceMap {
260            files: Default::default(),
261            working_dir,
262            file_loader: IntoDynSyncSend(file_loader),
263            path_mapping,
264            hash_kind,
265            checksum_hash_kind,
266        }
267    }
268
269    pub fn path_mapping(&self) -> &FilePathMapping {
270        &self.path_mapping
271    }
272
273    pub fn working_dir(&self) -> &RealFileName {
274        &self.working_dir
275    }
276
277    pub fn file_exists(&self, path: &Path) -> bool {
278        self.file_loader.file_exists(path)
279    }
280
281    pub fn load_file(&self, path: &Path) -> io::Result<Arc<SourceFile>> {
282        let src = self.file_loader.read_file(path)?;
283        let filename = FileName::Real(self.path_mapping.to_real_filename(&self.working_dir, path));
284        Ok(self.new_source_file(filename, src))
285    }
286
287    /// Loads source file as a binary blob.
288    ///
289    /// Unlike `load_file`, guarantees that no normalization like BOM-removal
290    /// takes place.
291    pub fn load_binary_file(&self, path: &Path) -> io::Result<(Arc<[u8]>, Span)> {
292        let bytes = self.file_loader.read_binary_file(path)?;
293
294        // We need to add file to the `SourceMap`, so that it is present
295        // in dep-info. There's also an edge case that file might be both
296        // loaded as a binary via `include_bytes!` and as proper `SourceFile`
297        // via `mod`, so we try to use real file contents and not just an
298        // empty string.
299        let text = std::str::from_utf8(&bytes).unwrap_or("").to_string();
300        let filename = FileName::Real(self.path_mapping.to_real_filename(&self.working_dir, path));
301        let file = self.new_source_file(filename, text);
302        Ok((
303            bytes,
304            Span::new(
305                file.start_pos,
306                BytePos(file.start_pos.0 + file.normalized_source_len.0),
307                SyntaxContext::root(),
308                None,
309            ),
310        ))
311    }
312
313    // By returning a `MonotonicVec`, we ensure that consumers cannot invalidate
314    // any existing indices pointing into `files`.
315    pub fn files(&self) -> MappedReadGuard<'_, monotonic::MonotonicVec<Arc<SourceFile>>> {
316        ReadGuard::map(self.files.borrow(), |files| &files.source_files)
317    }
318
319    pub fn source_file_by_stable_id(
320        &self,
321        stable_id: StableSourceFileId,
322    ) -> Option<Arc<SourceFile>> {
323        self.files.borrow().stable_id_to_source_file.get(&stable_id).cloned()
324    }
325
326    fn register_source_file(
327        &self,
328        file_id: StableSourceFileId,
329        mut file: SourceFile,
330    ) -> Result<Arc<SourceFile>, OffsetOverflowError> {
331        let mut files = self.files.borrow_mut();
332
333        file.start_pos = BytePos(if let Some(last_file) = files.source_files.last() {
334            // Add one so there is some space between files. This lets us distinguish
335            // positions in the `SourceMap`, even in the presence of zero-length files.
336            last_file.end_position().0.checked_add(1).ok_or(OffsetOverflowError)?
337        } else {
338            0
339        });
340
341        let file = Arc::new(file);
342        files.source_files.push(Arc::clone(&file));
343        files.stable_id_to_source_file.insert(file_id, Arc::clone(&file));
344
345        Ok(file)
346    }
347
348    /// Creates a new `SourceFile`.
349    /// If a file already exists in the `SourceMap` with the same ID, that file is returned
350    /// unmodified.
351    pub fn new_source_file(&self, filename: FileName, src: String) -> Arc<SourceFile> {
352        self.try_new_source_file(filename, src).unwrap_or_else(|OffsetOverflowError| {
353            {
    ::std::io::_eprint(format_args!("fatal error: rustc does not support text files larger than {0} bytes\n",
            SourceFile::MAX_FILE_SIZE));
};eprintln!(
354                "fatal error: rustc does not support text files larger than {} bytes",
355                SourceFile::MAX_FILE_SIZE
356            );
357            crate::fatal_error::FatalError.raise()
358        })
359    }
360
361    fn try_new_source_file(
362        &self,
363        filename: FileName,
364        src: String,
365    ) -> Result<Arc<SourceFile>, OffsetOverflowError> {
366        // Note that filename may not be a valid path, eg it may be `<anon>` etc,
367        // but this is okay because the directory determined by `path.pop()` will
368        // be empty, so the working directory will be used.
369
370        let stable_id = StableSourceFileId::from_filename_in_current_crate(&filename);
371        match self.source_file_by_stable_id(stable_id) {
372            Some(lrc_sf) => Ok(lrc_sf),
373            None => {
374                let source_file =
375                    SourceFile::new(filename, src, self.hash_kind, self.checksum_hash_kind)?;
376
377                // Let's make sure the file_id we generated above actually matches
378                // the ID we generate for the SourceFile we just created.
379                if true {
    {
        match (&source_file.stable_id, &stable_id) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(source_file.stable_id, stable_id);
380
381                self.register_source_file(stable_id, source_file)
382            }
383        }
384    }
385
386    /// Allocates a new `SourceFile` representing a source file from an external
387    /// crate. The source code of such an "imported `SourceFile`" is not available,
388    /// but we still know enough to generate accurate debuginfo location
389    /// information for things inlined from other crates.
390    pub fn new_imported_source_file(
391        &self,
392        filename: FileName,
393        src_hash: SourceFileHash,
394        checksum_hash: Option<SourceFileHash>,
395        stable_id: StableSourceFileId,
396        normalized_source_len: u32,
397        unnormalized_source_len: u32,
398        cnum: CrateNum,
399        file_local_lines: FreezeLock<SourceFileLines>,
400        multibyte_chars: Vec<MultiByteChar>,
401        normalized_pos: Vec<NormalizedPos>,
402        metadata_index: u32,
403    ) -> Arc<SourceFile> {
404        let normalized_source_len = RelativeBytePos::from_u32(normalized_source_len);
405
406        let source_file = SourceFile {
407            name: filename,
408            src: None,
409            src_hash,
410            checksum_hash,
411            external_src: FreezeLock::new(ExternalSource::Foreign {
412                kind: ExternalSourceKind::AbsentOk,
413                metadata_index,
414            }),
415            start_pos: BytePos(0),
416            normalized_source_len,
417            unnormalized_source_len,
418            lines: file_local_lines,
419            multibyte_chars,
420            normalized_pos,
421            stable_id,
422            cnum,
423        };
424
425        self.register_source_file(stable_id, source_file)
426            .expect("not enough address space for imported source file")
427    }
428
429    /// If there is a doctest offset, applies it to the line.
430    pub fn doctest_offset_line(&self, file: &FileName, orig: usize) -> usize {
431        match file {
432            FileName::DocTest(_, offset) => {
433                if *offset < 0 {
434                    orig - (-(*offset)) as usize
435                } else {
436                    orig + *offset as usize
437                }
438            }
439            _ => orig,
440        }
441    }
442
443    /// Return the SourceFile that contains the given `BytePos`
444    pub fn lookup_source_file(&self, pos: BytePos) -> Arc<SourceFile> {
445        let idx = self.lookup_source_file_idx(pos);
446        Arc::clone(&(*self.files.borrow().source_files)[idx])
447    }
448
449    /// Looks up source information about a `BytePos`.
450    pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
451        let sf = self.lookup_source_file(pos);
452        let (line, col, col_display) = sf.lookup_file_pos_with_col_display(pos);
453        Loc { file: sf, line, col, col_display }
454    }
455
456    /// If the corresponding `SourceFile` is empty, does not return a line number.
457    pub fn lookup_line(&self, pos: BytePos) -> Result<SourceFileAndLine, Arc<SourceFile>> {
458        let f = self.lookup_source_file(pos);
459
460        let pos = f.relative_position(pos);
461        match f.lookup_line(pos) {
462            Some(line) => Ok(SourceFileAndLine { sf: f, line }),
463            None => Err(f),
464        }
465    }
466
467    pub fn span_to_string(&self, sp: Span, display_scope: RemapPathScopeComponents) -> String {
468        self.span_to_string_ext(sp, display_scope, false)
469    }
470
471    pub fn span_to_short_string(
472        &self,
473        sp: Span,
474        display_scope: RemapPathScopeComponents,
475    ) -> String {
476        self.span_to_string_ext(sp, display_scope, true)
477    }
478
479    fn span_to_string_ext(
480        &self,
481        sp: Span,
482        display_scope: RemapPathScopeComponents,
483        short: bool,
484    ) -> String {
485        let (source_file, lo_line, lo_col, hi_line, hi_col) = self.span_to_location_info(sp);
486
487        let file_name = match source_file {
488            Some(sf) => {
489                if short { sf.name.short() } else { sf.name.display(display_scope) }.to_string()
490            }
491            None => return "no-location".to_string(),
492        };
493
494        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{1}:{2}:{3}{0}",
                if short {
                    String::new()
                } else {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!(": {0}:{1}", hi_line,
                                    hi_col))
                        })
                }, file_name, lo_line, lo_col))
    })format!(
495            "{file_name}:{lo_line}:{lo_col}{}",
496            if short { String::new() } else { format!(": {hi_line}:{hi_col}") }
497        )
498    }
499
500    pub fn span_to_location_info(
501        &self,
502        sp: Span,
503    ) -> (Option<Arc<SourceFile>>, usize, usize, usize, usize) {
504        if self.files.borrow().source_files.is_empty() || sp.is_dummy() {
505            return (None, 0, 0, 0, 0);
506        }
507
508        let lo = self.lookup_char_pos(sp.lo());
509        let hi = self.lookup_char_pos(sp.hi());
510        (Some(lo.file), lo.line, lo.col.to_usize() + 1, hi.line, hi.col.to_usize() + 1)
511    }
512
513    /// Format the span location to be printed in diagnostics. Must not be emitted
514    /// to build artifacts as this may leak local file paths. Use span_to_embeddable_string
515    /// for string suitable for embedding.
516    pub fn span_to_diagnostic_string(&self, sp: Span) -> String {
517        self.span_to_string(sp, RemapPathScopeComponents::DIAGNOSTICS)
518    }
519
520    pub fn span_to_filename(&self, sp: Span) -> FileName {
521        self.lookup_char_pos(sp.lo()).file.name.clone()
522    }
523
524    pub fn filename_for_diagnostics<'a>(&self, filename: &'a FileName) -> FileNameDisplay<'a> {
525        filename.display(RemapPathScopeComponents::DIAGNOSTICS)
526    }
527
528    pub fn is_multiline(&self, sp: Span) -> bool {
529        let lo = self.lookup_source_file_idx(sp.lo());
530        let hi = self.lookup_source_file_idx(sp.hi());
531        if lo != hi {
532            return true;
533        }
534        let f = Arc::clone(&(*self.files.borrow().source_files)[lo]);
535        let lo = f.relative_position(sp.lo());
536        let hi = f.relative_position(sp.hi());
537        f.lookup_line(lo) != f.lookup_line(hi)
538    }
539
540    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("is_valid_span",
                                    "rustc_span::source_map", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs"),
                                    ::tracing_core::__macro_support::Option::Some(540u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_span::source_map"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("sp")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("sp");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sp)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    Result<(Loc, Loc), SpanLinesError> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let lo = self.lookup_char_pos(sp.lo());
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs:543",
                                    "rustc_span::source_map", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs"),
                                    ::tracing_core::__macro_support::Option::Some(543u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_span::source_map"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("lo")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("lo");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lo)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let hi = self.lookup_char_pos(sp.hi());
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs:545",
                                    "rustc_span::source_map", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs"),
                                    ::tracing_core::__macro_support::Option::Some(545u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_span::source_map"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("hi")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("hi");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hi)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            if lo.file.start_pos != hi.file.start_pos {
                return Err(SpanLinesError::DistinctSources(Box::new(DistinctSources {
                                    begin: (lo.file.name.clone(), lo.file.start_pos),
                                    end: (hi.file.name.clone(), hi.file.start_pos),
                                })));
            }
            Ok((lo, hi))
        }
    }
}#[instrument(skip(self), level = "trace")]
541    pub fn is_valid_span(&self, sp: Span) -> Result<(Loc, Loc), SpanLinesError> {
542        let lo = self.lookup_char_pos(sp.lo());
543        trace!(?lo);
544        let hi = self.lookup_char_pos(sp.hi());
545        trace!(?hi);
546        if lo.file.start_pos != hi.file.start_pos {
547            return Err(SpanLinesError::DistinctSources(Box::new(DistinctSources {
548                begin: (lo.file.name.clone(), lo.file.start_pos),
549                end: (hi.file.name.clone(), hi.file.start_pos),
550            })));
551        }
552        Ok((lo, hi))
553    }
554
555    pub fn is_line_before_span_empty(&self, sp: Span) -> bool {
556        match self.span_to_prev_source(sp) {
557            Ok(s) => s.rsplit_once('\n').unwrap_or(("", &s)).1.trim_start().is_empty(),
558            Err(_) => false,
559        }
560    }
561
562    pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
563        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs:563",
                        "rustc_span::source_map", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs"),
                        ::tracing_core::__macro_support::Option::Some(563u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_span::source_map"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("span_to_lines(sp={0:?})",
                                                    sp) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("span_to_lines(sp={:?})", sp);
564        let (lo, hi) = self.is_valid_span(sp)?;
565        if !(hi.line >= lo.line) {
    ::core::panicking::panic("assertion failed: hi.line >= lo.line")
};assert!(hi.line >= lo.line);
566
567        if sp.is_dummy() {
568            return Ok(FileLines { file: lo.file, lines: Vec::new() });
569        }
570
571        let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
572
573        // The span starts partway through the first line,
574        // but after that it starts from offset 0.
575        let mut start_col = lo.col;
576
577        // For every line but the last, it extends from `start_col`
578        // and to the end of the line. Be careful because the line
579        // numbers in Loc are 1-based, so we subtract 1 to get 0-based
580        // lines.
581        //
582        // FIXME: now that we handle DUMMY_SP up above, we should consider
583        // asserting that the line numbers here are all indeed 1-based.
584        let hi_line = hi.line.saturating_sub(1);
585        for line_index in lo.line.saturating_sub(1)..hi_line {
586            let line_len = lo.file.get_line(line_index).map_or(0, |s| s.chars().count());
587            lines.push(LineInfo { line_index, start_col, end_col: CharPos::from_usize(line_len) });
588            start_col = CharPos::from_usize(0);
589        }
590
591        // For the last line, it extends from `start_col` to `hi.col`:
592        lines.push(LineInfo { line_index: hi_line, start_col, end_col: hi.col });
593
594        Ok(FileLines { file: lo.file, lines })
595    }
596
597    /// Extracts the source surrounding the given `Span` using the `extract_source` function. The
598    /// extract function takes three arguments: a string slice containing the source, an index in
599    /// the slice for the beginning of the span and an index in the slice for the end of the span.
600    pub fn span_to_source<F, T>(
601        &self,
602        sp: Span,
603        mut extract_source: F,
604    ) -> Result<T, SpanSnippetError>
605    where
606        F: FnMut(&str, usize, usize) -> Result<T, SpanSnippetError>,
607    {
608        let local_begin = self.lookup_byte_offset(sp.lo());
609        let local_end = self.lookup_byte_offset(sp.hi());
610
611        if local_begin.sf.start_pos != local_end.sf.start_pos {
612            Err(SpanSnippetError::DistinctSources(Box::new(DistinctSources {
613                begin: (local_begin.sf.name.clone(), local_begin.sf.start_pos),
614                end: (local_end.sf.name.clone(), local_end.sf.start_pos),
615            })))
616        } else {
617            self.ensure_source_file_source_present(&local_begin.sf);
618
619            let start_index = local_begin.pos.to_usize();
620            let end_index = local_end.pos.to_usize();
621            let source_len = local_begin.sf.normalized_source_len.to_usize();
622
623            if start_index > end_index || end_index > source_len {
624                return Err(SpanSnippetError::MalformedForSourcemap(MalformedSourceMapPositions {
625                    name: local_begin.sf.name.clone(),
626                    source_len,
627                    begin_pos: local_begin.pos,
628                    end_pos: local_end.pos,
629                }));
630            }
631
632            if let Some(ref src) = local_begin.sf.src {
633                extract_source(src, start_index, end_index)
634            } else if let Some(src) = local_begin.sf.external_src.read().get_source() {
635                extract_source(src, start_index, end_index)
636            } else {
637                Err(SpanSnippetError::SourceNotAvailable { filename: local_begin.sf.name.clone() })
638            }
639        }
640    }
641
642    pub fn is_span_accessible(&self, sp: Span) -> bool {
643        self.span_to_source(sp, |src, start_index, end_index| {
644            Ok(src.get(start_index..end_index).is_some())
645        })
646        .is_ok_and(|is_accessible| is_accessible)
647    }
648
649    /// Returns the source snippet as `String` corresponding to the given `Span`.
650    pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
651        self.span_to_source(sp, |src, start_index, end_index| {
652            src.get(start_index..end_index)
653                .map(|s| s.to_string())
654                .ok_or(SpanSnippetError::IllFormedSpan(sp))
655        })
656    }
657
658    pub fn span_to_margin(&self, sp: Span) -> Option<usize> {
659        Some(self.indentation_before(sp)?.len())
660    }
661
662    pub fn indentation_before(&self, sp: Span) -> Option<String> {
663        self.span_to_source(sp, |src, start_index, _| {
664            let before = &src[..start_index];
665            let last_line = before.rsplit_once('\n').map_or(before, |(_, last)| last);
666            Ok(last_line
667                .split_once(|c: char| !c.is_whitespace())
668                .map_or(last_line, |(indent, _)| indent)
669                .to_string())
670        })
671        .ok()
672    }
673
674    /// Returns the source snippet as `String` before the given `Span`.
675    pub fn span_to_prev_source(&self, sp: Span) -> Result<String, SpanSnippetError> {
676        self.span_to_source(sp, |src, start_index, _| {
677            src.get(..start_index).map(|s| s.to_string()).ok_or(SpanSnippetError::IllFormedSpan(sp))
678        })
679    }
680
681    /// Extends the given `Span` to just after the previous occurrence of `c`. Return the same span
682    /// if no character could be found or if an error occurred while retrieving the code snippet.
683    pub fn span_extend_to_prev_char(&self, sp: Span, c: char, accept_newlines: bool) -> Span {
684        if let Ok(prev_source) = self.span_to_prev_source(sp) {
685            let prev_source = prev_source.rsplit(c).next().unwrap_or("");
686            if !prev_source.is_empty() && (accept_newlines || !prev_source.contains('\n')) {
687                return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32));
688            }
689        }
690
691        sp
692    }
693
694    /// Extends the given `Span` to just before the previous occurrence of `c`. Return the same span
695    /// if an error occurred while retrieving the code snippet.
696    pub fn span_extend_to_prev_char_before(
697        &self,
698        sp: Span,
699        c: char,
700        accept_newlines: bool,
701    ) -> Span {
702        if let Ok(prev_source) = self.span_to_prev_source(sp) {
703            let prev_source = prev_source.rsplit(c).next().unwrap_or("");
704            if accept_newlines || !prev_source.contains('\n') {
705                return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32 - 1_u32));
706            }
707        }
708
709        sp
710    }
711
712    /// Extends the given `Span` to just after the previous occurrence of `pat` when surrounded by
713    /// whitespace. Returns None if the pattern could not be found or if an error occurred while
714    /// retrieving the code snippet.
715    pub fn span_extend_to_prev_str(
716        &self,
717        sp: Span,
718        pat: &str,
719        accept_newlines: bool,
720        include_whitespace: bool,
721    ) -> Option<Span> {
722        // assure that the pattern is delimited, to avoid the following
723        //     fn my_fn()
724        //           ^^^^ returned span without the check
725        //     ---------- correct span
726        let prev_source = self.span_to_prev_source(sp).ok()?;
727        for ws in &[" ", "\t", "\n"] {
728            let pat = pat.to_owned() + ws;
729            if let Some(pat_pos) = prev_source.rfind(&pat) {
730                let just_after_pat_pos = pat_pos + pat.len() - 1;
731                let just_after_pat_plus_ws = if include_whitespace {
732                    just_after_pat_pos
733                        + prev_source[just_after_pat_pos..]
734                            .find(|c: char| !c.is_whitespace())
735                            .unwrap_or(0)
736                } else {
737                    just_after_pat_pos
738                };
739                let len = prev_source.len() - just_after_pat_plus_ws;
740                let prev_source = &prev_source[just_after_pat_plus_ws..];
741                if accept_newlines || !prev_source.trim_start().contains('\n') {
742                    return Some(sp.with_lo(BytePos(sp.lo().0 - len as u32)));
743                }
744            }
745        }
746
747        None
748    }
749
750    /// Returns the source snippet as `String` after the given `Span`.
751    pub fn span_to_next_source(&self, sp: Span) -> Result<String, SpanSnippetError> {
752        self.span_to_source(sp, |src, _, end_index| {
753            src.get(end_index..).map(|s| s.to_string()).ok_or(SpanSnippetError::IllFormedSpan(sp))
754        })
755    }
756
757    /// Extends the given `Span` while the next character matches the predicate
758    pub fn span_extend_while(
759        &self,
760        span: Span,
761        mut f: impl FnMut(char) -> bool,
762    ) -> Result<Span, SpanSnippetError> {
763        self.span_to_source(span, |s, _start, end| {
764            let n = s[end..].char_indices().find(|&(_, c)| !f(c)).map_or(s.len() - end, |(i, _)| i);
765            Ok(span.with_hi(span.hi() + BytePos(n as u32)))
766        })
767    }
768
769    /// Extends the span to include any trailing whitespace, or returns the original
770    /// span if a `SpanSnippetError` was encountered.
771    pub fn span_extend_while_whitespace(&self, span: Span) -> Span {
772        self.span_extend_while(span, char::is_whitespace).unwrap_or(span)
773    }
774
775    /// Extends the given `Span` to previous character while the previous character matches the predicate
776    pub fn span_extend_prev_while(
777        &self,
778        span: Span,
779        f: impl Fn(char) -> bool,
780    ) -> Result<Span, SpanSnippetError> {
781        self.span_to_source(span, |s, start, _end| {
782            let n = s[..start]
783                .char_indices()
784                .rfind(|&(_, c)| !f(c))
785                .map_or(start, |(i, c)| start - i - c.len_utf8());
786            Ok(span.with_lo(span.lo() - BytePos(n as u32)))
787        })
788    }
789
790    /// Extends the given `Span` to just before the next occurrence of `c`.
791    pub fn span_extend_to_next_char(&self, sp: Span, c: char, accept_newlines: bool) -> Span {
792        if let Ok(next_source) = self.span_to_next_source(sp) {
793            let next_source = next_source.split(c).next().unwrap_or("");
794            if !next_source.is_empty() && (accept_newlines || !next_source.contains('\n')) {
795                return sp.with_hi(BytePos(sp.hi().0 + next_source.len() as u32));
796            }
797        }
798
799        sp
800    }
801
802    /// Extends the given `Span` to contain the entire line it is on.
803    pub fn span_extend_to_line(&self, sp: Span) -> Span {
804        self.span_extend_to_prev_char(self.span_extend_to_next_char(sp, '\n', true), '\n', true)
805    }
806
807    /// Given a `Span`, tries to get a shorter span ending before the first occurrence of `char`
808    /// `c`.
809    pub fn span_until_char(&self, sp: Span, c: char) -> Span {
810        match self.span_to_snippet(sp) {
811            Ok(snippet) => {
812                let snippet = snippet.split(c).next().unwrap_or("").trim_end();
813                if !snippet.is_empty() && !snippet.contains('\n') {
814                    sp.with_hi(BytePos(sp.lo().0 + snippet.len() as u32))
815                } else {
816                    sp
817                }
818            }
819            _ => sp,
820        }
821    }
822
823    /// Given a 'Span', tries to tell if it's wrapped by "<>" or "()"
824    /// the algorithm searches if the next character is '>' or ')' after skipping whitespace and comments
825    /// then searches the previous character to match '<' or '(' after skipping whitespace and comments
826    /// return true if wrapped by '<>' or '()'
827    pub fn span_wrapped_by_angle_or_parentheses(&self, span: Span) -> bool {
828        self.span_to_source(span, |src, start_index, end_index| {
829            if src.get(start_index..end_index).is_none() {
830                return Ok(false);
831            }
832            let right = tokenize(&src[end_index..], FrontmatterAllowed::No)
833                .find_map(|token| (!is_trivia(token.kind)).then_some(token.kind));
834            let left = tokenize(&src[..start_index], FrontmatterAllowed::No)
835                .map(|token| token.kind)
836                .filter(|kind| !is_trivia(*kind))
837                .last();
838
839            Ok(#[allow(non_exhaustive_omitted_patterns)] match (left, right) {
    (Some(TokenKind::Lt), Some(TokenKind::Gt)) |
        (Some(TokenKind::OpenParen), Some(TokenKind::CloseParen)) => true,
    _ => false,
}matches!(
840                (left, right),
841                (Some(TokenKind::Lt), Some(TokenKind::Gt))
842                    | (Some(TokenKind::OpenParen), Some(TokenKind::CloseParen))
843            ))
844        })
845        .is_ok_and(|is_accessible| is_accessible)
846    }
847
848    /// Given a `Span`, tries to get a shorter span ending just after the first occurrence of `char`
849    /// `c`.
850    pub fn span_through_char(&self, sp: Span, c: char) -> Span {
851        if let Ok(snippet) = self.span_to_snippet(sp)
852            && let Some(offset) = snippet.find(c)
853        {
854            return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32));
855        }
856        sp
857    }
858
859    /// Given a `Span`, gets a new `Span` covering the first token and all its trailing whitespace
860    /// or the original `Span`.
861    ///
862    /// If `sp` points to `"let mut x"`, then a span pointing at `"let "` will be returned.
863    pub fn span_until_non_whitespace(&self, sp: Span) -> Span {
864        let mut whitespace_found = false;
865
866        self.span_take_while(sp, |c| {
867            if !whitespace_found && c.is_whitespace() {
868                whitespace_found = true;
869            }
870
871            !whitespace_found || c.is_whitespace()
872        })
873    }
874
875    /// Given a `Span`, gets a new `Span` covering the first token without its trailing whitespace
876    /// or the original `Span` in case of error.
877    ///
878    /// If `sp` points to `"let mut x"`, then a span pointing at `"let"` will be returned.
879    pub fn span_until_whitespace(&self, sp: Span) -> Span {
880        self.span_take_while(sp, |c| !c.is_whitespace())
881    }
882
883    /// Given a `Span`, gets a shorter one until `predicate` yields `false`.
884    pub fn span_take_while<P>(&self, sp: Span, predicate: P) -> Span
885    where
886        P: for<'r> FnMut(&'r char) -> bool,
887    {
888        if let Ok(snippet) = self.span_to_snippet(sp) {
889            let offset = snippet.chars().take_while(predicate).map(|c| c.len_utf8()).sum::<usize>();
890
891            sp.with_hi(BytePos(sp.lo().0 + (offset as u32)))
892        } else {
893            sp
894        }
895    }
896
897    /// Given a `Span`, return a span ending in the closest `{`. This is useful when you have a
898    /// `Span` enclosing a whole item but we need to point at only the head (usually the first
899    /// line) of that item.
900    ///
901    /// *Only suitable for diagnostics.*
902    pub fn guess_head_span(&self, sp: Span) -> Span {
903        // FIXME: extend the AST items to have a head span, or replace callers with pointing at
904        // the item's ident when appropriate.
905        self.span_until_char(sp, '{')
906    }
907
908    /// Returns a new span representing just the first character of the given span.
909    pub fn start_point(&self, sp: Span) -> Span {
910        let width = {
911            let local_begin = self.lookup_byte_offset(sp.lo());
912            let start_index = local_begin.pos.to_usize();
913            let src = local_begin.sf.external_src.read();
914
915            let snippet = if let Some(ref src) = local_begin.sf.src {
916                Some(&src[start_index..])
917            } else {
918                src.get_source().map(|src| &src[start_index..])
919            };
920
921            match snippet {
922                None => 1,
923                Some(snippet) => match snippet.chars().next() {
924                    None => 1,
925                    Some(c) => c.len_utf8(),
926                },
927            }
928        };
929
930        sp.with_hi(BytePos(sp.lo().0 + width as u32))
931    }
932
933    /// Returns a new span representing just the last character of this span.
934    pub fn end_point(&self, sp: Span) -> Span {
935        let sp = sp.data();
936        let pos = sp.hi.0;
937
938        let width = self.find_width_of_character_at_span(sp, false);
939        let corrected_end_position = pos.checked_sub(width).unwrap_or(pos);
940
941        let end_point = BytePos(cmp::max(corrected_end_position, sp.lo.0));
942        sp.with_lo(end_point)
943    }
944
945    /// Returns a new span representing the next character after the end-point of this span.
946    /// Special cases:
947    /// - if span is a dummy one, returns the same span
948    /// - if next_point reached the end of source, return a span exceeding the end of source,
949    ///   which means sm.span_to_snippet(next_point) will get `Err`
950    /// - respect multi-byte characters
951    pub fn next_point(&self, sp: Span) -> Span {
952        if sp.is_dummy() {
953            return sp;
954        }
955
956        let sp = sp.data();
957        let start_of_next_point = sp.hi.0;
958        let width = self.find_width_of_character_at_span(sp, true);
959        // If the width is 1, then the next span should only contain the next char besides current ending.
960        // However, in the case of a multibyte character, where the width != 1, the next span should
961        // span multiple bytes to include the whole character.
962        let end_of_next_point =
963            start_of_next_point.checked_add(width).unwrap_or(start_of_next_point);
964
965        let end_of_next_point = BytePos(cmp::max(start_of_next_point + 1, end_of_next_point));
966        Span::new(BytePos(start_of_next_point), end_of_next_point, sp.ctxt, None)
967    }
968
969    /// Check whether span is followed by some specified target string, ignoring whitespace.
970    /// *Only suitable for diagnostics.*
971    pub fn span_followed_by(&self, span: Span, target: &str) -> Option<Span> {
972        let span = self.span_extend_while_whitespace(span);
973        self.span_to_next_source(span).ok()?.strip_prefix(target).map(|_| {
974            Span::new(span.hi(), span.hi() + BytePos(target.len() as u32), span.ctxt(), None)
975        })
976    }
977
978    /// Finds the width of the character, either before or after the end of provided span,
979    /// depending on the `forwards` parameter.
980    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("find_width_of_character_at_span",
                                    "rustc_span::source_map", ::tracing::Level::INFO,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs"),
                                    ::tracing_core::__macro_support::Option::Some(980u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_span::source_map"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("forwards")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("forwards");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::INFO <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::INFO <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&forwards
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: u32 = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if sp.lo == sp.hi && !forwards {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs:983",
                                        "rustc_span::source_map", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs"),
                                        ::tracing_core::__macro_support::Option::Some(983u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_span::source_map"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("early return empty span")
                                                            as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                return 1;
            }
            let local_begin = self.lookup_byte_offset(sp.lo);
            let local_end = self.lookup_byte_offset(sp.hi);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs:989",
                                    "rustc_span::source_map", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs"),
                                    ::tracing_core::__macro_support::Option::Some(989u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_span::source_map"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("local_begin=`{0:?}`, local_end=`{1:?}`",
                                                                local_begin, local_end) as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            if local_begin.sf.start_pos != local_end.sf.start_pos {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs:992",
                                        "rustc_span::source_map", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs"),
                                        ::tracing_core::__macro_support::Option::Some(992u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_span::source_map"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("begin and end are in different files")
                                                            as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                return 1;
            }
            let start_index = local_begin.pos.to_usize();
            let end_index = local_end.pos.to_usize();
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs:998",
                                    "rustc_span::source_map", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs"),
                                    ::tracing_core::__macro_support::Option::Some(998u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_span::source_map"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("start_index=`{0:?}`, end_index=`{1:?}`",
                                                                start_index, end_index) as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            if (!forwards && end_index == usize::MIN) ||
                    (forwards && start_index == usize::MAX) {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs:1003",
                                        "rustc_span::source_map", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs"),
                                        ::tracing_core::__macro_support::Option::Some(1003u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_span::source_map"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("start or end of span, cannot be multibyte")
                                                            as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                return 1;
            }
            let source_len = local_begin.sf.normalized_source_len.to_usize();
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs:1008",
                                    "rustc_span::source_map", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1008u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_span::source_map"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("source_len=`{0:?}`",
                                                                source_len) as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            if start_index > end_index || end_index > source_len - 1 {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs:1011",
                                        "rustc_span::source_map", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs"),
                                        ::tracing_core::__macro_support::Option::Some(1011u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_span::source_map"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("source indexes are malformed")
                                                            as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                return 1;
            }
            let src = local_begin.sf.external_src.read();
            let snippet =
                if let Some(src) = &local_begin.sf.src {
                    src
                } else if let Some(src) = src.get_source() {
                    src
                } else { return 1; };
            if forwards {
                (snippet.ceil_char_boundary(end_index + 1) - end_index) as u32
            } else {
                (end_index - snippet.floor_char_boundary(end_index - 1)) as
                    u32
            }
        }
    }
}#[instrument(skip(self, sp))]
981    fn find_width_of_character_at_span(&self, sp: SpanData, forwards: bool) -> u32 {
982        if sp.lo == sp.hi && !forwards {
983            debug!("early return empty span");
984            return 1;
985        }
986
987        let local_begin = self.lookup_byte_offset(sp.lo);
988        let local_end = self.lookup_byte_offset(sp.hi);
989        debug!("local_begin=`{:?}`, local_end=`{:?}`", local_begin, local_end);
990
991        if local_begin.sf.start_pos != local_end.sf.start_pos {
992            debug!("begin and end are in different files");
993            return 1;
994        }
995
996        let start_index = local_begin.pos.to_usize();
997        let end_index = local_end.pos.to_usize();
998        debug!("start_index=`{:?}`, end_index=`{:?}`", start_index, end_index);
999
1000        // Disregard indexes that are at the start or end of their spans, they can't fit bigger
1001        // characters.
1002        if (!forwards && end_index == usize::MIN) || (forwards && start_index == usize::MAX) {
1003            debug!("start or end of span, cannot be multibyte");
1004            return 1;
1005        }
1006
1007        let source_len = local_begin.sf.normalized_source_len.to_usize();
1008        debug!("source_len=`{:?}`", source_len);
1009        // Ensure indexes are also not malformed.
1010        if start_index > end_index || end_index > source_len - 1 {
1011            debug!("source indexes are malformed");
1012            return 1;
1013        }
1014
1015        let src = local_begin.sf.external_src.read();
1016
1017        let snippet = if let Some(src) = &local_begin.sf.src {
1018            src
1019        } else if let Some(src) = src.get_source() {
1020            src
1021        } else {
1022            return 1;
1023        };
1024
1025        if forwards {
1026            (snippet.ceil_char_boundary(end_index + 1) - end_index) as u32
1027        } else {
1028            (end_index - snippet.floor_char_boundary(end_index - 1)) as u32
1029        }
1030    }
1031
1032    pub fn get_source_file(&self, filename: &FileName) -> Option<Arc<SourceFile>> {
1033        for sf in self.files.borrow().source_files.iter() {
1034            if *filename == sf.name {
1035                return Some(Arc::clone(&sf));
1036            }
1037        }
1038        None
1039    }
1040
1041    /// For a global `BytePos`, computes the local offset within the containing `SourceFile`.
1042    pub fn lookup_byte_offset(&self, bpos: BytePos) -> SourceFileAndBytePos {
1043        let idx = self.lookup_source_file_idx(bpos);
1044        let sf = Arc::clone(&(*self.files.borrow().source_files)[idx]);
1045        let offset = bpos - sf.start_pos;
1046        SourceFileAndBytePos { sf, pos: offset }
1047    }
1048
1049    /// Returns the index of the [`SourceFile`] (in `self.files`) that contains `pos`.
1050    /// This index is guaranteed to be valid for the lifetime of this `SourceMap`,
1051    /// since `source_files` is a `MonotonicVec`
1052    pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize {
1053        self.files.borrow().source_files.partition_point(|x| x.start_pos <= pos) - 1
1054    }
1055
1056    pub fn count_lines(&self) -> usize {
1057        self.files().iter().fold(0, |a, f| a + f.count_lines())
1058    }
1059
1060    pub fn ensure_source_file_source_present(&self, source_file: &SourceFile) -> bool {
1061        source_file.add_external_src(|| {
1062            let FileName::Real(ref name) = source_file.name else {
1063                return None;
1064            };
1065
1066            let local_path: Cow<'_, Path> = match name.local_path() {
1067                Some(local) => local.into(),
1068                None => {
1069                    // The compiler produces better error messages if the sources of dependencies
1070                    // are available. Attempt to undo any path mapping so we can find remapped
1071                    // dependencies.
1072                    //
1073                    // We can only use the heuristic because `add_external_src` checks the file
1074                    // content hash.
1075                    let maybe_remapped_path = name.path(RemapPathScopeComponents::DIAGNOSTICS);
1076                    self.path_mapping
1077                        .reverse_map_prefix_heuristically(maybe_remapped_path)
1078                        .map(Cow::from)
1079                        .unwrap_or(maybe_remapped_path.into())
1080                }
1081            };
1082
1083            self.file_loader.read_file(&local_path).ok()
1084        })
1085    }
1086
1087    pub fn is_imported(&self, sp: Span) -> bool {
1088        let source_file_index = self.lookup_source_file_idx(sp.lo());
1089        let source_file = &self.files()[source_file_index];
1090        source_file.is_imported()
1091    }
1092
1093    /// Gets the span of a statement. If the statement is a macro expansion, the
1094    /// span in the context of the block span is found. The trailing semicolon is included
1095    /// on a best-effort basis.
1096    pub fn stmt_span(&self, stmt_span: Span, block_span: Span) -> Span {
1097        if !stmt_span.from_expansion() {
1098            return stmt_span;
1099        }
1100        let mac_call = original_sp(stmt_span, block_span);
1101        self.mac_call_stmt_semi_span(mac_call).map_or(mac_call, |s| mac_call.with_hi(s.hi()))
1102    }
1103
1104    /// Tries to find the span of the semicolon of a macro call statement.
1105    /// The input must be the *call site* span of a statement from macro expansion.
1106    /// ```ignore (illustrative)
1107    /// //       v output
1108    ///    mac!();
1109    /// // ^^^^^^ input
1110    /// ```
1111    pub fn mac_call_stmt_semi_span(&self, mac_call: Span) -> Option<Span> {
1112        let span = self.span_extend_while_whitespace(mac_call);
1113        let span = self.next_point(span);
1114        if self.span_to_snippet(span).as_deref() == Ok(";") { Some(span) } else { None }
1115    }
1116}
1117
1118pub fn get_source_map() -> Option<Arc<SourceMap>> {
1119    with_session_globals(|session_globals| session_globals.source_map.clone())
1120}
1121
1122#[derive(#[automatically_derived]impl ::core::clone::Clone for FilePathMapping {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        FilePathMapping {
            mapping: ::core::clone::Clone::clone(&self.mapping),
            filename_remapping_scopes: ::core::clone::Clone::clone(&self.filename_remapping_scopes),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for FilePathMapping {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "FilePathMapping mapping filename_remapping_scopes",
            &self.mapping, &&self.filename_remapping_scopes)
    }
}Debug)]
1123pub struct FilePathMapping {
1124    mapping: Vec<(PathBuf, PathBuf)>,
1125    filename_remapping_scopes: RemapPathScopeComponents,
1126}
1127
1128impl FilePathMapping {
1129    pub fn empty() -> FilePathMapping {
1130        FilePathMapping::new(Vec::new(), RemapPathScopeComponents::empty())
1131    }
1132
1133    pub fn new(
1134        mapping: Vec<(PathBuf, PathBuf)>,
1135        filename_remapping_scopes: RemapPathScopeComponents,
1136    ) -> FilePathMapping {
1137        FilePathMapping { mapping, filename_remapping_scopes }
1138    }
1139
1140    /// Applies any path prefix substitution as defined by the mapping.
1141    /// The return value is the remapped path and a boolean indicating whether
1142    /// the path was affected by the mapping.
1143    fn map_prefix<'a>(&'a self, path: impl Into<Cow<'a, Path>>) -> (Cow<'a, Path>, bool) {
1144        let path = path.into();
1145        if path.as_os_str().is_empty() {
1146            // Exit early if the path is empty and therefore there's nothing to remap.
1147            // This is mostly to reduce spam for `RUSTC_LOG=[remap_path_prefix]`.
1148            return (path, false);
1149        }
1150
1151        return remap_path_prefix(&self.mapping, path);
1152
1153        {}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::DEBUG <=
                ::tracing::level_filters::LevelFilter::current() || { false }
    {
    __tracing_attr_span =
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("remap_path_prefix",
                                "rustc_span::source_map", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs"),
                                ::tracing_core::__macro_support::Option::Some(1153u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_span::source_map"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("path")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("path");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return: (Cow<'a, Path>, bool) =
                            loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        for (from, to) in mapping.iter().rev() {
                            {
                                use ::tracing::__macro_support::Callsite as _;
                                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                    {
                                        static META: ::tracing::Metadata<'static> =
                                            {
                                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs:1162",
                                                    "rustc_span::source_map", ::tracing::Level::DEBUG,
                                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs"),
                                                    ::tracing_core::__macro_support::Option::Some(1162u32),
                                                    ::tracing_core::__macro_support::Option::Some("rustc_span::source_map"),
                                                    ::tracing_core::field::FieldSet::new(&["message"],
                                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                    ::tracing::metadata::Kind::EVENT)
                                            };
                                        ::tracing::callsite::DefaultCallsite::new(&META)
                                    };
                                let enabled =
                                    ::tracing::Level::DEBUG <=
                                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                            ::tracing::Level::DEBUG <=
                                                ::tracing::level_filters::LevelFilter::current() &&
                                        {
                                            let interest = __CALLSITE.interest();
                                            !interest.is_never() &&
                                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                    interest)
                                        };
                                if enabled {
                                    (|value_set: ::tracing::field::ValueSet|
                                                {
                                                    let meta = __CALLSITE.metadata();
                                                    ::tracing::Event::dispatch(meta, &value_set);
                                                    ;
                                                })({
                                            #[allow(unused_imports)]
                                            use ::tracing::field::{debug, display, Value};
                                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Trying to apply {0:?} => {1:?}",
                                                                                from, to) as &dyn ::tracing::field::Value))])
                                        });
                                } else { ; }
                            };
                            if let Ok(rest) = path.strip_prefix(from) {
                                let remapped =
                                    if rest.as_os_str().is_empty() {
                                        to.into()
                                    } else { to.join(rest).into() };
                                {
                                    use ::tracing::__macro_support::Callsite as _;
                                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                        {
                                            static META: ::tracing::Metadata<'static> =
                                                {
                                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs:1176",
                                                        "rustc_span::source_map", ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(1176u32),
                                                        ::tracing_core::__macro_support::Option::Some("rustc_span::source_map"),
                                                        ::tracing_core::field::FieldSet::new(&["message"],
                                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                        ::tracing::metadata::Kind::EVENT)
                                                };
                                            ::tracing::callsite::DefaultCallsite::new(&META)
                                        };
                                    let enabled =
                                        ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::LevelFilter::current() &&
                                            {
                                                let interest = __CALLSITE.interest();
                                                !interest.is_never() &&
                                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                        interest)
                                            };
                                    if enabled {
                                        (|value_set: ::tracing::field::ValueSet|
                                                    {
                                                        let meta = __CALLSITE.metadata();
                                                        ::tracing::Event::dispatch(meta, &value_set);
                                                        ;
                                                    })({
                                                #[allow(unused_imports)]
                                                use ::tracing::field::{debug, display, Value};
                                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Match - remapped")
                                                                            as &dyn ::tracing::field::Value))])
                                            });
                                    } else { ; }
                                };
                                return (remapped, true);
                            } else {
                                {
                                    use ::tracing::__macro_support::Callsite as _;
                                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                        {
                                            static META: ::tracing::Metadata<'static> =
                                                {
                                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs:1180",
                                                        "rustc_span::source_map", ::tracing::Level::DEBUG,
                                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs"),
                                                        ::tracing_core::__macro_support::Option::Some(1180u32),
                                                        ::tracing_core::__macro_support::Option::Some("rustc_span::source_map"),
                                                        ::tracing_core::field::FieldSet::new(&["message"],
                                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                        ::tracing::metadata::Kind::EVENT)
                                                };
                                            ::tracing::callsite::DefaultCallsite::new(&META)
                                        };
                                    let enabled =
                                        ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                ::tracing::Level::DEBUG <=
                                                    ::tracing::level_filters::LevelFilter::current() &&
                                            {
                                                let interest = __CALLSITE.interest();
                                                !interest.is_never() &&
                                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                        interest)
                                            };
                                    if enabled {
                                        (|value_set: ::tracing::field::ValueSet|
                                                    {
                                                        let meta = __CALLSITE.metadata();
                                                        ::tracing::Event::dispatch(meta, &value_set);
                                                        ;
                                                    })({
                                                #[allow(unused_imports)]
                                                use ::tracing::field::{debug, display, Value};
                                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("No match - prefix {0:?} does not match",
                                                                                    from) as &dyn ::tracing::field::Value))])
                                            });
                                    } else { ; }
                                };
                            }
                        }
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs:1184",
                                                "rustc_span::source_map", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs"),
                                                ::tracing_core::__macro_support::Option::Some(1184u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_span::source_map"),
                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("not remapped")
                                                                    as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        (path, false)
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs:1153",
                        "rustc_span::source_map", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs"),
                        ::tracing_core::__macro_support::Option::Some(1153u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_span::source_map"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(mapping), ret)]
1154        fn remap_path_prefix<'a>(
1155            mapping: &'a [(PathBuf, PathBuf)],
1156            path: Cow<'a, Path>,
1157        ) -> (Cow<'a, Path>, bool) {
1158            // NOTE: We are iterating over the mapping entries from last to first
1159            //       because entries specified later on the command line should
1160            //       take precedence.
1161            for (from, to) in mapping.iter().rev() {
1162                debug!("Trying to apply {from:?} => {to:?}");
1163
1164                if let Ok(rest) = path.strip_prefix(from) {
1165                    let remapped = if rest.as_os_str().is_empty() {
1166                        // This is subtle, joining an empty path onto e.g. `foo/bar` will
1167                        // result in `foo/bar/`, that is, there'll be an additional directory
1168                        // separator at the end. This can lead to duplicated directory separators
1169                        // in remapped paths down the line.
1170                        // So, if we have an exact match, we just return that without a call
1171                        // to `Path::join()`.
1172                        to.into()
1173                    } else {
1174                        to.join(rest).into()
1175                    };
1176                    debug!("Match - remapped");
1177
1178                    return (remapped, true);
1179                } else {
1180                    debug!("No match - prefix {from:?} does not match");
1181                }
1182            }
1183
1184            debug!("not remapped");
1185            (path, false)
1186        }
1187    }
1188
1189    /// Applies any path prefix substitution as defined by the mapping.
1190    ///
1191    /// The returned filename contains the a remapped path representing the remapped
1192    /// part if any remapping was performed.
1193    pub fn to_real_filename<'a>(
1194        &self,
1195        working_directory: &RealFileName,
1196        local_path: impl Into<Cow<'a, Path>>,
1197    ) -> RealFileName {
1198        let local_path = local_path.into();
1199
1200        let (remapped_path, mut was_remapped) = self.map_prefix(&*local_path);
1201        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs:1201",
                        "rustc_span::source_map", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs"),
                        ::tracing_core::__macro_support::Option::Some(1201u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_span::source_map"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("local_path")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("local_path");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("remapped_path")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("remapped_path");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("was_remapped")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("was_remapped");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("self.filename_remapping_scopes")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("self.filename_remapping_scopes");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&local_path)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&remapped_path)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&was_remapped)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.filename_remapping_scopes)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?local_path, ?remapped_path, ?was_remapped, ?self.filename_remapping_scopes);
1202
1203        // Always populate the local part, even if we just remapped it and the scopes are
1204        // total, so that places that load the file from disk still have access to it.
1205        let local = InnerRealFileName {
1206            name: local_path.to_path_buf(),
1207            working_directory: working_directory
1208                .local_path()
1209                .expect("working directory should be local")
1210                .to_path_buf(),
1211            embeddable_name: if local_path.is_absolute() {
1212                local_path.to_path_buf()
1213            } else {
1214                working_directory
1215                    .local_path()
1216                    .expect("working directory should be local")
1217                    .to_path_buf()
1218                    .join(&local_path)
1219            },
1220        };
1221
1222        RealFileName {
1223            maybe_remapped: InnerRealFileName {
1224                working_directory: working_directory.maybe_remapped.name.clone(),
1225                embeddable_name: if remapped_path.is_absolute() || was_remapped {
1226                    // The current directory may have been remapped so we take that
1227                    // into account, otherwise we'll forget to include the scopes
1228                    was_remapped = was_remapped || working_directory.was_remapped();
1229
1230                    remapped_path.to_path_buf()
1231                } else {
1232                    // Create an absolute path and remap it as well.
1233                    let (abs_path, abs_was_remapped) = self.map_prefix(
1234                        working_directory.maybe_remapped.name.clone().join(&remapped_path),
1235                    );
1236
1237                    // If either the embeddable name or the working directory was
1238                    // remapped, then the filename was remapped
1239                    was_remapped = abs_was_remapped || working_directory.was_remapped();
1240
1241                    abs_path.to_path_buf()
1242                },
1243                name: remapped_path.to_path_buf(),
1244            },
1245            local: Some(local),
1246            scopes: if was_remapped {
1247                self.filename_remapping_scopes
1248            } else {
1249                RemapPathScopeComponents::empty()
1250            },
1251        }
1252    }
1253
1254    /// Attempts to (heuristically) reverse a prefix mapping.
1255    ///
1256    /// Returns [`Some`] if there is exactly one mapping where the "to" part is
1257    /// a prefix of `path` and has at least one non-empty
1258    /// [`Normal`](path::Component::Normal) component. The component
1259    /// restriction exists to avoid reverse mapping overly generic paths like
1260    /// `/` or `.`).
1261    ///
1262    /// This is a heuristic and not guaranteed to return the actual original
1263    /// path! Do not rely on the result unless you have other means to verify
1264    /// that the mapping is correct (e.g. by checking the file content hash).
1265    {}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
            ::tracing::Level::DEBUG <=
                ::tracing::level_filters::LevelFilter::current() || { false }
    {
    __tracing_attr_span =
        {
            use ::tracing::__macro_support::Callsite as _;
            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                {
                    static META: ::tracing::Metadata<'static> =
                        {
                            ::tracing_core::metadata::Metadata::new("reverse_map_prefix_heuristically",
                                "rustc_span::source_map", ::tracing::Level::DEBUG,
                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs"),
                                ::tracing_core::__macro_support::Option::Some(1265u32),
                                ::tracing_core::__macro_support::Option::Some("rustc_span::source_map"),
                                ::tracing_core::field::FieldSet::new(&[{
                                                    const NAME:
                                                        ::tracing::__macro_support::FieldName<{
                                                            ::tracing::__macro_support::FieldName::len("path")
                                                        }> =
                                                        ::tracing::__macro_support::FieldName::new("path");
                                                    NAME.as_str()
                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                ::tracing::metadata::Kind::SPAN)
                        };
                    ::tracing::callsite::DefaultCallsite::new(&META)
                };
            let mut interest = ::tracing::subscriber::Interest::never();
            if ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        { interest = __CALLSITE.interest(); !interest.is_never() }
                    &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest) {
                let meta = __CALLSITE.metadata();
                ::tracing::Span::new(meta,
                    &{
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                        as &dyn ::tracing::field::Value))])
                        })
            } else {
                let span =
                    ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                {};
                span
            }
        };
    __tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
    (move ||
                {

                    #[allow(unknown_lints, unreachable_code, clippy ::
                    diverging_sub_expression, clippy :: empty_loop, clippy ::
                    let_unit_value, clippy :: let_with_type_underscore, clippy
                    :: needless_return, clippy :: unreachable)]
                    if false {
                        let __tracing_attr_fake_return: Option<PathBuf> = loop {};
                        return __tracing_attr_fake_return;
                    }
                    {
                        let mut found = None;
                        for (from, to) in self.mapping.iter() {
                            let has_normal_component =
                                to.components().any(|c|
                                        match c {
                                            path::Component::Normal(s) => !s.is_empty(),
                                            _ => false,
                                        });
                            if !has_normal_component { continue; }
                            let Ok(rest) = path.strip_prefix(to) else { continue; };
                            if found.is_some() { return None; }
                            found = Some(from.join(rest));
                        }
                        found
                    }
                })();
{
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs:1265",
                        "rustc_span::source_map", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/20fe935d50367c0ff8872c2ebfa050c5c99d9201/compiler/rustc_span/src/source_map.rs"),
                        ::tracing_core::__macro_support::Option::Some(1265u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_span::source_map"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("return")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("return");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};
x;#[instrument(level = "debug", skip(self), ret)]
1266    fn reverse_map_prefix_heuristically(&self, path: &Path) -> Option<PathBuf> {
1267        let mut found = None;
1268
1269        for (from, to) in self.mapping.iter() {
1270            let has_normal_component = to.components().any(|c| match c {
1271                path::Component::Normal(s) => !s.is_empty(),
1272                _ => false,
1273            });
1274
1275            if !has_normal_component {
1276                continue;
1277            }
1278
1279            let Ok(rest) = path.strip_prefix(to) else {
1280                continue;
1281            };
1282
1283            if found.is_some() {
1284                return None;
1285            }
1286
1287            found = Some(from.join(rest));
1288        }
1289
1290        found
1291    }
1292}
1293
1294fn is_trivia(kind: TokenKind) -> bool {
1295    #[allow(non_exhaustive_omitted_patterns)] match kind {
    TokenKind::Whitespace | TokenKind::LineComment { doc_style: None, .. } |
        TokenKind::BlockComment { doc_style: None, .. } => true,
    _ => false,
}matches!(
1296        kind,
1297        TokenKind::Whitespace
1298            | TokenKind::LineComment { doc_style: None, .. }
1299            | TokenKind::BlockComment { doc_style: None, .. }
1300    )
1301}