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