rustc_span/
lib.rs

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