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