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