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