Skip to main content

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(core_io_borrowed_buf)]
22#![feature(map_try_insert)]
23#![feature(negative_impls)]
24#![feature(read_buf)]
25#![feature(rustc_attrs)]
26// tidy-alphabetical-end
27
28// The code produced by the `Encodable`/`Decodable` derive macros refer to
29// `rustc_span::Span{Encoder,Decoder}`. That's fine outside this crate, but doesn't work inside
30// this crate without this line making `rustc_span` available.
31extern crate self as rustc_span;
32
33use derive_where::derive_where;
34use rustc_data_structures::{AtomicRef, outline};
35use rustc_macros::{Decodable, Encodable, HashStable_Generic};
36use rustc_serialize::opaque::{FileEncoder, MemDecoder};
37use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
38use tracing::debug;
39pub use unicode_width::UNICODE_VERSION;
40
41mod caching_source_map_view;
42pub mod source_map;
43use source_map::{SourceMap, SourceMapInputs};
44
45pub use self::caching_source_map_view::CachingSourceMapView;
46use crate::fatal_error::FatalError;
47
48pub mod edition;
49use edition::Edition;
50pub mod hygiene;
51use hygiene::Transparency;
52pub use hygiene::{
53    DesugaringKind, ExpnData, ExpnHash, ExpnId, ExpnKind, LocalExpnId, MacroKind, SyntaxContext,
54};
55pub mod def_id;
56use def_id::{CrateNum, DefId, DefIndex, DefPathHash, LOCAL_CRATE, LocalDefId, StableCrateId};
57pub mod edit_distance;
58mod span_encoding;
59pub use span_encoding::{DUMMY_SP, Span};
60
61pub mod symbol;
62pub use symbol::{
63    ByteSymbol, Ident, MacroRulesNormalizedIdent, STDLIB_STABLE_CRATES, Symbol, kw, sym,
64};
65
66mod analyze_source_file;
67pub mod fatal_error;
68
69pub mod profiling;
70
71use std::borrow::Cow;
72use std::cmp::{self, Ordering};
73use std::fmt::Display;
74use std::hash::Hash;
75use std::io::{self, Read};
76use std::ops::{Add, Range, Sub};
77use std::path::{Path, PathBuf};
78use std::str::FromStr;
79use std::sync::Arc;
80use std::{fmt, iter};
81
82use md5::{Digest, Md5};
83use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
84use rustc_data_structures::sync::{FreezeLock, FreezeWriteGuard, Lock};
85use rustc_data_structures::unord::UnordMap;
86use rustc_hashes::{Hash64, Hash128};
87use sha1::Sha1;
88use sha2::Sha256;
89
90#[cfg(test)]
91mod tests;
92
93#[derive(#[automatically_derived]
impl<T: ::core::clone::Clone> ::core::clone::Clone for Spanned<T> {
    #[inline]
    fn clone(&self) -> Spanned<T> {
        Spanned {
            node: ::core::clone::Clone::clone(&self.node),
            span: ::core::clone::Clone::clone(&self.span),
        }
    }
}Clone, const _: () =
    {
        impl<T, __E: ::rustc_span::SpanEncoder>
            ::rustc_serialize::Encodable<__E> for Spanned<T> where
            T: ::rustc_serialize::Encodable<__E> {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    Spanned { node: ref __binding_0, span: ref __binding_1 } =>
                        {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<T, __D: ::rustc_span::SpanDecoder>
            ::rustc_serialize::Decodable<__D> for Spanned<T> where
            T: ::rustc_serialize::Decodable<__D> {
            fn decode(__decoder: &mut __D) -> Self {
                Spanned {
                    node: ::rustc_serialize::Decodable::decode(__decoder),
                    span: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable, #[automatically_derived]
impl<T: ::core::fmt::Debug> ::core::fmt::Debug for Spanned<T> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "Spanned",
            "node", &self.node, "span", &&self.span)
    }
}Debug, #[automatically_derived]
impl<T: ::core::marker::Copy> ::core::marker::Copy for Spanned<T> { }Copy, #[automatically_derived]
impl<T: ::core::cmp::PartialEq> ::core::cmp::PartialEq for Spanned<T> {
    #[inline]
    fn eq(&self, other: &Spanned<T>) -> bool {
        self.node == other.node && self.span == other.span
    }
}PartialEq, #[automatically_derived]
impl<T: ::core::hash::Hash> ::core::hash::Hash for Spanned<T> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.node, state);
        ::core::hash::Hash::hash(&self.span, state)
    }
}Hash, const _: () =
    {
        impl<T, __CTX>
            ::rustc_data_structures::stable_hasher::HashStable<__CTX> for
            Spanned<T> where __CTX: crate::HashStableContext,
            T: ::rustc_data_structures::stable_hasher::HashStable<__CTX> {
            #[inline]
            fn hash_stable(&self, __hcx: &mut __CTX,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::StableHasher) {
                match *self {
                    Spanned { node: ref __binding_0, span: ref __binding_1 } =>
                        {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                        { __binding_1.hash_stable(__hcx, __hasher); }
                    }
                }
            }
        }
    };HashStable_Generic)]
94pub struct Spanned<T> {
95    pub node: T,
96    pub span: Span,
97}
98
99pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
100    Spanned { node: t, span: sp }
101}
102
103pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
104    respan(DUMMY_SP, t)
105}
106
107/// Per-session global variables: this struct is stored in thread-local storage
108/// in such a way that it is accessible without any kind of handle to all
109/// threads within the compilation session, but is not accessible outside the
110/// session.
111pub struct SessionGlobals {
112    symbol_interner: symbol::Interner,
113    span_interner: Lock<span_encoding::SpanInterner>,
114    /// Maps a macro argument token into use of the corresponding metavariable in the macro body.
115    /// Collisions are possible and processed in `maybe_use_metavar_location` on best effort basis.
116    metavar_spans: MetavarSpansMap,
117    hygiene_data: Lock<hygiene::HygieneData>,
118
119    /// The session's source map, if there is one. This field should only be
120    /// used in places where the `Session` is truly not available, such as
121    /// `<Span as Debug>::fmt`.
122    source_map: Option<Arc<SourceMap>>,
123}
124
125impl SessionGlobals {
126    pub fn new(
127        edition: Edition,
128        extra_symbols: &[&'static str],
129        sm_inputs: Option<SourceMapInputs>,
130    ) -> SessionGlobals {
131        SessionGlobals {
132            symbol_interner: symbol::Interner::with_extra_symbols(extra_symbols),
133            span_interner: Lock::new(span_encoding::SpanInterner::default()),
134            metavar_spans: Default::default(),
135            hygiene_data: Lock::new(hygiene::HygieneData::new(edition)),
136            source_map: sm_inputs.map(|inputs| Arc::new(SourceMap::with_inputs(inputs))),
137        }
138    }
139}
140
141pub fn create_session_globals_then<R>(
142    edition: Edition,
143    extra_symbols: &[&'static str],
144    sm_inputs: Option<SourceMapInputs>,
145    f: impl FnOnce() -> R,
146) -> R {
147    if !!SESSION_GLOBALS.is_set() {
    {
        ::core::panicking::panic_fmt(format_args!("SESSION_GLOBALS should never be overwritten! Use another thread if you need another SessionGlobals"));
    }
};assert!(
148        !SESSION_GLOBALS.is_set(),
149        "SESSION_GLOBALS should never be overwritten! \
150         Use another thread if you need another SessionGlobals"
151    );
152    let session_globals = SessionGlobals::new(edition, extra_symbols, sm_inputs);
153    SESSION_GLOBALS.set(&session_globals, f)
154}
155
156pub fn set_session_globals_then<R>(session_globals: &SessionGlobals, f: impl FnOnce() -> R) -> R {
157    if !!SESSION_GLOBALS.is_set() {
    {
        ::core::panicking::panic_fmt(format_args!("SESSION_GLOBALS should never be overwritten! Use another thread if you need another SessionGlobals"));
    }
};assert!(
158        !SESSION_GLOBALS.is_set(),
159        "SESSION_GLOBALS should never be overwritten! \
160         Use another thread if you need another SessionGlobals"
161    );
162    SESSION_GLOBALS.set(session_globals, f)
163}
164
165/// No source map.
166pub fn create_session_if_not_set_then<R, F>(edition: Edition, f: F) -> R
167where
168    F: FnOnce(&SessionGlobals) -> R,
169{
170    if !SESSION_GLOBALS.is_set() {
171        let session_globals = SessionGlobals::new(edition, &[], None);
172        SESSION_GLOBALS.set(&session_globals, || SESSION_GLOBALS.with(f))
173    } else {
174        SESSION_GLOBALS.with(f)
175    }
176}
177
178#[inline]
179pub fn with_session_globals<R, F>(f: F) -> R
180where
181    F: FnOnce(&SessionGlobals) -> R,
182{
183    SESSION_GLOBALS.with(f)
184}
185
186/// Default edition, no source map.
187pub fn create_default_session_globals_then<R>(f: impl FnOnce() -> R) -> R {
188    create_session_globals_then(edition::DEFAULT_EDITION, &[], None, f)
189}
190
191// If this ever becomes non thread-local, `decode_syntax_context`
192// and `decode_expn_id` will need to be updated to handle concurrent
193// deserialization.
194static SESSION_GLOBALS: ::scoped_tls::ScopedKey<SessionGlobals> =
    ::scoped_tls::ScopedKey {
        inner: {
            const FOO: ::std::thread::LocalKey<::std::cell::Cell<*const ()>> =
                {
                    const __RUST_STD_INTERNAL_INIT: ::std::cell::Cell<*const ()>
                        =
                        { ::std::cell::Cell::new(::std::ptr::null()) };
                    unsafe {
                        ::std::thread::LocalKey::new(const {
                                    if ::std::mem::needs_drop::<::std::cell::Cell<*const ()>>()
                                        {
                                        |_|
                                            {
                                                #[thread_local]
                                                static __RUST_STD_INTERNAL_VAL:
                                                    ::std::thread::local_impl::EagerStorage<::std::cell::Cell<*const ()>>
                                                    =
                                                    ::std::thread::local_impl::EagerStorage::new(__RUST_STD_INTERNAL_INIT);
                                                __RUST_STD_INTERNAL_VAL.get()
                                            }
                                    } else {
                                        |_|
                                            {
                                                #[thread_local]
                                                static __RUST_STD_INTERNAL_VAL: ::std::cell::Cell<*const ()>
                                                    =
                                                    __RUST_STD_INTERNAL_INIT;
                                                &__RUST_STD_INTERNAL_VAL
                                            }
                                    }
                                })
                    }
                };
            &FOO
        },
        _marker: ::std::marker::PhantomData,
    };scoped_tls::scoped_thread_local!(static SESSION_GLOBALS: SessionGlobals);
195
196#[derive(#[automatically_derived]
impl ::core::default::Default for MetavarSpansMap {
    #[inline]
    fn default() -> MetavarSpansMap {
        MetavarSpansMap(::core::default::Default::default())
    }
}Default)]
197pub struct MetavarSpansMap(FreezeLock<UnordMap<Span, (Span, bool)>>);
198
199impl MetavarSpansMap {
200    pub fn insert(&self, span: Span, var_span: Span) -> bool {
201        match self.0.write().try_insert(span, (var_span, false)) {
202            Ok(_) => true,
203            Err(entry) => entry.entry.get().0 == var_span,
204        }
205    }
206
207    /// Read a span and record that it was read.
208    pub fn get(&self, span: Span) -> Option<Span> {
209        if let Some(mut mspans) = self.0.try_write() {
210            if let Some((var_span, read)) = mspans.get_mut(&span) {
211                *read = true;
212                Some(*var_span)
213            } else {
214                None
215            }
216        } else {
217            if let Some((span, true)) = self.0.read().get(&span) { Some(*span) } else { None }
218        }
219    }
220
221    /// Freeze the set, and return the spans which have been read.
222    ///
223    /// After this is frozen, no spans that have not been read can be read.
224    pub fn freeze_and_get_read_spans(&self) -> UnordMap<Span, Span> {
225        self.0.freeze().items().filter(|(_, (_, b))| *b).map(|(s1, (s2, _))| (*s1, *s2)).collect()
226    }
227}
228
229#[inline]
230pub fn with_metavar_spans<R>(f: impl FnOnce(&MetavarSpansMap) -> R) -> R {
231    with_session_globals(|session_globals| f(&session_globals.metavar_spans))
232}
233
234#[doc =
r" Scopes used to determined if it need to apply to `--remap-path-prefix`"]
pub struct RemapPathScopeComponents(<RemapPathScopeComponents as
    ::bitflags::__private::PublicFlags>::Internal);
#[automatically_derived]
impl ::core::fmt::Debug for RemapPathScopeComponents {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f,
            "RemapPathScopeComponents", &&self.0)
    }
}
#[automatically_derived]
impl ::core::cmp::Eq for RemapPathScopeComponents {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _:
                ::core::cmp::AssertParamIsEq<<RemapPathScopeComponents as
                ::bitflags::__private::PublicFlags>::Internal>;
    }
}
#[automatically_derived]
impl ::core::marker::StructuralPartialEq for RemapPathScopeComponents { }
#[automatically_derived]
impl ::core::cmp::PartialEq for RemapPathScopeComponents {
    #[inline]
    fn eq(&self, other: &RemapPathScopeComponents) -> bool {
        self.0 == other.0
    }
}
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for RemapPathScopeComponents { }
#[automatically_derived]
impl ::core::clone::Clone for RemapPathScopeComponents {
    #[inline]
    fn clone(&self) -> RemapPathScopeComponents {
        let _:
                ::core::clone::AssertParamIsClone<<RemapPathScopeComponents as
                ::bitflags::__private::PublicFlags>::Internal>;
        *self
    }
}
#[automatically_derived]
impl ::core::marker::Copy for RemapPathScopeComponents { }
#[automatically_derived]
impl ::core::cmp::Ord for RemapPathScopeComponents {
    #[inline]
    fn cmp(&self, other: &RemapPathScopeComponents) -> ::core::cmp::Ordering {
        ::core::cmp::Ord::cmp(&self.0, &other.0)
    }
}
#[automatically_derived]
impl ::core::cmp::PartialOrd for RemapPathScopeComponents {
    #[inline]
    fn partial_cmp(&self, other: &RemapPathScopeComponents)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::cmp::PartialOrd::partial_cmp(&self.0, &other.0)
    }
}
#[automatically_derived]
impl ::core::hash::Hash for RemapPathScopeComponents {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}
impl RemapPathScopeComponents {
    #[doc = r" Apply remappings to the expansion of `std::file!()` macro"]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const MACRO: Self = Self::from_bits_retain(1 << 0);
    #[doc = r" Apply remappings to printed compiler diagnostics"]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const DIAGNOSTICS: Self = Self::from_bits_retain(1 << 1);
    #[doc = r" Apply remappings to debug information"]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const DEBUGINFO: Self = Self::from_bits_retain(1 << 3);
    #[doc = r" Apply remappings to coverage information"]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const COVERAGE: Self = Self::from_bits_retain(1 << 4);
    #[doc = r" Apply remappings to documentation information"]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const DOCUMENTATION: Self = Self::from_bits_retain(1 << 5);
    #[doc =
    r" An alias for `macro`, `debuginfo` and `coverage`. This ensures all paths in compiled"]
    #[doc =
    r" executables, libraries and objects are remapped but not elsewhere."]
    #[allow(deprecated, non_upper_case_globals,)]
    pub const OBJECT: Self =
        Self::from_bits_retain(Self::MACRO.bits() | Self::DEBUGINFO.bits() |
                Self::COVERAGE.bits());
}
impl ::bitflags::Flags for RemapPathScopeComponents {
    const FLAGS: &'static [::bitflags::Flag<RemapPathScopeComponents>] =
        &[{

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("MACRO",
                            RemapPathScopeComponents::MACRO)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("DIAGNOSTICS",
                            RemapPathScopeComponents::DIAGNOSTICS)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("DEBUGINFO",
                            RemapPathScopeComponents::DEBUGINFO)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("COVERAGE",
                            RemapPathScopeComponents::COVERAGE)
                    },
                    {

                        #[allow(deprecated, non_upper_case_globals,)]
                        ::bitflags::Flag::new("DOCUMENTATION",
                            RemapPathScopeComponents::DOCUMENTATION)
                    },
                    {

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