rustc_span/
lib.rs

1//! Source positions and related helper functions.
2//!
3//! Important concepts in this module include:
4//!
5//! - the *span*, represented by [`SpanData`] and related types;
6//! - source code as represented by a [`SourceMap`]; and
7//! - interned strings, represented by [`Symbol`]s, with some common symbols available statically
8//!   in the [`sym`] module.
9//!
10//! Unlike most compilers, the span contains not only the position in the source code, but also
11//! various other metadata, such as the edition and macro hygiene. This metadata is stored in
12//! [`SyntaxContext`] and [`ExpnData`].
13//!
14//! ## Note
15//!
16//! This API is completely unstable and subject to change.
17
18// tidy-alphabetical-start
19#![allow(internal_features)]
20#![cfg_attr(bootstrap, feature(array_windows))]
21#![cfg_attr(target_arch = "loongarch64", feature(stdarch_loongarch))]
22#![feature(cfg_select)]
23#![feature(core_io_borrowed_buf)]
24#![feature(if_let_guard)]
25#![feature(map_try_insert)]
26#![feature(negative_impls)]
27#![feature(read_buf)]
28#![feature(rustc_attrs)]
29// tidy-alphabetical-end
30
31// The code produced by the `Encodable`/`Decodable` derive macros refer to
32// `rustc_span::Span{Encoder,Decoder}`. That's fine outside this crate, but doesn't work inside
33// this crate without this line making `rustc_span` available.
34extern crate self as rustc_span;
35
36use derive_where::derive_where;
37use rustc_data_structures::{AtomicRef, outline};
38use rustc_macros::{Decodable, Encodable, HashStable_Generic};
39use rustc_serialize::opaque::{FileEncoder, MemDecoder};
40use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
41use tracing::debug;
42pub use unicode_width::UNICODE_VERSION;
43
44mod caching_source_map_view;
45pub mod source_map;
46use source_map::{SourceMap, SourceMapInputs};
47
48pub use self::caching_source_map_view::CachingSourceMapView;
49use crate::fatal_error::FatalError;
50
51pub mod edition;
52use edition::Edition;
53pub mod hygiene;
54use hygiene::Transparency;
55pub use hygiene::{
56    DesugaringKind, ExpnData, ExpnHash, ExpnId, ExpnKind, LocalExpnId, MacroKind, SyntaxContext,
57};
58use rustc_data_structures::stable_hasher::HashingControls;
59pub mod def_id;
60use def_id::{CrateNum, DefId, DefIndex, DefPathHash, LOCAL_CRATE, LocalDefId, StableCrateId};
61pub mod edit_distance;
62mod span_encoding;
63pub use span_encoding::{DUMMY_SP, Span};
64
65pub mod symbol;
66pub use symbol::{
67    ByteSymbol, Ident, MacroRulesNormalizedIdent, Macros20NormalizedIdent, STDLIB_STABLE_CRATES,
68    Symbol, kw, sym,
69};
70
71mod analyze_source_file;
72pub mod fatal_error;
73
74pub mod profiling;
75
76use std::borrow::Cow;
77use std::cmp::{self, Ordering};
78use std::fmt::Display;
79use std::hash::Hash;
80use std::io::{self, Read};
81use std::ops::{Add, Range, Sub};
82use std::path::{Path, PathBuf};
83use std::str::FromStr;
84use std::sync::Arc;
85use std::{fmt, iter};
86
87use md5::{Digest, Md5};
88use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
89use rustc_data_structures::sync::{FreezeLock, FreezeWriteGuard, Lock};
90use rustc_data_structures::unord::UnordMap;
91use rustc_hashes::{Hash64, Hash128};
92use sha1::Sha1;
93use sha2::Sha256;
94
95#[cfg(test)]
96mod tests;
97
98/// Per-session global variables: this struct is stored in thread-local storage
99/// in such a way that it is accessible without any kind of handle to all
100/// threads within the compilation session, but is not accessible outside the
101/// session.
102pub struct SessionGlobals {
103    symbol_interner: symbol::Interner,
104    span_interner: Lock<span_encoding::SpanInterner>,
105    /// Maps a macro argument token into use of the corresponding metavariable in the macro body.
106    /// Collisions are possible and processed in `maybe_use_metavar_location` on best effort basis.
107    metavar_spans: MetavarSpansMap,
108    hygiene_data: Lock<hygiene::HygieneData>,
109
110    /// The session's source map, if there is one. This field should only be
111    /// used in places where the `Session` is truly not available, such as
112    /// `<Span as Debug>::fmt`.
113    source_map: Option<Arc<SourceMap>>,
114}
115
116impl SessionGlobals {
117    pub fn new(
118        edition: Edition,
119        extra_symbols: &[&'static str],
120        sm_inputs: Option<SourceMapInputs>,
121    ) -> SessionGlobals {
122        SessionGlobals {
123            symbol_interner: symbol::Interner::with_extra_symbols(extra_symbols),
124            span_interner: Lock::new(span_encoding::SpanInterner::default()),
125            metavar_spans: Default::default(),
126            hygiene_data: Lock::new(hygiene::HygieneData::new(edition)),
127            source_map: sm_inputs.map(|inputs| Arc::new(SourceMap::with_inputs(inputs))),
128        }
129    }
130}
131
132pub fn create_session_globals_then<R>(
133    edition: Edition,
134    extra_symbols: &[&'static str],
135    sm_inputs: Option<SourceMapInputs>,
136    f: impl FnOnce() -> R,
137) -> R {
138    assert!(
139        !SESSION_GLOBALS.is_set(),
140        "SESSION_GLOBALS should never be overwritten! \
141         Use another thread if you need another SessionGlobals"
142    );
143    let session_globals = SessionGlobals::new(edition, extra_symbols, sm_inputs);
144    SESSION_GLOBALS.set(&session_globals, f)
145}
146
147pub fn set_session_globals_then<R>(session_globals: &SessionGlobals, f: impl FnOnce() -> R) -> R {
148    assert!(
149        !SESSION_GLOBALS.is_set(),
150        "SESSION_GLOBALS should never be overwritten! \
151         Use another thread if you need another SessionGlobals"
152    );
153    SESSION_GLOBALS.set(session_globals, f)
154}
155
156/// No source map.
157pub fn create_session_if_not_set_then<R, F>(edition: Edition, f: F) -> R
158where
159    F: FnOnce(&SessionGlobals) -> R,
160{
161    if !SESSION_GLOBALS.is_set() {
162        let session_globals = SessionGlobals::new(edition, &[], None);
163        SESSION_GLOBALS.set(&session_globals, || SESSION_GLOBALS.with(f))
164    } else {
165        SESSION_GLOBALS.with(f)
166    }
167}
168
169#[inline]
170pub fn with_session_globals<R, F>(f: F) -> R
171where
172    F: FnOnce(&SessionGlobals) -> R,
173{
174    SESSION_GLOBALS.with(f)
175}
176
177/// Default edition, no source map.
178pub fn create_default_session_globals_then<R>(f: impl FnOnce() -> R) -> R {
179    create_session_globals_then(edition::DEFAULT_EDITION, &[], None, f)
180}
181
182// If this ever becomes non thread-local, `decode_syntax_context`
183// and `decode_expn_id` will need to be updated to handle concurrent
184// deserialization.
185scoped_tls::scoped_thread_local!(static SESSION_GLOBALS: SessionGlobals);
186
187#[derive(Default)]
188pub struct MetavarSpansMap(FreezeLock<UnordMap<Span, (Span, bool)>>);
189
190impl MetavarSpansMap {
191    pub fn insert(&self, span: Span, var_span: Span) -> bool {
192        match self.0.write().try_insert(span, (var_span, false)) {
193            Ok(_) => true,
194            Err(entry) => entry.entry.get().0 == var_span,
195        }
196    }
197
198    /// Read a span and record that it was read.
199    pub fn get(&self, span: Span) -> Option<Span> {
200        if let Some(mut mspans) = self.0.try_write() {
201            if let Some((var_span, read)) = mspans.get_mut(&span) {
202                *read = true;
203                Some(*var_span)
204            } else {
205                None
206            }
207        } else {
208            if let Some((span, true)) = self.0.read().get(&span) { Some(*span) } else { None }
209        }
210    }
211
212    /// Freeze the set, and return the spans which have been read.
213    ///
214    /// After this is frozen, no spans that have not been read can be read.
215    pub fn freeze_and_get_read_spans(&self) -> UnordMap<Span, Span> {
216        self.0.freeze().items().filter(|(_, (_, b))| *b).map(|(s1, (s2, _))| (*s1, *s2)).collect()
217    }
218}
219
220#[inline]
221pub fn with_metavar_spans<R>(f: impl FnOnce(&MetavarSpansMap) -> R) -> R {
222    with_session_globals(|session_globals| f(&session_globals.metavar_spans))
223}
224
225bitflags::bitflags! {
226    /// Scopes used to determined if it need to apply to `--remap-path-prefix`
227    #[derive(Debug, Eq, PartialEq, Clone, Copy, Ord, PartialOrd, Hash)]
228    pub struct RemapPathScopeComponents: u8 {
229        /// Apply remappings to the expansion of `std::file!()` macro
230        const MACRO = 1 << 0;
231        /// Apply remappings to printed compiler diagnostics
232        const DIAGNOSTICS = 1 << 1;
233        /// Apply remappings to debug information
234        const DEBUGINFO = 1 << 3;
235        /// Apply remappings to coverage information
236        const COVERAGE = 1 << 4;
237
238        /// An alias for `macro`, `debuginfo` and `coverage`. This ensures all paths in compiled
239        /// executables, libraries and objects are remapped but not elsewhere.
240        const OBJECT = Self::MACRO.bits() | Self::DEBUGINFO.bits() | Self::COVERAGE.bits();
241    }
242}
243
244impl<E: Encoder> Encodable<E> for RemapPathScopeComponents {
245    #[inline]
246    fn encode(&self, s: &mut E) {
247        s.emit_u8(self.bits());
248    }
249}
250
251impl<D: Decoder> Decodable<D> for RemapPathScopeComponents {
252    #[inline]
253    fn decode(s: &mut D) -> RemapPathScopeComponents {
254        RemapPathScopeComponents::from_bits(s.read_u8())
255            .expect("invalid bits for RemapPathScopeComponents")
256    }
257}
258
259/// A self-contained "real" filename.
260///
261/// It is produced by `SourceMap::to_real_filename`.
262///
263/// `RealFileName` represents a filename that may have been (partly) remapped
264/// by `--remap-path-prefix` and `-Zremap-path-scope`.
265///
266/// It also contains an embedabble component which gives a working directory
267/// and a maybe-remapped maybe-aboslote name. This is useful for debuginfo where
268/// some formats and tools highly prefer absolute paths.
269///
270/// ## Consistency across compiler sessions
271///
272/// The type-system, const-eval and other parts of the compiler rely on `FileName`
273/// and by extension `RealFileName` to be consistent across compiler sessions.
274///
275/// Otherwise unsoudness (like rust-lang/rust#148328) may occur.
276///
277/// As such this type is self-sufficient and consistent in it's output.
278///
279/// The [`RealFileName::path`] and [`RealFileName::embeddable_name`] methods
280/// are guaranteed to always return the same output across compiler sessions.
281///
282/// ## Usage
283///
284/// Creation of a [`RealFileName`] should be done using
285/// [`FilePathMapping::to_real_filename`][rustc_span::source_map::FilePathMapping::to_real_filename].
286///
287/// Retrieving a path can be done in two main ways:
288///  - by using [`RealFileName::path`] with a given scope (should be preferred)
289///  - or by using [`RealFileName::embeddable_name`] with a given scope
290#[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Decodable, Encodable)]
291pub struct RealFileName {
292    /// The local name (always present in the original crate)
293    local: Option<InnerRealFileName>,
294    /// The maybe remapped part. Correspond to `local` when no remapped happened.
295    maybe_remapped: InnerRealFileName,
296    /// The remapped scopes. Any active scope MUST use `maybe_virtual`
297    scopes: RemapPathScopeComponents,
298}
299
300/// The inner workings of `RealFileName`.
301///
302/// It contains the `name`, `working_directory` and `embeddable_name` components.
303#[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Decodable, Encodable, Hash)]
304struct InnerRealFileName {
305    /// The name.
306    name: PathBuf,
307    /// The working directory associated with the embeddable name.
308    working_directory: PathBuf,
309    /// The embeddable name.
310    embeddable_name: PathBuf,
311}
312
313impl Hash for RealFileName {
314    #[inline]
315    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
316        // To prevent #70924 from happening again we should only hash the
317        // remapped path if that exists. This is because remapped paths to
318        // sysroot crates (/rust/$hash or /rust/$version) remain stable even
319        // if the corresponding local path changes.
320        if !self.was_fully_remapped() {
321            self.local.hash(state);
322        }
323        self.maybe_remapped.hash(state);
324        self.scopes.bits().hash(state);
325    }
326}
327
328impl RealFileName {
329    /// Returns the associated path for the given remapping scope.
330    ///
331    /// ## Panic
332    ///
333    /// Only one scope components can be given to this function.
334    #[inline]
335    pub fn path(&self, scope: RemapPathScopeComponents) -> &Path {
336        assert!(
337            scope.bits().count_ones() == 1,
338            "one and only one scope should be passed to `RealFileName::path`: {scope:?}"
339        );
340        if !self.scopes.contains(scope)
341            && let Some(local_name) = &self.local
342        {
343            local_name.name.as_path()
344        } else {
345            self.maybe_remapped.name.as_path()
346        }
347    }
348
349    /// Returns the working directory and embeddable path for the given remapping scope.
350    ///
351    /// Useful for embedding a mostly abosolute path (modulo remapping) in the compiler outputs.
352    ///
353    /// The embedabble path is not guaranteed to be an absolute path, nor is it garuenteed
354    /// that the working directory part is always a prefix of embeddable path.
355    ///
356    /// ## Panic
357    ///
358    /// Only one scope components can be given to this function.
359    #[inline]
360    pub fn embeddable_name(&self, scope: RemapPathScopeComponents) -> (&Path, &Path) {
361        assert!(
362            scope.bits().count_ones() == 1,
363            "one and only one scope should be passed to `RealFileName::embeddable_path`: {scope:?}"
364        );
365        if !self.scopes.contains(scope)
366            && let Some(local_name) = &self.local
367        {
368            (&local_name.working_directory, &local_name.embeddable_name)
369        } else {
370            (&self.maybe_remapped.working_directory, &self.maybe_remapped.embeddable_name)
371        }
372    }
373
374    /// Returns the path suitable for reading from the file system on the local host,
375    /// if this information exists.
376    ///
377    /// May not exists if the filename was imported from another crate.
378    ///
379    /// Avoid embedding this in build artifacts; prefer `path()` or `embeddable_name()`.
380    #[inline]
381    pub fn local_path(&self) -> Option<&Path> {
382        if self.was_not_remapped() {
383            Some(&self.maybe_remapped.name)
384        } else if let Some(local) = &self.local {
385            Some(&local.name)
386        } else {
387            None
388        }
389    }
390
391    /// Returns the path suitable for reading from the file system on the local host,
392    /// if this information exists.
393    ///
394    /// May not exists if the filename was imported from another crate.
395    ///
396    /// Avoid embedding this in build artifacts; prefer `path()` or `embeddable_name()`.
397    #[inline]
398    pub fn into_local_path(self) -> Option<PathBuf> {
399        if self.was_not_remapped() {
400            Some(self.maybe_remapped.name)
401        } else if let Some(local) = self.local {
402            Some(local.name)
403        } else {
404            None
405        }
406    }
407
408    /// Returns whenever the filename was remapped.
409    #[inline]
410    pub(crate) fn was_remapped(&self) -> bool {
411        !self.scopes.is_empty()
412    }
413
414    /// Returns whenever the filename was fully remapped.
415    #[inline]
416    fn was_fully_remapped(&self) -> bool {
417        self.scopes.is_all()
418    }
419
420    /// Returns whenever the filename was not remapped.
421    #[inline]
422    fn was_not_remapped(&self) -> bool {
423        self.scopes.is_empty()
424    }
425
426    /// Returns an empty `RealFileName`
427    ///
428    /// Useful as the working directory input to `SourceMap::to_real_filename`.
429    #[inline]
430    pub fn empty() -> RealFileName {
431        RealFileName {
432            local: Some(InnerRealFileName {
433                name: PathBuf::new(),
434                working_directory: PathBuf::new(),
435                embeddable_name: PathBuf::new(),
436            }),
437            maybe_remapped: InnerRealFileName {
438                name: PathBuf::new(),
439                working_directory: PathBuf::new(),
440                embeddable_name: PathBuf::new(),
441            },
442            scopes: RemapPathScopeComponents::empty(),
443        }
444    }
445
446    /// Returns a `RealFileName` that is completely remapped without any local components.
447    ///
448    /// Only exposed for the purpose of `-Zsimulate-remapped-rust-src-base`.
449    pub fn from_virtual_path(path: &Path) -> RealFileName {
450        let name = InnerRealFileName {
451            name: path.to_owned(),
452            embeddable_name: path.to_owned(),
453            working_directory: PathBuf::new(),
454        };
455        RealFileName { local: None, maybe_remapped: name, scopes: RemapPathScopeComponents::all() }
456    }
457
458    /// Update the filename for encoding in the crate metadata.
459    ///
460    /// Currently it's about removing the local part when the filename
461    /// is either fully remapped or not remapped at all.
462    #[inline]
463    pub fn update_for_crate_metadata(&mut self) {
464        if self.was_fully_remapped() || self.was_not_remapped() {
465            // NOTE: This works because when the filename is fully
466            // remapped, we don't care about the `local` part,
467            // and when the filename is not remapped at all,
468            // `maybe_remapped` and `local` are equal.
469            self.local = None;
470        }
471    }
472
473    /// Internal routine to display the filename.
474    ///
475    /// Users should always use the `RealFileName::path` method or `FileName` methods instead.
476    fn to_string_lossy<'a>(&'a self, display_pref: FileNameDisplayPreference) -> Cow<'a, str> {
477        match display_pref {
478            FileNameDisplayPreference::Remapped => self.maybe_remapped.name.to_string_lossy(),
479            FileNameDisplayPreference::Local => {
480                self.local.as_ref().unwrap_or(&self.maybe_remapped).name.to_string_lossy()
481            }
482            FileNameDisplayPreference::Short => self
483                .maybe_remapped
484                .name
485                .file_name()
486                .map_or_else(|| "".into(), |f| f.to_string_lossy()),
487            FileNameDisplayPreference::Scope(scope) => self.path(scope).to_string_lossy(),
488        }
489    }
490}
491
492/// Differentiates between real files and common virtual files.
493#[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash, Decodable, Encodable)]
494pub enum FileName {
495    Real(RealFileName),
496    /// Strings provided as `--cfg [cfgspec]`.
497    CfgSpec(Hash64),
498    /// Command line.
499    Anon(Hash64),
500    /// Hack in `src/librustc_ast/parse.rs`.
501    // FIXME(jseyfried)
502    MacroExpansion(Hash64),
503    ProcMacroSourceCode(Hash64),
504    /// Strings provided as crate attributes in the CLI.
505    CliCrateAttr(Hash64),
506    /// Custom sources for explicit parser calls from plugins and drivers.
507    Custom(String),
508    DocTest(PathBuf, isize),
509    /// Post-substitution inline assembly from LLVM.
510    InlineAsm(Hash64),
511}
512
513pub struct FileNameDisplay<'a> {
514    inner: &'a FileName,
515    display_pref: FileNameDisplayPreference,
516}
517
518// Internal enum. Should not be exposed.
519#[derive(Clone, Copy)]
520enum FileNameDisplayPreference {
521    Remapped,
522    Local,
523    Short,
524    Scope(RemapPathScopeComponents),
525}
526
527impl fmt::Display for FileNameDisplay<'_> {
528    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
529        use FileName::*;
530        match *self.inner {
531            Real(ref name) => {
532                write!(fmt, "{}", name.to_string_lossy(self.display_pref))
533            }
534            CfgSpec(_) => write!(fmt, "<cfgspec>"),
535            MacroExpansion(_) => write!(fmt, "<macro expansion>"),
536            Anon(_) => write!(fmt, "<anon>"),
537            ProcMacroSourceCode(_) => write!(fmt, "<proc-macro source code>"),
538            CliCrateAttr(_) => write!(fmt, "<crate attribute>"),
539            Custom(ref s) => write!(fmt, "<{s}>"),
540            DocTest(ref path, _) => write!(fmt, "{}", path.display()),
541            InlineAsm(_) => write!(fmt, "<inline asm>"),
542        }
543    }
544}
545
546impl<'a> FileNameDisplay<'a> {
547    pub fn to_string_lossy(&self) -> Cow<'a, str> {
548        match self.inner {
549            FileName::Real(inner) => inner.to_string_lossy(self.display_pref),
550            _ => Cow::from(self.to_string()),
551        }
552    }
553}
554
555impl FileName {
556    pub fn is_real(&self) -> bool {
557        use FileName::*;
558        match *self {
559            Real(_) => true,
560            Anon(_)
561            | MacroExpansion(_)
562            | ProcMacroSourceCode(_)
563            | CliCrateAttr(_)
564            | Custom(_)
565            | CfgSpec(_)
566            | DocTest(_, _)
567            | InlineAsm(_) => false,
568        }
569    }
570
571    /// Returns the path suitable for reading from the file system on the local host,
572    /// if this information exists.
573    ///
574    /// Avoid embedding this in build artifacts. Prefer using the `display` method.
575    #[inline]
576    pub fn prefer_remapped_unconditionally(&self) -> FileNameDisplay<'_> {
577        FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Remapped }
578    }
579
580    /// Returns the path suitable for reading from the file system on the local host,
581    /// if this information exists.
582    ///
583    /// Avoid embedding this in build artifacts. Prefer using the `display` method.
584    #[inline]
585    pub fn prefer_local_unconditionally(&self) -> FileNameDisplay<'_> {
586        FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Local }
587    }
588
589    /// Returns a short (either the filename or an empty string).
590    #[inline]
591    pub fn short(&self) -> FileNameDisplay<'_> {
592        FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Short }
593    }
594
595    /// Returns a `Display`-able path for the given scope.
596    #[inline]
597    pub fn display(&self, scope: RemapPathScopeComponents) -> FileNameDisplay<'_> {
598        FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Scope(scope) }
599    }
600
601    pub fn macro_expansion_source_code(src: &str) -> FileName {
602        let mut hasher = StableHasher::new();
603        src.hash(&mut hasher);
604        FileName::MacroExpansion(hasher.finish())
605    }
606
607    pub fn anon_source_code(src: &str) -> FileName {
608        let mut hasher = StableHasher::new();
609        src.hash(&mut hasher);
610        FileName::Anon(hasher.finish())
611    }
612
613    pub fn proc_macro_source_code(src: &str) -> FileName {
614        let mut hasher = StableHasher::new();
615        src.hash(&mut hasher);
616        FileName::ProcMacroSourceCode(hasher.finish())
617    }
618
619    pub fn cfg_spec_source_code(src: &str) -> FileName {
620        let mut hasher = StableHasher::new();
621        src.hash(&mut hasher);
622        FileName::CfgSpec(hasher.finish())
623    }
624
625    pub fn cli_crate_attr_source_code(src: &str) -> FileName {
626        let mut hasher = StableHasher::new();
627        src.hash(&mut hasher);
628        FileName::CliCrateAttr(hasher.finish())
629    }
630
631    pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName {
632        FileName::DocTest(path, line)
633    }
634
635    pub fn inline_asm_source_code(src: &str) -> FileName {
636        let mut hasher = StableHasher::new();
637        src.hash(&mut hasher);
638        FileName::InlineAsm(hasher.finish())
639    }
640
641    /// Returns the path suitable for reading from the file system on the local host,
642    /// if this information exists.
643    ///
644    /// Avoid embedding this in build artifacts.
645    pub fn into_local_path(self) -> Option<PathBuf> {
646        match self {
647            FileName::Real(path) => path.into_local_path(),
648            FileName::DocTest(path, _) => Some(path),
649            _ => None,
650        }
651    }
652}
653
654/// Represents a span.
655///
656/// Spans represent a region of code, used for error reporting. Positions in spans
657/// are *absolute* positions from the beginning of the [`SourceMap`], not positions
658/// relative to [`SourceFile`]s. Methods on the `SourceMap` can be used to relate spans back
659/// to the original source.
660///
661/// You must be careful if the span crosses more than one file, since you will not be
662/// able to use many of the functions on spans in source_map and you cannot assume
663/// that the length of the span is equal to `span.hi - span.lo`; there may be space in the
664/// [`BytePos`] range between files.
665///
666/// `SpanData` is public because `Span` uses a thread-local interner and can't be
667/// sent to other threads, but some pieces of performance infra run in a separate thread.
668/// Using `Span` is generally preferred.
669#[derive(Clone, Copy, Hash, PartialEq, Eq)]
670#[derive_where(PartialOrd, Ord)]
671pub struct SpanData {
672    pub lo: BytePos,
673    pub hi: BytePos,
674    /// Information about where the macro came from, if this piece of
675    /// code was created by a macro expansion.
676    #[derive_where(skip)]
677    // `SyntaxContext` does not implement `Ord`.
678    // The other fields are enough to determine in-file order.
679    pub ctxt: SyntaxContext,
680    #[derive_where(skip)]
681    // `LocalDefId` does not implement `Ord`.
682    // The other fields are enough to determine in-file order.
683    pub parent: Option<LocalDefId>,
684}
685
686impl SpanData {
687    #[inline]
688    pub fn span(&self) -> Span {
689        Span::new(self.lo, self.hi, self.ctxt, self.parent)
690    }
691    #[inline]
692    pub fn with_lo(&self, lo: BytePos) -> Span {
693        Span::new(lo, self.hi, self.ctxt, self.parent)
694    }
695    #[inline]
696    pub fn with_hi(&self, hi: BytePos) -> Span {
697        Span::new(self.lo, hi, self.ctxt, self.parent)
698    }
699    /// Avoid if possible, `Span::map_ctxt` should be preferred.
700    #[inline]
701    fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
702        Span::new(self.lo, self.hi, ctxt, self.parent)
703    }
704    /// Avoid if possible, `Span::with_parent` should be preferred.
705    #[inline]
706    fn with_parent(&self, parent: Option<LocalDefId>) -> Span {
707        Span::new(self.lo, self.hi, self.ctxt, parent)
708    }
709    /// Returns `true` if this is a dummy span with any hygienic context.
710    #[inline]
711    pub fn is_dummy(self) -> bool {
712        self.lo.0 == 0 && self.hi.0 == 0
713    }
714    /// Returns `true` if `self` fully encloses `other`.
715    pub fn contains(self, other: Self) -> bool {
716        self.lo <= other.lo && other.hi <= self.hi
717    }
718}
719
720impl Default for SpanData {
721    fn default() -> Self {
722        Self { lo: BytePos(0), hi: BytePos(0), ctxt: SyntaxContext::root(), parent: None }
723    }
724}
725
726impl PartialOrd for Span {
727    fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
728        PartialOrd::partial_cmp(&self.data(), &rhs.data())
729    }
730}
731impl Ord for Span {
732    fn cmp(&self, rhs: &Self) -> Ordering {
733        Ord::cmp(&self.data(), &rhs.data())
734    }
735}
736
737impl Span {
738    #[inline]
739    pub fn lo(self) -> BytePos {
740        self.data().lo
741    }
742    #[inline]
743    pub fn with_lo(self, lo: BytePos) -> Span {
744        self.data().with_lo(lo)
745    }
746    #[inline]
747    pub fn hi(self) -> BytePos {
748        self.data().hi
749    }
750    #[inline]
751    pub fn with_hi(self, hi: BytePos) -> Span {
752        self.data().with_hi(hi)
753    }
754    #[inline]
755    pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
756        self.map_ctxt(|_| ctxt)
757    }
758
759    #[inline]
760    pub fn is_visible(self, sm: &SourceMap) -> bool {
761        !self.is_dummy() && sm.is_span_accessible(self)
762    }
763
764    /// Returns whether this span originates in a foreign crate's external macro.
765    ///
766    /// This is used to test whether a lint should not even begin to figure out whether it should
767    /// be reported on the current node.
768    #[inline]
769    pub fn in_external_macro(self, sm: &SourceMap) -> bool {
770        self.ctxt().in_external_macro(sm)
771    }
772
773    /// Returns `true` if `span` originates in a derive-macro's expansion.
774    pub fn in_derive_expansion(self) -> bool {
775        matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _))
776    }
777
778    /// Return whether `span` is generated by `async` or `await`.
779    pub fn is_from_async_await(self) -> bool {
780        matches!(
781            self.ctxt().outer_expn_data().kind,
782            ExpnKind::Desugaring(DesugaringKind::Async | DesugaringKind::Await),
783        )
784    }
785
786    /// Gate suggestions that would not be appropriate in a context the user didn't write.
787    pub fn can_be_used_for_suggestions(self) -> bool {
788        !self.from_expansion()
789        // FIXME: If this span comes from a `derive` macro but it points at code the user wrote,
790        // the callsite span and the span will be pointing at different places. It also means that
791        // we can safely provide suggestions on this span.
792            || (self.in_derive_expansion()
793                && self.parent_callsite().map(|p| (p.lo(), p.hi())) != Some((self.lo(), self.hi())))
794    }
795
796    #[inline]
797    pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
798        Span::new(lo, hi, SyntaxContext::root(), None)
799    }
800
801    /// Returns a new span representing an empty span at the beginning of this span.
802    #[inline]
803    pub fn shrink_to_lo(self) -> Span {
804        let span = self.data_untracked();
805        span.with_hi(span.lo)
806    }
807    /// Returns a new span representing an empty span at the end of this span.
808    #[inline]
809    pub fn shrink_to_hi(self) -> Span {
810        let span = self.data_untracked();
811        span.with_lo(span.hi)
812    }
813
814    #[inline]
815    /// Returns `true` if `hi == lo`.
816    pub fn is_empty(self) -> bool {
817        let span = self.data_untracked();
818        span.hi == span.lo
819    }
820
821    /// Returns `self` if `self` is not the dummy span, and `other` otherwise.
822    pub fn substitute_dummy(self, other: Span) -> Span {
823        if self.is_dummy() { other } else { self }
824    }
825
826    /// Returns `true` if `self` fully encloses `other`.
827    pub fn contains(self, other: Span) -> bool {
828        let span = self.data();
829        let other = other.data();
830        span.contains(other)
831    }
832
833    /// Returns `true` if `self` touches `other`.
834    pub fn overlaps(self, other: Span) -> bool {
835        let span = self.data();
836        let other = other.data();
837        span.lo < other.hi && other.lo < span.hi
838    }
839
840    /// Returns `true` if `self` touches or adjoins `other`.
841    pub fn overlaps_or_adjacent(self, other: Span) -> bool {
842        let span = self.data();
843        let other = other.data();
844        span.lo <= other.hi && other.lo <= span.hi
845    }
846
847    /// Returns `true` if the spans are equal with regards to the source text.
848    ///
849    /// Use this instead of `==` when either span could be generated code,
850    /// and you only care that they point to the same bytes of source text.
851    pub fn source_equal(self, other: Span) -> bool {
852        let span = self.data();
853        let other = other.data();
854        span.lo == other.lo && span.hi == other.hi
855    }
856
857    /// Returns `Some(span)`, where the start is trimmed by the end of `other`.
858    pub fn trim_start(self, other: Span) -> Option<Span> {
859        let span = self.data();
860        let other = other.data();
861        if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None }
862    }
863
864    /// Returns `Some(span)`, where the end is trimmed by the start of `other`.
865    pub fn trim_end(self, other: Span) -> Option<Span> {
866        let span = self.data();
867        let other = other.data();
868        if span.lo < other.lo { Some(span.with_hi(cmp::min(span.hi, other.lo))) } else { None }
869    }
870
871    /// Returns the source span -- this is either the supplied span, or the span for
872    /// the macro callsite that expanded to it.
873    pub fn source_callsite(self) -> Span {
874        let ctxt = self.ctxt();
875        if !ctxt.is_root() { ctxt.outer_expn_data().call_site.source_callsite() } else { self }
876    }
877
878    /// Returns the call-site span of the last macro expansion which produced this `Span`.
879    /// (see [`ExpnData::call_site`]). Returns `None` if this is not an expansion.
880    pub fn parent_callsite(self) -> Option<Span> {
881        let ctxt = self.ctxt();
882        (!ctxt.is_root()).then(|| ctxt.outer_expn_data().call_site)
883    }
884
885    /// Find the first ancestor span that's contained within `outer`.
886    ///
887    /// This method traverses the macro expansion ancestors until it finds the first span
888    /// that's contained within `outer`.
889    ///
890    /// The span returned by this method may have a different [`SyntaxContext`] than `outer`.
891    /// If you need to extend the span, use [`find_ancestor_inside_same_ctxt`] instead,
892    /// because joining spans with different syntax contexts can create unexpected results.
893    ///
894    /// This is used to find the span of the macro call when a parent expr span, i.e. `outer`, is known.
895    ///
896    /// [`find_ancestor_inside_same_ctxt`]: Self::find_ancestor_inside_same_ctxt
897    pub fn find_ancestor_inside(mut self, outer: Span) -> Option<Span> {
898        while !outer.contains(self) {
899            self = self.parent_callsite()?;
900        }
901        Some(self)
902    }
903
904    /// Find the first ancestor span with the same [`SyntaxContext`] as `other`.
905    ///
906    /// This method traverses the macro expansion ancestors until it finds a span
907    /// that has the same [`SyntaxContext`] as `other`.
908    ///
909    /// Like [`find_ancestor_inside_same_ctxt`], but specifically for when spans might not
910    /// overlap. Take care when using this, and prefer [`find_ancestor_inside`] or
911    /// [`find_ancestor_inside_same_ctxt`] when you know that the spans are nested (modulo
912    /// macro expansion).
913    ///
914    /// [`find_ancestor_inside`]: Self::find_ancestor_inside
915    /// [`find_ancestor_inside_same_ctxt`]: Self::find_ancestor_inside_same_ctxt
916    pub fn find_ancestor_in_same_ctxt(mut self, other: Span) -> Option<Span> {
917        while !self.eq_ctxt(other) {
918            self = self.parent_callsite()?;
919        }
920        Some(self)
921    }
922
923    /// Find the first ancestor span that's contained within `outer` and
924    /// has the same [`SyntaxContext`] as `outer`.
925    ///
926    /// This method traverses the macro expansion ancestors until it finds a span
927    /// that is both contained within `outer` and has the same [`SyntaxContext`] as `outer`.
928    ///
929    /// This method is the combination of [`find_ancestor_inside`] and
930    /// [`find_ancestor_in_same_ctxt`] and should be preferred when extending the returned span.
931    /// If you do not need to modify the span, use [`find_ancestor_inside`] instead.
932    ///
933    /// [`find_ancestor_inside`]: Self::find_ancestor_inside
934    /// [`find_ancestor_in_same_ctxt`]: Self::find_ancestor_in_same_ctxt
935    pub fn find_ancestor_inside_same_ctxt(mut self, outer: Span) -> Option<Span> {
936        while !outer.contains(self) || !self.eq_ctxt(outer) {
937            self = self.parent_callsite()?;
938        }
939        Some(self)
940    }
941
942    /// Find the first ancestor span that does not come from an external macro.
943    ///
944    /// This method traverses the macro expansion ancestors until it finds a span
945    /// that is either from user-written code or from a local macro (defined in the current crate).
946    ///
947    /// External macros are those defined in dependencies or the standard library.
948    /// This method is useful for reporting errors in user-controllable code and avoiding
949    /// diagnostics inside external macros.
950    ///
951    /// # See also
952    ///
953    /// - [`Self::find_ancestor_not_from_macro`]
954    /// - [`Self::in_external_macro`]
955    pub fn find_ancestor_not_from_extern_macro(mut self, sm: &SourceMap) -> Option<Span> {
956        while self.in_external_macro(sm) {
957            self = self.parent_callsite()?;
958        }
959        Some(self)
960    }
961
962    /// Find the first ancestor span that does not come from any macro expansion.
963    ///
964    /// This method traverses the macro expansion ancestors until it finds a span
965    /// that originates from user-written code rather than any macro-generated code.
966    ///
967    /// This method is useful for reporting errors at the exact location users wrote code
968    /// and providing suggestions at directly editable locations.
969    ///
970    /// # See also
971    ///
972    /// - [`Self::find_ancestor_not_from_extern_macro`]
973    /// - [`Span::from_expansion`]
974    pub fn find_ancestor_not_from_macro(mut self) -> Option<Span> {
975        while self.from_expansion() {
976            self = self.parent_callsite()?;
977        }
978        Some(self)
979    }
980
981    /// Edition of the crate from which this span came.
982    pub fn edition(self) -> edition::Edition {
983        self.ctxt().edition()
984    }
985
986    /// Is this edition 2015?
987    #[inline]
988    pub fn is_rust_2015(self) -> bool {
989        self.edition().is_rust_2015()
990    }
991
992    /// Are we allowed to use features from the Rust 2018 edition?
993    #[inline]
994    pub fn at_least_rust_2018(self) -> bool {
995        self.edition().at_least_rust_2018()
996    }
997
998    /// Are we allowed to use features from the Rust 2021 edition?
999    #[inline]
1000    pub fn at_least_rust_2021(self) -> bool {
1001        self.edition().at_least_rust_2021()
1002    }
1003
1004    /// Are we allowed to use features from the Rust 2024 edition?
1005    #[inline]
1006    pub fn at_least_rust_2024(self) -> bool {
1007        self.edition().at_least_rust_2024()
1008    }
1009
1010    /// Returns the source callee.
1011    ///
1012    /// Returns `None` if the supplied span has no expansion trace,
1013    /// else returns the `ExpnData` for the macro definition
1014    /// corresponding to the source callsite.
1015    pub fn source_callee(self) -> Option<ExpnData> {
1016        let mut ctxt = self.ctxt();
1017        let mut opt_expn_data = None;
1018        while !ctxt.is_root() {
1019            let expn_data = ctxt.outer_expn_data();
1020            ctxt = expn_data.call_site.ctxt();
1021            opt_expn_data = Some(expn_data);
1022        }
1023        opt_expn_data
1024    }
1025
1026    /// Checks if a span is "internal" to a macro in which `#[unstable]`
1027    /// items can be used (that is, a macro marked with
1028    /// `#[allow_internal_unstable]`).
1029    pub fn allows_unstable(self, feature: Symbol) -> bool {
1030        self.ctxt()
1031            .outer_expn_data()
1032            .allow_internal_unstable
1033            .is_some_and(|features| features.contains(&feature))
1034    }
1035
1036    /// Checks if this span arises from a compiler desugaring of kind `kind`.
1037    pub fn is_desugaring(self, kind: DesugaringKind) -> bool {
1038        match self.ctxt().outer_expn_data().kind {
1039            ExpnKind::Desugaring(k) => k == kind,
1040            _ => false,
1041        }
1042    }
1043
1044    /// Returns the compiler desugaring that created this span, or `None`
1045    /// if this span is not from a desugaring.
1046    pub fn desugaring_kind(self) -> Option<DesugaringKind> {
1047        match self.ctxt().outer_expn_data().kind {
1048            ExpnKind::Desugaring(k) => Some(k),
1049            _ => None,
1050        }
1051    }
1052
1053    /// Checks if a span is "internal" to a macro in which `unsafe`
1054    /// can be used without triggering the `unsafe_code` lint.
1055    /// (that is, a macro marked with `#[allow_internal_unsafe]`).
1056    pub fn allows_unsafe(self) -> bool {
1057        self.ctxt().outer_expn_data().allow_internal_unsafe
1058    }
1059
1060    pub fn macro_backtrace(mut self) -> impl Iterator<Item = ExpnData> {
1061        let mut prev_span = DUMMY_SP;
1062        iter::from_fn(move || {
1063            loop {
1064                let ctxt = self.ctxt();
1065                if ctxt.is_root() {
1066                    return None;
1067                }
1068
1069                let expn_data = ctxt.outer_expn_data();
1070                let is_recursive = expn_data.call_site.source_equal(prev_span);
1071
1072                prev_span = self;
1073                self = expn_data.call_site;
1074
1075                // Don't print recursive invocations.
1076                if !is_recursive {
1077                    return Some(expn_data);
1078                }
1079            }
1080        })
1081    }
1082
1083    /// Splits a span into two composite spans around a certain position.
1084    pub fn split_at(self, pos: u32) -> (Span, Span) {
1085        let len = self.hi().0 - self.lo().0;
1086        debug_assert!(pos <= len);
1087
1088        let split_pos = BytePos(self.lo().0 + pos);
1089        (
1090            Span::new(self.lo(), split_pos, self.ctxt(), self.parent()),
1091            Span::new(split_pos, self.hi(), self.ctxt(), self.parent()),
1092        )
1093    }
1094
1095    /// Check if you can select metavar spans for the given spans to get matching contexts.
1096    fn try_metavars(a: SpanData, b: SpanData, a_orig: Span, b_orig: Span) -> (SpanData, SpanData) {
1097        match with_metavar_spans(|mspans| (mspans.get(a_orig), mspans.get(b_orig))) {
1098            (None, None) => {}
1099            (Some(meta_a), None) => {
1100                let meta_a = meta_a.data();
1101                if meta_a.ctxt == b.ctxt {
1102                    return (meta_a, b);
1103                }
1104            }
1105            (None, Some(meta_b)) => {
1106                let meta_b = meta_b.data();
1107                if a.ctxt == meta_b.ctxt {
1108                    return (a, meta_b);
1109                }
1110            }
1111            (Some(meta_a), Some(meta_b)) => {
1112                let meta_b = meta_b.data();
1113                if a.ctxt == meta_b.ctxt {
1114                    return (a, meta_b);
1115                }
1116                let meta_a = meta_a.data();
1117                if meta_a.ctxt == b.ctxt {
1118                    return (meta_a, b);
1119                } else if meta_a.ctxt == meta_b.ctxt {
1120                    return (meta_a, meta_b);
1121                }
1122            }
1123        }
1124
1125        (a, b)
1126    }
1127
1128    /// Prepare two spans to a combine operation like `to` or `between`.
1129    fn prepare_to_combine(
1130        a_orig: Span,
1131        b_orig: Span,
1132    ) -> Result<(SpanData, SpanData, Option<LocalDefId>), Span> {
1133        let (a, b) = (a_orig.data(), b_orig.data());
1134        if a.ctxt == b.ctxt {
1135            return Ok((a, b, if a.parent == b.parent { a.parent } else { None }));
1136        }
1137
1138        let (a, b) = Span::try_metavars(a, b, a_orig, b_orig);
1139        if a.ctxt == b.ctxt {
1140            return Ok((a, b, if a.parent == b.parent { a.parent } else { None }));
1141        }
1142
1143        // Context mismatches usually happen when procedural macros combine spans copied from
1144        // the macro input with spans produced by the macro (`Span::*_site`).
1145        // In that case we consider the combined span to be produced by the macro and return
1146        // the original macro-produced span as the result.
1147        // Otherwise we just fall back to returning the first span.
1148        // Combining locations typically doesn't make sense in case of context mismatches.
1149        // `is_root` here is a fast path optimization.
1150        let a_is_callsite = a.ctxt.is_root() || a.ctxt == b.span().source_callsite().ctxt();
1151        Err(if a_is_callsite { b_orig } else { a_orig })
1152    }
1153
1154    /// This span, but in a larger context, may switch to the metavariable span if suitable.
1155    pub fn with_neighbor(self, neighbor: Span) -> Span {
1156        match Span::prepare_to_combine(self, neighbor) {
1157            Ok((this, ..)) => this.span(),
1158            Err(_) => self,
1159        }
1160    }
1161
1162    /// Returns a `Span` that would enclose both `self` and `end`.
1163    ///
1164    /// Note that this can also be used to extend the span "backwards":
1165    /// `start.to(end)` and `end.to(start)` return the same `Span`.
1166    ///
1167    /// ```text
1168    ///     ____             ___
1169    ///     self lorem ipsum end
1170    ///     ^^^^^^^^^^^^^^^^^^^^
1171    /// ```
1172    pub fn to(self, end: Span) -> Span {
1173        match Span::prepare_to_combine(self, end) {
1174            Ok((from, to, parent)) => {
1175                Span::new(cmp::min(from.lo, to.lo), cmp::max(from.hi, to.hi), from.ctxt, parent)
1176            }
1177            Err(fallback) => fallback,
1178        }
1179    }
1180
1181    /// Returns a `Span` between the end of `self` to the beginning of `end`.
1182    ///
1183    /// ```text
1184    ///     ____             ___
1185    ///     self lorem ipsum end
1186    ///         ^^^^^^^^^^^^^
1187    /// ```
1188    pub fn between(self, end: Span) -> Span {
1189        match Span::prepare_to_combine(self, end) {
1190            Ok((from, to, parent)) => {
1191                Span::new(cmp::min(from.hi, to.hi), cmp::max(from.lo, to.lo), from.ctxt, parent)
1192            }
1193            Err(fallback) => fallback,
1194        }
1195    }
1196
1197    /// Returns a `Span` from the beginning of `self` until the beginning of `end`.
1198    ///
1199    /// ```text
1200    ///     ____             ___
1201    ///     self lorem ipsum end
1202    ///     ^^^^^^^^^^^^^^^^^
1203    /// ```
1204    pub fn until(self, end: Span) -> Span {
1205        match Span::prepare_to_combine(self, end) {
1206            Ok((from, to, parent)) => {
1207                Span::new(cmp::min(from.lo, to.lo), cmp::max(from.lo, to.lo), from.ctxt, parent)
1208            }
1209            Err(fallback) => fallback,
1210        }
1211    }
1212
1213    /// Returns the `Span` within the syntax context of "within". This is useful when
1214    /// "self" is an expansion from a macro variable, since this can be used for
1215    /// providing extra macro expansion context for certain errors.
1216    ///
1217    /// ```text
1218    /// macro_rules! m {
1219    ///     ($ident:ident) => { ($ident,) }
1220    /// }
1221    ///
1222    /// m!(outer_ident);
1223    /// ```
1224    ///
1225    /// If "self" is the span of the outer_ident, and "within" is the span of the `($ident,)`
1226    /// expr, then this will return the span of the `$ident` macro variable.
1227    pub fn within_macro(self, within: Span, sm: &SourceMap) -> Option<Span> {
1228        match Span::prepare_to_combine(self, within) {
1229            // Only return something if it doesn't overlap with the original span,
1230            // and the span isn't "imported" (i.e. from unavailable sources).
1231            // FIXME: This does limit the usefulness of the error when the macro is
1232            // from a foreign crate; we could also take into account `-Zmacro-backtrace`,
1233            // which doesn't redact this span (but that would mean passing in even more
1234            // args to this function, lol).
1235            Ok((self_, _, parent))
1236                if self_.hi < self.lo() || self.hi() < self_.lo && !sm.is_imported(within) =>
1237            {
1238                Some(Span::new(self_.lo, self_.hi, self_.ctxt, parent))
1239            }
1240            _ => None,
1241        }
1242    }
1243
1244    pub fn from_inner(self, inner: InnerSpan) -> Span {
1245        let span = self.data();
1246        Span::new(
1247            span.lo + BytePos::from_usize(inner.start),
1248            span.lo + BytePos::from_usize(inner.end),
1249            span.ctxt,
1250            span.parent,
1251        )
1252    }
1253
1254    /// Equivalent of `Span::def_site` from the proc macro API,
1255    /// except that the location is taken from the `self` span.
1256    pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
1257        self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
1258    }
1259
1260    /// Equivalent of `Span::call_site` from the proc macro API,
1261    /// except that the location is taken from the `self` span.
1262    pub fn with_call_site_ctxt(self, expn_id: ExpnId) -> Span {
1263        self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
1264    }
1265
1266    /// Equivalent of `Span::mixed_site` from the proc macro API,
1267    /// except that the location is taken from the `self` span.
1268    pub fn with_mixed_site_ctxt(self, expn_id: ExpnId) -> Span {
1269        self.with_ctxt_from_mark(expn_id, Transparency::SemiOpaque)
1270    }
1271
1272    /// Produces a span with the same location as `self` and context produced by a macro with the
1273    /// given ID and transparency, assuming that macro was defined directly and not produced by
1274    /// some other macro (which is the case for built-in and procedural macros).
1275    fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
1276        self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
1277    }
1278
1279    #[inline]
1280    pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
1281        self.map_ctxt(|ctxt| ctxt.apply_mark(expn_id, transparency))
1282    }
1283
1284    #[inline]
1285    pub fn remove_mark(&mut self) -> ExpnId {
1286        let mut mark = ExpnId::root();
1287        *self = self.map_ctxt(|mut ctxt| {
1288            mark = ctxt.remove_mark();
1289            ctxt
1290        });
1291        mark
1292    }
1293
1294    #[inline]
1295    pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
1296        let mut mark = None;
1297        *self = self.map_ctxt(|mut ctxt| {
1298            mark = ctxt.adjust(expn_id);
1299            ctxt
1300        });
1301        mark
1302    }
1303
1304    #[inline]
1305    pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
1306        let mut mark = None;
1307        *self = self.map_ctxt(|mut ctxt| {
1308            mark = ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
1309            ctxt
1310        });
1311        mark
1312    }
1313
1314    #[inline]
1315    pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option<Option<ExpnId>> {
1316        let mut mark = None;
1317        *self = self.map_ctxt(|mut ctxt| {
1318            mark = ctxt.glob_adjust(expn_id, glob_span);
1319            ctxt
1320        });
1321        mark
1322    }
1323
1324    #[inline]
1325    pub fn reverse_glob_adjust(
1326        &mut self,
1327        expn_id: ExpnId,
1328        glob_span: Span,
1329    ) -> Option<Option<ExpnId>> {
1330        let mut mark = None;
1331        *self = self.map_ctxt(|mut ctxt| {
1332            mark = ctxt.reverse_glob_adjust(expn_id, glob_span);
1333            ctxt
1334        });
1335        mark
1336    }
1337
1338    #[inline]
1339    pub fn normalize_to_macros_2_0(self) -> Span {
1340        self.map_ctxt(|ctxt| ctxt.normalize_to_macros_2_0())
1341    }
1342
1343    #[inline]
1344    pub fn normalize_to_macro_rules(self) -> Span {
1345        self.map_ctxt(|ctxt| ctxt.normalize_to_macro_rules())
1346    }
1347}
1348
1349impl Default for Span {
1350    fn default() -> Self {
1351        DUMMY_SP
1352    }
1353}
1354
1355rustc_index::newtype_index! {
1356    #[orderable]
1357    #[debug_format = "AttrId({})"]
1358    pub struct AttrId {}
1359}
1360
1361/// This trait is used to allow encoder specific encodings of certain types.
1362/// It is similar to rustc_type_ir's TyEncoder.
1363pub trait SpanEncoder: Encoder {
1364    fn encode_span(&mut self, span: Span);
1365    fn encode_symbol(&mut self, sym: Symbol);
1366    fn encode_byte_symbol(&mut self, byte_sym: ByteSymbol);
1367    fn encode_expn_id(&mut self, expn_id: ExpnId);
1368    fn encode_syntax_context(&mut self, syntax_context: SyntaxContext);
1369    /// As a local identifier, a `CrateNum` is only meaningful within its context, e.g. within a
1370    /// tcx. Therefore, make sure to include the context when encode a `CrateNum`.
1371    fn encode_crate_num(&mut self, crate_num: CrateNum);
1372    fn encode_def_index(&mut self, def_index: DefIndex);
1373    fn encode_def_id(&mut self, def_id: DefId);
1374}
1375
1376impl SpanEncoder for FileEncoder {
1377    fn encode_span(&mut self, span: Span) {
1378        let span = span.data();
1379        span.lo.encode(self);
1380        span.hi.encode(self);
1381    }
1382
1383    fn encode_symbol(&mut self, sym: Symbol) {
1384        self.emit_str(sym.as_str());
1385    }
1386
1387    fn encode_byte_symbol(&mut self, byte_sym: ByteSymbol) {
1388        self.emit_byte_str(byte_sym.as_byte_str());
1389    }
1390
1391    fn encode_expn_id(&mut self, _expn_id: ExpnId) {
1392        panic!("cannot encode `ExpnId` with `FileEncoder`");
1393    }
1394
1395    fn encode_syntax_context(&mut self, _syntax_context: SyntaxContext) {
1396        panic!("cannot encode `SyntaxContext` with `FileEncoder`");
1397    }
1398
1399    fn encode_crate_num(&mut self, crate_num: CrateNum) {
1400        self.emit_u32(crate_num.as_u32());
1401    }
1402
1403    fn encode_def_index(&mut self, _def_index: DefIndex) {
1404        panic!("cannot encode `DefIndex` with `FileEncoder`");
1405    }
1406
1407    fn encode_def_id(&mut self, def_id: DefId) {
1408        def_id.krate.encode(self);
1409        def_id.index.encode(self);
1410    }
1411}
1412
1413impl<E: SpanEncoder> Encodable<E> for Span {
1414    fn encode(&self, s: &mut E) {
1415        s.encode_span(*self);
1416    }
1417}
1418
1419impl<E: SpanEncoder> Encodable<E> for Symbol {
1420    fn encode(&self, s: &mut E) {
1421        s.encode_symbol(*self);
1422    }
1423}
1424
1425impl<E: SpanEncoder> Encodable<E> for ByteSymbol {
1426    fn encode(&self, s: &mut E) {
1427        s.encode_byte_symbol(*self);
1428    }
1429}
1430
1431impl<E: SpanEncoder> Encodable<E> for ExpnId {
1432    fn encode(&self, s: &mut E) {
1433        s.encode_expn_id(*self)
1434    }
1435}
1436
1437impl<E: SpanEncoder> Encodable<E> for SyntaxContext {
1438    fn encode(&self, s: &mut E) {
1439        s.encode_syntax_context(*self)
1440    }
1441}
1442
1443impl<E: SpanEncoder> Encodable<E> for CrateNum {
1444    fn encode(&self, s: &mut E) {
1445        s.encode_crate_num(*self)
1446    }
1447}
1448
1449impl<E: SpanEncoder> Encodable<E> for DefIndex {
1450    fn encode(&self, s: &mut E) {
1451        s.encode_def_index(*self)
1452    }
1453}
1454
1455impl<E: SpanEncoder> Encodable<E> for DefId {
1456    fn encode(&self, s: &mut E) {
1457        s.encode_def_id(*self)
1458    }
1459}
1460
1461impl<E: SpanEncoder> Encodable<E> for AttrId {
1462    fn encode(&self, _s: &mut E) {
1463        // A fresh id will be generated when decoding
1464    }
1465}
1466
1467pub trait BlobDecoder: Decoder {
1468    fn decode_symbol(&mut self) -> Symbol;
1469    fn decode_byte_symbol(&mut self) -> ByteSymbol;
1470    fn decode_def_index(&mut self) -> DefIndex;
1471}
1472
1473/// This trait is used to allow decoder specific encodings of certain types.
1474/// It is similar to rustc_type_ir's TyDecoder.
1475///
1476/// Specifically for metadata, an important note is that spans can only be decoded once
1477/// some other metadata is already read.
1478/// Spans have to be properly mapped into the decoding crate's sourcemap,
1479/// and crate numbers have to be converted sometimes.
1480/// This can only be done once the `CrateRoot` is available.
1481///
1482/// As such, some methods that used to be in the `SpanDecoder` trait
1483/// are now in the `BlobDecoder` trait. This hierarchy is not mirrored for `Encoder`s.
1484/// `BlobDecoder` has methods for deserializing types that are more complex than just those
1485/// that can be decoded with `Decoder`, but which can be decoded on their own, *before* any other metadata is.
1486/// Importantly, that means that types that can be decoded with `BlobDecoder` can show up in the crate root.
1487/// The place where this distinction is relevant is in `rustc_metadata` where metadata is decoded using either the
1488/// `MetadataDecodeContext` or the `BlobDecodeContext`.
1489pub trait SpanDecoder: BlobDecoder {
1490    fn decode_span(&mut self) -> Span;
1491    fn decode_expn_id(&mut self) -> ExpnId;
1492    fn decode_syntax_context(&mut self) -> SyntaxContext;
1493    fn decode_crate_num(&mut self) -> CrateNum;
1494    fn decode_def_id(&mut self) -> DefId;
1495    fn decode_attr_id(&mut self) -> AttrId;
1496}
1497
1498impl BlobDecoder for MemDecoder<'_> {
1499    fn decode_symbol(&mut self) -> Symbol {
1500        Symbol::intern(self.read_str())
1501    }
1502
1503    fn decode_byte_symbol(&mut self) -> ByteSymbol {
1504        ByteSymbol::intern(self.read_byte_str())
1505    }
1506
1507    fn decode_def_index(&mut self) -> DefIndex {
1508        panic!("cannot decode `DefIndex` with `MemDecoder`");
1509    }
1510}
1511
1512impl SpanDecoder for MemDecoder<'_> {
1513    fn decode_span(&mut self) -> Span {
1514        let lo = Decodable::decode(self);
1515        let hi = Decodable::decode(self);
1516
1517        Span::new(lo, hi, SyntaxContext::root(), None)
1518    }
1519
1520    fn decode_expn_id(&mut self) -> ExpnId {
1521        panic!("cannot decode `ExpnId` with `MemDecoder`");
1522    }
1523
1524    fn decode_syntax_context(&mut self) -> SyntaxContext {
1525        panic!("cannot decode `SyntaxContext` with `MemDecoder`");
1526    }
1527
1528    fn decode_crate_num(&mut self) -> CrateNum {
1529        CrateNum::from_u32(self.read_u32())
1530    }
1531
1532    fn decode_def_id(&mut self) -> DefId {
1533        DefId { krate: Decodable::decode(self), index: Decodable::decode(self) }
1534    }
1535
1536    fn decode_attr_id(&mut self) -> AttrId {
1537        panic!("cannot decode `AttrId` with `MemDecoder`");
1538    }
1539}
1540
1541impl<D: SpanDecoder> Decodable<D> for Span {
1542    fn decode(s: &mut D) -> Span {
1543        s.decode_span()
1544    }
1545}
1546
1547impl<D: BlobDecoder> Decodable<D> for Symbol {
1548    fn decode(s: &mut D) -> Symbol {
1549        s.decode_symbol()
1550    }
1551}
1552
1553impl<D: BlobDecoder> Decodable<D> for ByteSymbol {
1554    fn decode(s: &mut D) -> ByteSymbol {
1555        s.decode_byte_symbol()
1556    }
1557}
1558
1559impl<D: SpanDecoder> Decodable<D> for ExpnId {
1560    fn decode(s: &mut D) -> ExpnId {
1561        s.decode_expn_id()
1562    }
1563}
1564
1565impl<D: SpanDecoder> Decodable<D> for SyntaxContext {
1566    fn decode(s: &mut D) -> SyntaxContext {
1567        s.decode_syntax_context()
1568    }
1569}
1570
1571impl<D: SpanDecoder> Decodable<D> for CrateNum {
1572    fn decode(s: &mut D) -> CrateNum {
1573        s.decode_crate_num()
1574    }
1575}
1576
1577impl<D: BlobDecoder> Decodable<D> for DefIndex {
1578    fn decode(s: &mut D) -> DefIndex {
1579        s.decode_def_index()
1580    }
1581}
1582
1583impl<D: SpanDecoder> Decodable<D> for DefId {
1584    fn decode(s: &mut D) -> DefId {
1585        s.decode_def_id()
1586    }
1587}
1588
1589impl<D: SpanDecoder> Decodable<D> for AttrId {
1590    fn decode(s: &mut D) -> AttrId {
1591        s.decode_attr_id()
1592    }
1593}
1594
1595impl fmt::Debug for Span {
1596    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1597        // Use the global `SourceMap` to print the span. If that's not
1598        // available, fall back to printing the raw values.
1599
1600        fn fallback(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1601            f.debug_struct("Span")
1602                .field("lo", &span.lo())
1603                .field("hi", &span.hi())
1604                .field("ctxt", &span.ctxt())
1605                .finish()
1606        }
1607
1608        if SESSION_GLOBALS.is_set() {
1609            with_session_globals(|session_globals| {
1610                if let Some(source_map) = &session_globals.source_map {
1611                    write!(f, "{} ({:?})", source_map.span_to_diagnostic_string(*self), self.ctxt())
1612                } else {
1613                    fallback(*self, f)
1614                }
1615            })
1616        } else {
1617            fallback(*self, f)
1618        }
1619    }
1620}
1621
1622impl fmt::Debug for SpanData {
1623    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1624        fmt::Debug::fmt(&self.span(), f)
1625    }
1626}
1627
1628/// Identifies an offset of a multi-byte character in a `SourceFile`.
1629#[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug, HashStable_Generic)]
1630pub struct MultiByteChar {
1631    /// The relative offset of the character in the `SourceFile`.
1632    pub pos: RelativeBytePos,
1633    /// The number of bytes, `>= 2`.
1634    pub bytes: u8,
1635}
1636
1637/// Identifies an offset of a character that was normalized away from `SourceFile`.
1638#[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug, HashStable_Generic)]
1639pub struct NormalizedPos {
1640    /// The relative offset of the character in the `SourceFile`.
1641    pub pos: RelativeBytePos,
1642    /// The difference between original and normalized string at position.
1643    pub diff: u32,
1644}
1645
1646#[derive(PartialEq, Eq, Clone, Debug)]
1647pub enum ExternalSource {
1648    /// No external source has to be loaded, since the `SourceFile` represents a local crate.
1649    Unneeded,
1650    Foreign {
1651        kind: ExternalSourceKind,
1652        /// Index of the file inside metadata.
1653        metadata_index: u32,
1654    },
1655}
1656
1657/// The state of the lazy external source loading mechanism of a `SourceFile`.
1658#[derive(PartialEq, Eq, Clone, Debug)]
1659pub enum ExternalSourceKind {
1660    /// The external source has been loaded already.
1661    Present(Arc<String>),
1662    /// No attempt has been made to load the external source.
1663    AbsentOk,
1664    /// A failed attempt has been made to load the external source.
1665    AbsentErr,
1666}
1667
1668impl ExternalSource {
1669    pub fn get_source(&self) -> Option<&str> {
1670        match self {
1671            ExternalSource::Foreign { kind: ExternalSourceKind::Present(src), .. } => Some(src),
1672            _ => None,
1673        }
1674    }
1675}
1676
1677#[derive(Debug)]
1678pub struct OffsetOverflowError;
1679
1680#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)]
1681#[derive(HashStable_Generic)]
1682pub enum SourceFileHashAlgorithm {
1683    Md5,
1684    Sha1,
1685    Sha256,
1686    Blake3,
1687}
1688
1689impl Display for SourceFileHashAlgorithm {
1690    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1691        f.write_str(match self {
1692            Self::Md5 => "md5",
1693            Self::Sha1 => "sha1",
1694            Self::Sha256 => "sha256",
1695            Self::Blake3 => "blake3",
1696        })
1697    }
1698}
1699
1700impl FromStr for SourceFileHashAlgorithm {
1701    type Err = ();
1702
1703    fn from_str(s: &str) -> Result<SourceFileHashAlgorithm, ()> {
1704        match s {
1705            "md5" => Ok(SourceFileHashAlgorithm::Md5),
1706            "sha1" => Ok(SourceFileHashAlgorithm::Sha1),
1707            "sha256" => Ok(SourceFileHashAlgorithm::Sha256),
1708            "blake3" => Ok(SourceFileHashAlgorithm::Blake3),
1709            _ => Err(()),
1710        }
1711    }
1712}
1713
1714/// The hash of the on-disk source file used for debug info and cargo freshness checks.
1715#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
1716#[derive(HashStable_Generic, Encodable, Decodable)]
1717pub struct SourceFileHash {
1718    pub kind: SourceFileHashAlgorithm,
1719    value: [u8; 32],
1720}
1721
1722impl Display for SourceFileHash {
1723    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1724        write!(f, "{}=", self.kind)?;
1725        for byte in self.value[0..self.hash_len()].into_iter() {
1726            write!(f, "{byte:02x}")?;
1727        }
1728        Ok(())
1729    }
1730}
1731
1732impl SourceFileHash {
1733    pub fn new_in_memory(kind: SourceFileHashAlgorithm, src: impl AsRef<[u8]>) -> SourceFileHash {
1734        let mut hash = SourceFileHash { kind, value: Default::default() };
1735        let len = hash.hash_len();
1736        let value = &mut hash.value[..len];
1737        let data = src.as_ref();
1738        match kind {
1739            SourceFileHashAlgorithm::Md5 => {
1740                value.copy_from_slice(&Md5::digest(data));
1741            }
1742            SourceFileHashAlgorithm::Sha1 => {
1743                value.copy_from_slice(&Sha1::digest(data));
1744            }
1745            SourceFileHashAlgorithm::Sha256 => {
1746                value.copy_from_slice(&Sha256::digest(data));
1747            }
1748            SourceFileHashAlgorithm::Blake3 => value.copy_from_slice(blake3::hash(data).as_bytes()),
1749        };
1750        hash
1751    }
1752
1753    pub fn new(kind: SourceFileHashAlgorithm, src: impl Read) -> Result<SourceFileHash, io::Error> {
1754        let mut hash = SourceFileHash { kind, value: Default::default() };
1755        let len = hash.hash_len();
1756        let value = &mut hash.value[..len];
1757        // Buffer size is the recommended amount to fully leverage SIMD instructions on AVX-512 as per
1758        // blake3 documentation.
1759        let mut buf = vec![0; 16 * 1024];
1760
1761        fn digest<T>(
1762            mut hasher: T,
1763            mut update: impl FnMut(&mut T, &[u8]),
1764            finish: impl FnOnce(T, &mut [u8]),
1765            mut src: impl Read,
1766            buf: &mut [u8],
1767            value: &mut [u8],
1768        ) -> Result<(), io::Error> {
1769            loop {
1770                let bytes_read = src.read(buf)?;
1771                if bytes_read == 0 {
1772                    break;
1773                }
1774                update(&mut hasher, &buf[0..bytes_read]);
1775            }
1776            finish(hasher, value);
1777            Ok(())
1778        }
1779
1780        match kind {
1781            SourceFileHashAlgorithm::Sha256 => {
1782                digest(
1783                    Sha256::new(),
1784                    |h, b| {
1785                        h.update(b);
1786                    },
1787                    |h, out| out.copy_from_slice(&h.finalize()),
1788                    src,
1789                    &mut buf,
1790                    value,
1791                )?;
1792            }
1793            SourceFileHashAlgorithm::Sha1 => {
1794                digest(
1795                    Sha1::new(),
1796                    |h, b| {
1797                        h.update(b);
1798                    },
1799                    |h, out| out.copy_from_slice(&h.finalize()),
1800                    src,
1801                    &mut buf,
1802                    value,
1803                )?;
1804            }
1805            SourceFileHashAlgorithm::Md5 => {
1806                digest(
1807                    Md5::new(),
1808                    |h, b| {
1809                        h.update(b);
1810                    },
1811                    |h, out| out.copy_from_slice(&h.finalize()),
1812                    src,
1813                    &mut buf,
1814                    value,
1815                )?;
1816            }
1817            SourceFileHashAlgorithm::Blake3 => {
1818                digest(
1819                    blake3::Hasher::new(),
1820                    |h, b| {
1821                        h.update(b);
1822                    },
1823                    |h, out| out.copy_from_slice(h.finalize().as_bytes()),
1824                    src,
1825                    &mut buf,
1826                    value,
1827                )?;
1828            }
1829        }
1830        Ok(hash)
1831    }
1832
1833    /// Check if the stored hash matches the hash of the string.
1834    pub fn matches(&self, src: &str) -> bool {
1835        Self::new_in_memory(self.kind, src.as_bytes()) == *self
1836    }
1837
1838    /// The bytes of the hash.
1839    pub fn hash_bytes(&self) -> &[u8] {
1840        let len = self.hash_len();
1841        &self.value[..len]
1842    }
1843
1844    fn hash_len(&self) -> usize {
1845        match self.kind {
1846            SourceFileHashAlgorithm::Md5 => 16,
1847            SourceFileHashAlgorithm::Sha1 => 20,
1848            SourceFileHashAlgorithm::Sha256 | SourceFileHashAlgorithm::Blake3 => 32,
1849        }
1850    }
1851}
1852
1853#[derive(Clone)]
1854pub enum SourceFileLines {
1855    /// The source file lines, in decoded (random-access) form.
1856    Lines(Vec<RelativeBytePos>),
1857
1858    /// The source file lines, in undecoded difference list form.
1859    Diffs(SourceFileDiffs),
1860}
1861
1862impl SourceFileLines {
1863    pub fn is_lines(&self) -> bool {
1864        matches!(self, SourceFileLines::Lines(_))
1865    }
1866}
1867
1868/// The source file lines in difference list form. This matches the form
1869/// used within metadata, which saves space by exploiting the fact that the
1870/// lines list is sorted and individual lines are usually not that long.
1871///
1872/// We read it directly from metadata and only decode it into `Lines` form
1873/// when necessary. This is a significant performance win, especially for
1874/// small crates where very little of `std`'s metadata is used.
1875#[derive(Clone)]
1876pub struct SourceFileDiffs {
1877    /// Always 1, 2, or 4. Always as small as possible, while being big
1878    /// enough to hold the length of the longest line in the source file.
1879    /// The 1 case is by far the most common.
1880    bytes_per_diff: usize,
1881
1882    /// The number of diffs encoded in `raw_diffs`. Always one less than
1883    /// the number of lines in the source file.
1884    num_diffs: usize,
1885
1886    /// The diffs in "raw" form. Each segment of `bytes_per_diff` length
1887    /// encodes one little-endian diff. Note that they aren't LEB128
1888    /// encoded. This makes for much faster decoding. Besides, the
1889    /// bytes_per_diff==1 case is by far the most common, and LEB128
1890    /// encoding has no effect on that case.
1891    raw_diffs: Vec<u8>,
1892}
1893
1894/// A single source in the [`SourceMap`].
1895pub struct SourceFile {
1896    /// The name of the file that the source came from. Source that doesn't
1897    /// originate from files has names between angle brackets by convention
1898    /// (e.g., `<anon>`).
1899    pub name: FileName,
1900    /// The complete source code.
1901    pub src: Option<Arc<String>>,
1902    /// The source code's hash.
1903    pub src_hash: SourceFileHash,
1904    /// Used to enable cargo to use checksums to check if a crate is fresh rather
1905    /// than mtimes. This might be the same as `src_hash`, and if the requested algorithm
1906    /// is identical we won't compute it twice.
1907    pub checksum_hash: Option<SourceFileHash>,
1908    /// The external source code (used for external crates, which will have a `None`
1909    /// value as `self.src`.
1910    pub external_src: FreezeLock<ExternalSource>,
1911    /// The start position of this source in the `SourceMap`.
1912    pub start_pos: BytePos,
1913    /// The byte length of this source after normalization.
1914    pub normalized_source_len: RelativeBytePos,
1915    /// The byte length of this source before normalization.
1916    pub unnormalized_source_len: u32,
1917    /// Locations of lines beginnings in the source code.
1918    pub lines: FreezeLock<SourceFileLines>,
1919    /// Locations of multi-byte characters in the source code.
1920    pub multibyte_chars: Vec<MultiByteChar>,
1921    /// Locations of characters removed during normalization.
1922    pub normalized_pos: Vec<NormalizedPos>,
1923    /// A hash of the filename & crate-id, used for uniquely identifying source
1924    /// files within the crate graph and for speeding up hashing in incremental
1925    /// compilation.
1926    pub stable_id: StableSourceFileId,
1927    /// Indicates which crate this `SourceFile` was imported from.
1928    pub cnum: CrateNum,
1929}
1930
1931impl Clone for SourceFile {
1932    fn clone(&self) -> Self {
1933        Self {
1934            name: self.name.clone(),
1935            src: self.src.clone(),
1936            src_hash: self.src_hash,
1937            checksum_hash: self.checksum_hash,
1938            external_src: self.external_src.clone(),
1939            start_pos: self.start_pos,
1940            normalized_source_len: self.normalized_source_len,
1941            unnormalized_source_len: self.unnormalized_source_len,
1942            lines: self.lines.clone(),
1943            multibyte_chars: self.multibyte_chars.clone(),
1944            normalized_pos: self.normalized_pos.clone(),
1945            stable_id: self.stable_id,
1946            cnum: self.cnum,
1947        }
1948    }
1949}
1950
1951impl<S: SpanEncoder> Encodable<S> for SourceFile {
1952    fn encode(&self, s: &mut S) {
1953        self.name.encode(s);
1954        self.src_hash.encode(s);
1955        self.checksum_hash.encode(s);
1956        // Do not encode `start_pos` as it's global state for this session.
1957        self.normalized_source_len.encode(s);
1958        self.unnormalized_source_len.encode(s);
1959
1960        // We are always in `Lines` form by the time we reach here.
1961        assert!(self.lines.read().is_lines());
1962        let lines = self.lines();
1963        // Store the length.
1964        s.emit_u32(lines.len() as u32);
1965
1966        // Compute and store the difference list.
1967        if lines.len() != 0 {
1968            let max_line_length = if lines.len() == 1 {
1969                0
1970            } else {
1971                lines
1972                    .array_windows()
1973                    .map(|&[fst, snd]| snd - fst)
1974                    .map(|bp| bp.to_usize())
1975                    .max()
1976                    .unwrap()
1977            };
1978
1979            let bytes_per_diff: usize = match max_line_length {
1980                0..=0xFF => 1,
1981                0x100..=0xFFFF => 2,
1982                _ => 4,
1983            };
1984
1985            // Encode the number of bytes used per diff.
1986            s.emit_u8(bytes_per_diff as u8);
1987
1988            // Encode the first element.
1989            assert_eq!(lines[0], RelativeBytePos(0));
1990
1991            // Encode the difference list.
1992            let diff_iter = lines.array_windows().map(|&[fst, snd]| snd - fst);
1993            let num_diffs = lines.len() - 1;
1994            let mut raw_diffs;
1995            match bytes_per_diff {
1996                1 => {
1997                    raw_diffs = Vec::with_capacity(num_diffs);
1998                    for diff in diff_iter {
1999                        raw_diffs.push(diff.0 as u8);
2000                    }
2001                }
2002                2 => {
2003                    raw_diffs = Vec::with_capacity(bytes_per_diff * num_diffs);
2004                    for diff in diff_iter {
2005                        raw_diffs.extend_from_slice(&(diff.0 as u16).to_le_bytes());
2006                    }
2007                }
2008                4 => {
2009                    raw_diffs = Vec::with_capacity(bytes_per_diff * num_diffs);
2010                    for diff in diff_iter {
2011                        raw_diffs.extend_from_slice(&(diff.0).to_le_bytes());
2012                    }
2013                }
2014                _ => unreachable!(),
2015            }
2016            s.emit_raw_bytes(&raw_diffs);
2017        }
2018
2019        self.multibyte_chars.encode(s);
2020        self.stable_id.encode(s);
2021        self.normalized_pos.encode(s);
2022        self.cnum.encode(s);
2023    }
2024}
2025
2026impl<D: SpanDecoder> Decodable<D> for SourceFile {
2027    fn decode(d: &mut D) -> SourceFile {
2028        let name: FileName = Decodable::decode(d);
2029        let src_hash: SourceFileHash = Decodable::decode(d);
2030        let checksum_hash: Option<SourceFileHash> = Decodable::decode(d);
2031        let normalized_source_len: RelativeBytePos = Decodable::decode(d);
2032        let unnormalized_source_len = Decodable::decode(d);
2033        let lines = {
2034            let num_lines: u32 = Decodable::decode(d);
2035            if num_lines > 0 {
2036                // Read the number of bytes used per diff.
2037                let bytes_per_diff = d.read_u8() as usize;
2038
2039                // Read the difference list.
2040                let num_diffs = num_lines as usize - 1;
2041                let raw_diffs = d.read_raw_bytes(bytes_per_diff * num_diffs).to_vec();
2042                SourceFileLines::Diffs(SourceFileDiffs { bytes_per_diff, num_diffs, raw_diffs })
2043            } else {
2044                SourceFileLines::Lines(vec![])
2045            }
2046        };
2047        let multibyte_chars: Vec<MultiByteChar> = Decodable::decode(d);
2048        let stable_id = Decodable::decode(d);
2049        let normalized_pos: Vec<NormalizedPos> = Decodable::decode(d);
2050        let cnum: CrateNum = Decodable::decode(d);
2051        SourceFile {
2052            name,
2053            start_pos: BytePos::from_u32(0),
2054            normalized_source_len,
2055            unnormalized_source_len,
2056            src: None,
2057            src_hash,
2058            checksum_hash,
2059            // Unused - the metadata decoder will construct
2060            // a new SourceFile, filling in `external_src` properly
2061            external_src: FreezeLock::frozen(ExternalSource::Unneeded),
2062            lines: FreezeLock::new(lines),
2063            multibyte_chars,
2064            normalized_pos,
2065            stable_id,
2066            cnum,
2067        }
2068    }
2069}
2070
2071impl fmt::Debug for SourceFile {
2072    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2073        write!(fmt, "SourceFile({:?})", self.name)
2074    }
2075}
2076
2077/// This is a [SourceFile] identifier that is used to correlate source files between
2078/// subsequent compilation sessions (which is something we need to do during
2079/// incremental compilation).
2080///
2081/// It is a hash value (so we can efficiently consume it when stable-hashing
2082/// spans) that consists of the `FileName` and the `StableCrateId` of the crate
2083/// the source file is from. The crate id is needed because sometimes the
2084/// `FileName` is not unique within the crate graph (think `src/lib.rs`, for
2085/// example).
2086///
2087/// The way the crate-id part is handled is a bit special: source files of the
2088/// local crate are hashed as `(filename, None)`, while source files from
2089/// upstream crates have a hash of `(filename, Some(stable_crate_id))`. This
2090/// is because SourceFiles for the local crate are allocated very early in the
2091/// compilation process when the `StableCrateId` is not yet known. If, due to
2092/// some refactoring of the compiler, the `StableCrateId` of the local crate
2093/// were to become available, it would be better to uniformly make this a
2094/// hash of `(filename, stable_crate_id)`.
2095///
2096/// When `SourceFile`s are exported in crate metadata, the `StableSourceFileId`
2097/// is updated to incorporate the `StableCrateId` of the exporting crate.
2098#[derive(
2099    Debug,
2100    Clone,
2101    Copy,
2102    Hash,
2103    PartialEq,
2104    Eq,
2105    HashStable_Generic,
2106    Encodable,
2107    Decodable,
2108    Default,
2109    PartialOrd,
2110    Ord
2111)]
2112pub struct StableSourceFileId(Hash128);
2113
2114impl StableSourceFileId {
2115    fn from_filename_in_current_crate(filename: &FileName) -> Self {
2116        Self::from_filename_and_stable_crate_id(filename, None)
2117    }
2118
2119    pub fn from_filename_for_export(
2120        filename: &FileName,
2121        local_crate_stable_crate_id: StableCrateId,
2122    ) -> Self {
2123        Self::from_filename_and_stable_crate_id(filename, Some(local_crate_stable_crate_id))
2124    }
2125
2126    fn from_filename_and_stable_crate_id(
2127        filename: &FileName,
2128        stable_crate_id: Option<StableCrateId>,
2129    ) -> Self {
2130        let mut hasher = StableHasher::new();
2131        filename.hash(&mut hasher);
2132        stable_crate_id.hash(&mut hasher);
2133        StableSourceFileId(hasher.finish())
2134    }
2135}
2136
2137impl SourceFile {
2138    const MAX_FILE_SIZE: u32 = u32::MAX - 1;
2139
2140    pub fn new(
2141        name: FileName,
2142        mut src: String,
2143        hash_kind: SourceFileHashAlgorithm,
2144        checksum_hash_kind: Option<SourceFileHashAlgorithm>,
2145    ) -> Result<Self, OffsetOverflowError> {
2146        // Compute the file hash before any normalization.
2147        let src_hash = SourceFileHash::new_in_memory(hash_kind, src.as_bytes());
2148        let checksum_hash = checksum_hash_kind.map(|checksum_hash_kind| {
2149            if checksum_hash_kind == hash_kind {
2150                src_hash
2151            } else {
2152                SourceFileHash::new_in_memory(checksum_hash_kind, src.as_bytes())
2153            }
2154        });
2155        // Capture the original source length before normalization.
2156        let unnormalized_source_len = u32::try_from(src.len()).map_err(|_| OffsetOverflowError)?;
2157        if unnormalized_source_len > Self::MAX_FILE_SIZE {
2158            return Err(OffsetOverflowError);
2159        }
2160
2161        let normalized_pos = normalize_src(&mut src);
2162
2163        let stable_id = StableSourceFileId::from_filename_in_current_crate(&name);
2164        let normalized_source_len = u32::try_from(src.len()).map_err(|_| OffsetOverflowError)?;
2165        if normalized_source_len > Self::MAX_FILE_SIZE {
2166            return Err(OffsetOverflowError);
2167        }
2168
2169        let (lines, multibyte_chars) = analyze_source_file::analyze_source_file(&src);
2170
2171        Ok(SourceFile {
2172            name,
2173            src: Some(Arc::new(src)),
2174            src_hash,
2175            checksum_hash,
2176            external_src: FreezeLock::frozen(ExternalSource::Unneeded),
2177            start_pos: BytePos::from_u32(0),
2178            normalized_source_len: RelativeBytePos::from_u32(normalized_source_len),
2179            unnormalized_source_len,
2180            lines: FreezeLock::frozen(SourceFileLines::Lines(lines)),
2181            multibyte_chars,
2182            normalized_pos,
2183            stable_id,
2184            cnum: LOCAL_CRATE,
2185        })
2186    }
2187
2188    /// This converts the `lines` field to contain `SourceFileLines::Lines` if needed and freezes
2189    /// it.
2190    fn convert_diffs_to_lines_frozen(&self) {
2191        let mut guard = if let Some(guard) = self.lines.try_write() { guard } else { return };
2192
2193        let SourceFileDiffs { bytes_per_diff, num_diffs, raw_diffs } = match &*guard {
2194            SourceFileLines::Diffs(diffs) => diffs,
2195            SourceFileLines::Lines(..) => {
2196                FreezeWriteGuard::freeze(guard);
2197                return;
2198            }
2199        };
2200
2201        // Convert from "diffs" form to "lines" form.
2202        let num_lines = num_diffs + 1;
2203        let mut lines = Vec::with_capacity(num_lines);
2204        let mut line_start = RelativeBytePos(0);
2205        lines.push(line_start);
2206
2207        assert_eq!(*num_diffs, raw_diffs.len() / bytes_per_diff);
2208        match bytes_per_diff {
2209            1 => {
2210                lines.extend(raw_diffs.into_iter().map(|&diff| {
2211                    line_start = line_start + RelativeBytePos(diff as u32);
2212                    line_start
2213                }));
2214            }
2215            2 => {
2216                lines.extend((0..*num_diffs).map(|i| {
2217                    let pos = bytes_per_diff * i;
2218                    let bytes = [raw_diffs[pos], raw_diffs[pos + 1]];
2219                    let diff = u16::from_le_bytes(bytes);
2220                    line_start = line_start + RelativeBytePos(diff as u32);
2221                    line_start
2222                }));
2223            }
2224            4 => {
2225                lines.extend((0..*num_diffs).map(|i| {
2226                    let pos = bytes_per_diff * i;
2227                    let bytes = [
2228                        raw_diffs[pos],
2229                        raw_diffs[pos + 1],
2230                        raw_diffs[pos + 2],
2231                        raw_diffs[pos + 3],
2232                    ];
2233                    let diff = u32::from_le_bytes(bytes);
2234                    line_start = line_start + RelativeBytePos(diff);
2235                    line_start
2236                }));
2237            }
2238            _ => unreachable!(),
2239        }
2240
2241        *guard = SourceFileLines::Lines(lines);
2242
2243        FreezeWriteGuard::freeze(guard);
2244    }
2245
2246    pub fn lines(&self) -> &[RelativeBytePos] {
2247        if let Some(SourceFileLines::Lines(lines)) = self.lines.get() {
2248            return &lines[..];
2249        }
2250
2251        outline(|| {
2252            self.convert_diffs_to_lines_frozen();
2253            if let Some(SourceFileLines::Lines(lines)) = self.lines.get() {
2254                return &lines[..];
2255            }
2256            unreachable!()
2257        })
2258    }
2259
2260    /// Returns the `BytePos` of the beginning of the current line.
2261    pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
2262        let pos = self.relative_position(pos);
2263        let line_index = self.lookup_line(pos).unwrap();
2264        let line_start_pos = self.lines()[line_index];
2265        self.absolute_position(line_start_pos)
2266    }
2267
2268    /// Add externally loaded source.
2269    /// If the hash of the input doesn't match or no input is supplied via None,
2270    /// it is interpreted as an error and the corresponding enum variant is set.
2271    /// The return value signifies whether some kind of source is present.
2272    pub fn add_external_src<F>(&self, get_src: F) -> bool
2273    where
2274        F: FnOnce() -> Option<String>,
2275    {
2276        if !self.external_src.is_frozen() {
2277            let src = get_src();
2278            let src = src.and_then(|mut src| {
2279                // The src_hash needs to be computed on the pre-normalized src.
2280                self.src_hash.matches(&src).then(|| {
2281                    normalize_src(&mut src);
2282                    src
2283                })
2284            });
2285
2286            self.external_src.try_write().map(|mut external_src| {
2287                if let ExternalSource::Foreign {
2288                    kind: src_kind @ ExternalSourceKind::AbsentOk,
2289                    ..
2290                } = &mut *external_src
2291                {
2292                    *src_kind = if let Some(src) = src {
2293                        ExternalSourceKind::Present(Arc::new(src))
2294                    } else {
2295                        ExternalSourceKind::AbsentErr
2296                    };
2297                } else {
2298                    panic!("unexpected state {:?}", *external_src)
2299                }
2300
2301                // Freeze this so we don't try to load the source again.
2302                FreezeWriteGuard::freeze(external_src)
2303            });
2304        }
2305
2306        self.src.is_some() || self.external_src.read().get_source().is_some()
2307    }
2308
2309    /// Gets a line from the list of pre-computed line-beginnings.
2310    /// The line number here is 0-based.
2311    pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
2312        fn get_until_newline(src: &str, begin: usize) -> &str {
2313            // We can't use `lines.get(line_number+1)` because we might
2314            // be parsing when we call this function and thus the current
2315            // line is the last one we have line info for.
2316            let slice = &src[begin..];
2317            match slice.find('\n') {
2318                Some(e) => &slice[..e],
2319                None => slice,
2320            }
2321        }
2322
2323        let begin = {
2324            let line = self.lines().get(line_number).copied()?;
2325            line.to_usize()
2326        };
2327
2328        if let Some(ref src) = self.src {
2329            Some(Cow::from(get_until_newline(src, begin)))
2330        } else {
2331            self.external_src
2332                .borrow()
2333                .get_source()
2334                .map(|src| Cow::Owned(String::from(get_until_newline(src, begin))))
2335        }
2336    }
2337
2338    pub fn is_real_file(&self) -> bool {
2339        self.name.is_real()
2340    }
2341
2342    #[inline]
2343    pub fn is_imported(&self) -> bool {
2344        self.src.is_none()
2345    }
2346
2347    pub fn count_lines(&self) -> usize {
2348        self.lines().len()
2349    }
2350
2351    #[inline]
2352    pub fn absolute_position(&self, pos: RelativeBytePos) -> BytePos {
2353        BytePos::from_u32(pos.to_u32() + self.start_pos.to_u32())
2354    }
2355
2356    #[inline]
2357    pub fn relative_position(&self, pos: BytePos) -> RelativeBytePos {
2358        RelativeBytePos::from_u32(pos.to_u32() - self.start_pos.to_u32())
2359    }
2360
2361    #[inline]
2362    pub fn end_position(&self) -> BytePos {
2363        self.absolute_position(self.normalized_source_len)
2364    }
2365
2366    /// Finds the line containing the given position. The return value is the
2367    /// index into the `lines` array of this `SourceFile`, not the 1-based line
2368    /// number. If the source_file is empty or the position is located before the
2369    /// first line, `None` is returned.
2370    pub fn lookup_line(&self, pos: RelativeBytePos) -> Option<usize> {
2371        self.lines().partition_point(|x| x <= &pos).checked_sub(1)
2372    }
2373
2374    pub fn line_bounds(&self, line_index: usize) -> Range<BytePos> {
2375        if self.is_empty() {
2376            return self.start_pos..self.start_pos;
2377        }
2378
2379        let lines = self.lines();
2380        assert!(line_index < lines.len());
2381        if line_index == (lines.len() - 1) {
2382            self.absolute_position(lines[line_index])..self.end_position()
2383        } else {
2384            self.absolute_position(lines[line_index])..self.absolute_position(lines[line_index + 1])
2385        }
2386    }
2387
2388    /// Returns whether or not the file contains the given `SourceMap` byte
2389    /// position. The position one past the end of the file is considered to be
2390    /// contained by the file. This implies that files for which `is_empty`
2391    /// returns true still contain one byte position according to this function.
2392    #[inline]
2393    pub fn contains(&self, byte_pos: BytePos) -> bool {
2394        byte_pos >= self.start_pos && byte_pos <= self.end_position()
2395    }
2396
2397    #[inline]
2398    pub fn is_empty(&self) -> bool {
2399        self.normalized_source_len.to_u32() == 0
2400    }
2401
2402    /// Calculates the original byte position relative to the start of the file
2403    /// based on the given byte position.
2404    pub fn original_relative_byte_pos(&self, pos: BytePos) -> RelativeBytePos {
2405        let pos = self.relative_position(pos);
2406
2407        // Diff before any records is 0. Otherwise use the previously recorded
2408        // diff as that applies to the following characters until a new diff
2409        // is recorded.
2410        let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) {
2411            Ok(i) => self.normalized_pos[i].diff,
2412            Err(0) => 0,
2413            Err(i) => self.normalized_pos[i - 1].diff,
2414        };
2415
2416        RelativeBytePos::from_u32(pos.0 + diff)
2417    }
2418
2419    /// Calculates a normalized byte position from a byte offset relative to the
2420    /// start of the file.
2421    ///
2422    /// When we get an inline assembler error from LLVM during codegen, we
2423    /// import the expanded assembly code as a new `SourceFile`, which can then
2424    /// be used for error reporting with spans. However the byte offsets given
2425    /// to us by LLVM are relative to the start of the original buffer, not the
2426    /// normalized one. Hence we need to convert those offsets to the normalized
2427    /// form when constructing spans.
2428    pub fn normalized_byte_pos(&self, offset: u32) -> BytePos {
2429        let diff = match self
2430            .normalized_pos
2431            .binary_search_by(|np| (np.pos.0 + np.diff).cmp(&(self.start_pos.0 + offset)))
2432        {
2433            Ok(i) => self.normalized_pos[i].diff,
2434            Err(0) => 0,
2435            Err(i) => self.normalized_pos[i - 1].diff,
2436        };
2437
2438        BytePos::from_u32(self.start_pos.0 + offset - diff)
2439    }
2440
2441    /// Converts an relative `RelativeBytePos` to a `CharPos` relative to the `SourceFile`.
2442    fn bytepos_to_file_charpos(&self, bpos: RelativeBytePos) -> CharPos {
2443        // The number of extra bytes due to multibyte chars in the `SourceFile`.
2444        let mut total_extra_bytes = 0;
2445
2446        for mbc in self.multibyte_chars.iter() {
2447            debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
2448            if mbc.pos < bpos {
2449                // Every character is at least one byte, so we only
2450                // count the actual extra bytes.
2451                total_extra_bytes += mbc.bytes as u32 - 1;
2452                // We should never see a byte position in the middle of a
2453                // character.
2454                assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32);
2455            } else {
2456                break;
2457            }
2458        }
2459
2460        assert!(total_extra_bytes <= bpos.to_u32());
2461        CharPos(bpos.to_usize() - total_extra_bytes as usize)
2462    }
2463
2464    /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a
2465    /// given `RelativeBytePos`.
2466    fn lookup_file_pos(&self, pos: RelativeBytePos) -> (usize, CharPos) {
2467        let chpos = self.bytepos_to_file_charpos(pos);
2468        match self.lookup_line(pos) {
2469            Some(a) => {
2470                let line = a + 1; // Line numbers start at 1
2471                let linebpos = self.lines()[a];
2472                let linechpos = self.bytepos_to_file_charpos(linebpos);
2473                let col = chpos - linechpos;
2474                debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos);
2475                debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos);
2476                debug!("byte is on line: {}", line);
2477                assert!(chpos >= linechpos);
2478                (line, col)
2479            }
2480            None => (0, chpos),
2481        }
2482    }
2483
2484    /// Looks up the file's (1-based) line number, (0-based `CharPos`) column offset, and (0-based)
2485    /// column offset when displayed, for a given `BytePos`.
2486    pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) {
2487        let pos = self.relative_position(pos);
2488        let (line, col_or_chpos) = self.lookup_file_pos(pos);
2489        if line > 0 {
2490            let Some(code) = self.get_line(line - 1) else {
2491                // If we don't have the code available, it is ok as a fallback to return the bytepos
2492                // instead of the "display" column, which is only used to properly show underlines
2493                // in the terminal.
2494                // FIXME: we'll want better handling of this in the future for the sake of tools
2495                // that want to use the display col instead of byte offsets to modify Rust code, but
2496                // that is a problem for another day, the previous code was already incorrect for
2497                // both displaying *and* third party tools using the json output naïvely.
2498                tracing::info!("couldn't find line {line} {:?}", self.name);
2499                return (line, col_or_chpos, col_or_chpos.0);
2500            };
2501            let display_col = code.chars().take(col_or_chpos.0).map(|ch| char_width(ch)).sum();
2502            (line, col_or_chpos, display_col)
2503        } else {
2504            // This is never meant to happen?
2505            (0, col_or_chpos, col_or_chpos.0)
2506        }
2507    }
2508}
2509
2510pub fn char_width(ch: char) -> usize {
2511    // FIXME: `unicode_width` sometimes disagrees with terminals on how wide a `char` is. For now,
2512    // just accept that sometimes the code line will be longer than desired.
2513    match ch {
2514        '\t' => 4,
2515        // Keep the following list in sync with `rustc_errors::emitter::OUTPUT_REPLACEMENTS`. These
2516        // are control points that we replace before printing with a visible codepoint for the sake
2517        // of being able to point at them with underlines.
2518        '\u{0000}' | '\u{0001}' | '\u{0002}' | '\u{0003}' | '\u{0004}' | '\u{0005}'
2519        | '\u{0006}' | '\u{0007}' | '\u{0008}' | '\u{000B}' | '\u{000C}' | '\u{000D}'
2520        | '\u{000E}' | '\u{000F}' | '\u{0010}' | '\u{0011}' | '\u{0012}' | '\u{0013}'
2521        | '\u{0014}' | '\u{0015}' | '\u{0016}' | '\u{0017}' | '\u{0018}' | '\u{0019}'
2522        | '\u{001A}' | '\u{001B}' | '\u{001C}' | '\u{001D}' | '\u{001E}' | '\u{001F}'
2523        | '\u{007F}' | '\u{202A}' | '\u{202B}' | '\u{202D}' | '\u{202E}' | '\u{2066}'
2524        | '\u{2067}' | '\u{2068}' | '\u{202C}' | '\u{2069}' => 1,
2525        _ => unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1),
2526    }
2527}
2528
2529pub fn str_width(s: &str) -> usize {
2530    s.chars().map(char_width).sum()
2531}
2532
2533/// Normalizes the source code and records the normalizations.
2534fn normalize_src(src: &mut String) -> Vec<NormalizedPos> {
2535    let mut normalized_pos = vec![];
2536    remove_bom(src, &mut normalized_pos);
2537    normalize_newlines(src, &mut normalized_pos);
2538    normalized_pos
2539}
2540
2541/// Removes UTF-8 BOM, if any.
2542fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
2543    if src.starts_with('\u{feff}') {
2544        src.drain(..3);
2545        normalized_pos.push(NormalizedPos { pos: RelativeBytePos(0), diff: 3 });
2546    }
2547}
2548
2549/// Replaces `\r\n` with `\n` in-place in `src`.
2550///
2551/// Leaves any occurrences of lone `\r` unchanged.
2552fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
2553    if !src.as_bytes().contains(&b'\r') {
2554        return;
2555    }
2556
2557    // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding.
2558    // While we *can* call `as_mut_vec` and do surgery on the live string
2559    // directly, let's rather steal the contents of `src`. This makes the code
2560    // safe even if a panic occurs.
2561
2562    let mut buf = std::mem::replace(src, String::new()).into_bytes();
2563    let mut gap_len = 0;
2564    let mut tail = buf.as_mut_slice();
2565    let mut cursor = 0;
2566    let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
2567    loop {
2568        let idx = match find_crlf(&tail[gap_len..]) {
2569            None => tail.len(),
2570            Some(idx) => idx + gap_len,
2571        };
2572        tail.copy_within(gap_len..idx, 0);
2573        tail = &mut tail[idx - gap_len..];
2574        if tail.len() == gap_len {
2575            break;
2576        }
2577        cursor += idx - gap_len;
2578        gap_len += 1;
2579        normalized_pos.push(NormalizedPos {
2580            pos: RelativeBytePos::from_usize(cursor + 1),
2581            diff: original_gap + gap_len as u32,
2582        });
2583    }
2584
2585    // Account for removed `\r`.
2586    // After `set_len`, `buf` is guaranteed to contain utf-8 again.
2587    let new_len = buf.len() - gap_len;
2588    unsafe {
2589        buf.set_len(new_len);
2590        *src = String::from_utf8_unchecked(buf);
2591    }
2592
2593    fn find_crlf(src: &[u8]) -> Option<usize> {
2594        let mut search_idx = 0;
2595        while let Some(idx) = find_cr(&src[search_idx..]) {
2596            if src[search_idx..].get(idx + 1) != Some(&b'\n') {
2597                search_idx += idx + 1;
2598                continue;
2599            }
2600            return Some(search_idx + idx);
2601        }
2602        None
2603    }
2604
2605    fn find_cr(src: &[u8]) -> Option<usize> {
2606        src.iter().position(|&b| b == b'\r')
2607    }
2608}
2609
2610// _____________________________________________________________________________
2611// Pos, BytePos, CharPos
2612//
2613
2614pub trait Pos {
2615    fn from_usize(n: usize) -> Self;
2616    fn to_usize(&self) -> usize;
2617    fn from_u32(n: u32) -> Self;
2618    fn to_u32(&self) -> u32;
2619}
2620
2621macro_rules! impl_pos {
2622    (
2623        $(
2624            $(#[$attr:meta])*
2625            $vis:vis struct $ident:ident($inner_vis:vis $inner_ty:ty);
2626        )*
2627    ) => {
2628        $(
2629            $(#[$attr])*
2630            $vis struct $ident($inner_vis $inner_ty);
2631
2632            impl Pos for $ident {
2633                #[inline(always)]
2634                fn from_usize(n: usize) -> $ident {
2635                    $ident(n as $inner_ty)
2636                }
2637
2638                #[inline(always)]
2639                fn to_usize(&self) -> usize {
2640                    self.0 as usize
2641                }
2642
2643                #[inline(always)]
2644                fn from_u32(n: u32) -> $ident {
2645                    $ident(n as $inner_ty)
2646                }
2647
2648                #[inline(always)]
2649                fn to_u32(&self) -> u32 {
2650                    self.0 as u32
2651                }
2652            }
2653
2654            impl Add for $ident {
2655                type Output = $ident;
2656
2657                #[inline(always)]
2658                fn add(self, rhs: $ident) -> $ident {
2659                    $ident(self.0 + rhs.0)
2660                }
2661            }
2662
2663            impl Sub for $ident {
2664                type Output = $ident;
2665
2666                #[inline(always)]
2667                fn sub(self, rhs: $ident) -> $ident {
2668                    $ident(self.0 - rhs.0)
2669                }
2670            }
2671        )*
2672    };
2673}
2674
2675impl_pos! {
2676    /// A byte offset.
2677    ///
2678    /// Keep this small (currently 32-bits), as AST contains a lot of them.
2679    #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
2680    pub struct BytePos(pub u32);
2681
2682    /// A byte offset relative to file beginning.
2683    #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
2684    pub struct RelativeBytePos(pub u32);
2685
2686    /// A character offset.
2687    ///
2688    /// Because of multibyte UTF-8 characters, a byte offset
2689    /// is not equivalent to a character offset. The [`SourceMap`] will convert [`BytePos`]
2690    /// values to `CharPos` values as necessary.
2691    #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
2692    pub struct CharPos(pub usize);
2693}
2694
2695impl<S: Encoder> Encodable<S> for BytePos {
2696    fn encode(&self, s: &mut S) {
2697        s.emit_u32(self.0);
2698    }
2699}
2700
2701impl<D: Decoder> Decodable<D> for BytePos {
2702    fn decode(d: &mut D) -> BytePos {
2703        BytePos(d.read_u32())
2704    }
2705}
2706
2707impl<H: HashStableContext> HashStable<H> for RelativeBytePos {
2708    fn hash_stable(&self, hcx: &mut H, hasher: &mut StableHasher) {
2709        self.0.hash_stable(hcx, hasher);
2710    }
2711}
2712
2713impl<S: Encoder> Encodable<S> for RelativeBytePos {
2714    fn encode(&self, s: &mut S) {
2715        s.emit_u32(self.0);
2716    }
2717}
2718
2719impl<D: Decoder> Decodable<D> for RelativeBytePos {
2720    fn decode(d: &mut D) -> RelativeBytePos {
2721        RelativeBytePos(d.read_u32())
2722    }
2723}
2724
2725// _____________________________________________________________________________
2726// Loc, SourceFileAndLine, SourceFileAndBytePos
2727//
2728
2729/// A source code location used for error reporting.
2730#[derive(Debug, Clone)]
2731pub struct Loc {
2732    /// Information about the original source.
2733    pub file: Arc<SourceFile>,
2734    /// The (1-based) line number.
2735    pub line: usize,
2736    /// The (0-based) column offset.
2737    pub col: CharPos,
2738    /// The (0-based) column offset when displayed.
2739    pub col_display: usize,
2740}
2741
2742// Used to be structural records.
2743#[derive(Debug)]
2744pub struct SourceFileAndLine {
2745    pub sf: Arc<SourceFile>,
2746    /// Index of line, starting from 0.
2747    pub line: usize,
2748}
2749#[derive(Debug)]
2750pub struct SourceFileAndBytePos {
2751    pub sf: Arc<SourceFile>,
2752    pub pos: BytePos,
2753}
2754
2755#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2756pub struct LineInfo {
2757    /// Index of line, starting from 0.
2758    pub line_index: usize,
2759
2760    /// Column in line where span begins, starting from 0.
2761    pub start_col: CharPos,
2762
2763    /// Column in line where span ends, starting from 0, exclusive.
2764    pub end_col: CharPos,
2765}
2766
2767pub struct FileLines {
2768    pub file: Arc<SourceFile>,
2769    pub lines: Vec<LineInfo>,
2770}
2771
2772pub static SPAN_TRACK: AtomicRef<fn(LocalDefId)> = AtomicRef::new(&((|_| {}) as fn(_)));
2773
2774// _____________________________________________________________________________
2775// SpanLinesError, SpanSnippetError, DistinctSources, MalformedSourceMapPositions
2776//
2777
2778pub type FileLinesResult = Result<FileLines, SpanLinesError>;
2779
2780#[derive(Clone, PartialEq, Eq, Debug)]
2781pub enum SpanLinesError {
2782    DistinctSources(Box<DistinctSources>),
2783}
2784
2785#[derive(Clone, PartialEq, Eq, Debug)]
2786pub enum SpanSnippetError {
2787    IllFormedSpan(Span),
2788    DistinctSources(Box<DistinctSources>),
2789    MalformedForSourcemap(MalformedSourceMapPositions),
2790    SourceNotAvailable { filename: FileName },
2791}
2792
2793#[derive(Clone, PartialEq, Eq, Debug)]
2794pub struct DistinctSources {
2795    pub begin: (FileName, BytePos),
2796    pub end: (FileName, BytePos),
2797}
2798
2799#[derive(Clone, PartialEq, Eq, Debug)]
2800pub struct MalformedSourceMapPositions {
2801    pub name: FileName,
2802    pub source_len: usize,
2803    pub begin_pos: BytePos,
2804    pub end_pos: BytePos,
2805}
2806
2807/// Range inside of a `Span` used for diagnostics when we only have access to relative positions.
2808#[derive(Copy, Clone, PartialEq, Eq, Debug)]
2809pub struct InnerSpan {
2810    pub start: usize,
2811    pub end: usize,
2812}
2813
2814impl InnerSpan {
2815    pub fn new(start: usize, end: usize) -> InnerSpan {
2816        InnerSpan { start, end }
2817    }
2818}
2819
2820/// Requirements for a `StableHashingContext` to be used in this crate.
2821///
2822/// This is a hack to allow using the [`HashStable_Generic`] derive macro
2823/// instead of implementing everything in rustc_middle.
2824pub trait HashStableContext {
2825    fn def_path_hash(&self, def_id: DefId) -> DefPathHash;
2826    fn hash_spans(&self) -> bool;
2827    /// Accesses `sess.opts.unstable_opts.incremental_ignore_spans` since
2828    /// we don't have easy access to a `Session`
2829    fn unstable_opts_incremental_ignore_spans(&self) -> bool;
2830    fn def_span(&self, def_id: LocalDefId) -> Span;
2831    fn span_data_to_lines_and_cols(
2832        &mut self,
2833        span: &SpanData,
2834    ) -> Option<(StableSourceFileId, usize, BytePos, usize, BytePos)>;
2835    fn hashing_controls(&self) -> HashingControls;
2836}
2837
2838impl<CTX> HashStable<CTX> for Span
2839where
2840    CTX: HashStableContext,
2841{
2842    /// Hashes a span in a stable way. We can't directly hash the span's `BytePos`
2843    /// fields (that would be similar to hashing pointers, since those are just
2844    /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column)
2845    /// triple, which stays the same even if the containing `SourceFile` has moved
2846    /// within the `SourceMap`.
2847    ///
2848    /// Also note that we are hashing byte offsets for the column, not unicode
2849    /// codepoint offsets. For the purpose of the hash that's sufficient.
2850    /// Also, hashing filenames is expensive so we avoid doing it twice when the
2851    /// span starts and ends in the same file, which is almost always the case.
2852    fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
2853        const TAG_VALID_SPAN: u8 = 0;
2854        const TAG_INVALID_SPAN: u8 = 1;
2855        const TAG_RELATIVE_SPAN: u8 = 2;
2856
2857        if !ctx.hash_spans() {
2858            return;
2859        }
2860
2861        let span = self.data_untracked();
2862        span.ctxt.hash_stable(ctx, hasher);
2863        span.parent.hash_stable(ctx, hasher);
2864
2865        if span.is_dummy() {
2866            Hash::hash(&TAG_INVALID_SPAN, hasher);
2867            return;
2868        }
2869
2870        if let Some(parent) = span.parent {
2871            let def_span = ctx.def_span(parent).data_untracked();
2872            if def_span.contains(span) {
2873                // This span is enclosed in a definition: only hash the relative position.
2874                Hash::hash(&TAG_RELATIVE_SPAN, hasher);
2875                (span.lo - def_span.lo).to_u32().hash_stable(ctx, hasher);
2876                (span.hi - def_span.lo).to_u32().hash_stable(ctx, hasher);
2877                return;
2878            }
2879        }
2880
2881        // If this is not an empty or invalid span, we want to hash the last
2882        // position that belongs to it, as opposed to hashing the first
2883        // position past it.
2884        let Some((file, line_lo, col_lo, line_hi, col_hi)) = ctx.span_data_to_lines_and_cols(&span)
2885        else {
2886            Hash::hash(&TAG_INVALID_SPAN, hasher);
2887            return;
2888        };
2889
2890        Hash::hash(&TAG_VALID_SPAN, hasher);
2891        Hash::hash(&file, hasher);
2892
2893        // Hash both the length and the end location (line/column) of a span. If we
2894        // hash only the length, for example, then two otherwise equal spans with
2895        // different end locations will have the same hash. This can cause a problem
2896        // during incremental compilation wherein a previous result for a query that
2897        // depends on the end location of a span will be incorrectly reused when the
2898        // end location of the span it depends on has changed (see issue #74890). A
2899        // similar analysis applies if some query depends specifically on the length
2900        // of the span, but we only hash the end location. So hash both.
2901
2902        let col_lo_trunc = (col_lo.0 as u64) & 0xFF;
2903        let line_lo_trunc = ((line_lo as u64) & 0xFF_FF_FF) << 8;
2904        let col_hi_trunc = (col_hi.0 as u64) & 0xFF << 32;
2905        let line_hi_trunc = ((line_hi as u64) & 0xFF_FF_FF) << 40;
2906        let col_line = col_lo_trunc | line_lo_trunc | col_hi_trunc | line_hi_trunc;
2907        let len = (span.hi - span.lo).0;
2908        Hash::hash(&col_line, hasher);
2909        Hash::hash(&len, hasher);
2910    }
2911}
2912
2913/// Useful type to use with `Result<>` indicate that an error has already
2914/// been reported to the user, so no need to continue checking.
2915///
2916/// The `()` field is necessary: it is non-`pub`, which means values of this
2917/// type cannot be constructed outside of this crate.
2918#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
2919#[derive(HashStable_Generic)]
2920pub struct ErrorGuaranteed(());
2921
2922impl ErrorGuaranteed {
2923    /// Don't use this outside of `DiagCtxtInner::emit_diagnostic`!
2924    #[deprecated = "should only be used in `DiagCtxtInner::emit_diagnostic`"]
2925    pub fn unchecked_error_guaranteed() -> Self {
2926        ErrorGuaranteed(())
2927    }
2928
2929    pub fn raise_fatal(self) -> ! {
2930        FatalError.raise()
2931    }
2932}
2933
2934impl<E: rustc_serialize::Encoder> Encodable<E> for ErrorGuaranteed {
2935    #[inline]
2936    fn encode(&self, _e: &mut E) {
2937        panic!(
2938            "should never serialize an `ErrorGuaranteed`, as we do not write metadata or \
2939            incremental caches in case errors occurred"
2940        )
2941    }
2942}
2943impl<D: rustc_serialize::Decoder> Decodable<D> for ErrorGuaranteed {
2944    #[inline]
2945    fn decode(_d: &mut D) -> ErrorGuaranteed {
2946        panic!(
2947            "`ErrorGuaranteed` should never have been serialized to metadata or incremental caches"
2948        )
2949    }
2950}