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