1#![allow(internal_features)]
20#![cfg_attr(target_arch = "loongarch64", feature(stdarch_loongarch))]
21#![feature(core_io_borrowed_buf)]
22#![feature(decl_macro)]
23#![feature(diagnostic_on_unknown)]
24#![feature(map_try_insert)]
25#![feature(negative_impls)]
26#![feature(read_buf)]
27#![feature(rustc_attrs)]
28extern crate self as rustc_span;
34
35use derive_where::derive_where;
36use rustc_data_structures::stable_hash::StableHashCtxt;
37use rustc_data_structures::{AtomicRef, outline};
38use rustc_macros::{Decodable, Encodable, StableHash};
39use rustc_serialize::opaque::mem_encoder::MemEncoder;
40use rustc_serialize::opaque::{FileEncoder, MemDecoder};
41use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
42use tracing::debug;
43pub use unicode_width::UNICODE_VERSION;
44
45mod caching_source_map_view;
46pub mod source_map;
47use source_map::{SourceMap, SourceMapInputs};
48
49pub use self::caching_source_map_view::CachingSourceMapView;
50use crate::fatal_error::FatalError;
51
52pub mod edition;
53use edition::Edition;
54pub mod hygiene;
55use hygiene::Transparency;
56pub use hygiene::{
57 DesugaringKind, ExpnData, ExpnHash, ExpnId, ExpnKind, LocalExpnId, MacroKind, SyntaxContext,
58};
59pub mod def_id;
60use def_id::{CrateNum, DefId, DefIndex, LOCAL_CRATE, LocalDefId, StableCrateId};
61pub mod edit_distance;
62mod span_encoding;
63pub use span_encoding::{DUMMY_SP, Span};
64
65pub mod symbol;
66pub use symbol::{
67 ByteSymbol, Ident, MacroRulesNormalizedIdent, STDLIB_STABLE_CRATES, Symbol, kw, sym,
68};
69
70mod analyze_source_file;
71pub mod fatal_error;
72
73pub mod profiling;
74
75pub mod macros;
76use std::borrow::Cow;
77use std::cmp::{self, Ordering};
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::{fmt, iter};
86
87pub use macros::{bug, span_bug};
88use md5::{Digest, Md5};
89use rustc_data_structures::stable_hash::{StableHash, StableHasher};
90use rustc_data_structures::sync::{FreezeLock, FreezeWriteGuard, Lock};
91use rustc_data_structures::unord::UnordMap;
92use rustc_hashes::{Hash64, Hash128};
93use sha1::Sha1;
94use sha2::Sha256;
95
96#[cfg(test)]
97mod tests;
98
99#[derive(#[automatically_derived]
impl<T: ::core::clone::Clone> ::core::clone::Clone for Spanned<T> {
#[inline]
fn clone(&self) -> Self {
Self {
node: ::core::clone::Clone::clone(&self.node),
span: ::core::clone::Clone::clone(&self.span),
}
}
}Clone, const _: () =
{
impl<T, __E: ::rustc_span::SpanEncoder>
::rustc_serialize::Encodable<__E> for Spanned<T> where
T: ::rustc_serialize::Encodable<__E> {
fn encode(&self, __encoder: &mut __E) {
let Spanned { node: ref __binding_0, span: ref __binding_1 } =
*self;
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
}
}
};Encodable, const _: () =
{
impl<T, __D: ::rustc_span::SpanDecoder>
::rustc_serialize::Decodable<__D> for Spanned<T> where
T: ::rustc_serialize::Decodable<__D> {
fn decode(__decoder: &mut __D) -> Self {
Spanned {
node: ::rustc_serialize::Decodable::decode(__decoder),
span: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable, #[automatically_derived]
impl<T: ::core::fmt::Debug> ::core::fmt::Debug for Spanned<T> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "Spanned",
"node", &self.node, "span", &&self.span)
}
}Debug, #[automatically_derived]
impl<T: ::core::marker::Copy> ::core::marker::Copy for Spanned<T> { }Copy, #[automatically_derived]
impl<T: ::core::cmp::PartialEq> ::core::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)]
100pub struct Spanned<T> {
101 pub node: T,
102 pub span: Span,
103}
104
105pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
106 Spanned { node: t, span: sp }
107}
108
109pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
110 respan(DUMMY_SP, t)
111}
112
113pub struct SessionGlobals {
118 symbol_interner: symbol::Interner,
119 span_interner: Lock<span_encoding::SpanInterner>,
120 metavar_spans: MetavarSpansMap,
123 hygiene_data: Lock<hygiene::HygieneData>,
124
125 source_map: Option<Arc<SourceMap>>,
129}
130
131impl SessionGlobals {
132 pub fn new(
133 edition: Edition,
134 extra_symbols: &[&'static str],
135 sm_inputs: Option<SourceMapInputs>,
136 ) -> SessionGlobals {
137 SessionGlobals {
138 symbol_interner: symbol::Interner::with_extra_symbols(extra_symbols),
139 span_interner: Lock::new(span_encoding::SpanInterner::default()),
140 metavar_spans: Default::default(),
141 hygiene_data: Lock::new(hygiene::HygieneData::new(edition)),
142 source_map: sm_inputs.map(|inputs| Arc::new(SourceMap::with_inputs(inputs))),
143 }
144 }
145}
146
147pub fn create_session_globals_then<R>(
148 edition: Edition,
149 extra_symbols: &[&'static str],
150 sm_inputs: Option<SourceMapInputs>,
151 f: impl FnOnce() -> R,
152) -> R {
153 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!(
154 !SESSION_GLOBALS.is_set(),
155 "SESSION_GLOBALS should never be overwritten! \
156 Use another thread if you need another SessionGlobals"
157 );
158 let session_globals = SessionGlobals::new(edition, extra_symbols, sm_inputs);
159 SESSION_GLOBALS.set(&session_globals, f)
160}
161
162pub fn set_session_globals_then<R>(session_globals: &SessionGlobals, f: impl FnOnce() -> R) -> R {
163 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!(
164 !SESSION_GLOBALS.is_set(),
165 "SESSION_GLOBALS should never be overwritten! \
166 Use another thread if you need another SessionGlobals"
167 );
168 SESSION_GLOBALS.set(session_globals, f)
169}
170
171pub fn create_session_if_not_set_then<R, F>(edition: Edition, f: F) -> R
173where
174 F: FnOnce(&SessionGlobals) -> R,
175{
176 if !SESSION_GLOBALS.is_set() {
177 let session_globals = SessionGlobals::new(edition, &[], None);
178 SESSION_GLOBALS.set(&session_globals, || SESSION_GLOBALS.with(f))
179 } else {
180 SESSION_GLOBALS.with(f)
181 }
182}
183
184#[inline]
185pub fn with_session_globals<R, F>(f: F) -> R
186where
187 F: FnOnce(&SessionGlobals) -> R,
188{
189 SESSION_GLOBALS.with(f)
190}
191
192pub fn create_default_session_globals_then<R>(f: impl FnOnce() -> R) -> R {
194 create_session_globals_then(edition::DEFAULT_EDITION, &[], None, f)
195}
196
197static SESSION_GLOBALS: ::scoped_tls::ScopedKey<SessionGlobals> =
::scoped_tls::ScopedKey {
inner: {
const FOO: ::std::thread::LocalKey<::std::cell::Cell<*const ()>> =
{
const __RUST_STD_INTERNAL_INIT: ::std::cell::Cell<*const ()>
=
{ ::std::cell::Cell::new(::std::ptr::null()) };
unsafe {
::std::thread::LocalKey::new(const {
if ::std::mem::needs_drop::<::std::cell::Cell<*const ()>>()
{
|_|
{
#[thread_local]
static __RUST_STD_INTERNAL_VAL:
::std::thread::local_impl::EagerStorage<::std::cell::Cell<*const ()>>
=
::std::thread::local_impl::EagerStorage::new(__RUST_STD_INTERNAL_INIT);
__RUST_STD_INTERNAL_VAL.get()
}
} else {
|_|
{
#[thread_local]
static __RUST_STD_INTERNAL_VAL: ::std::cell::Cell<*const ()>
=
__RUST_STD_INTERNAL_INIT;
&__RUST_STD_INTERNAL_VAL
}
}
})
}
};
&FOO
},
_marker: ::std::marker::PhantomData,
};scoped_tls::scoped_thread_local!(static SESSION_GLOBALS: SessionGlobals);
201
202#[derive(#[automatically_derived]
impl ::core::default::Default for MetavarSpansMap {
#[inline]
fn default() -> Self { Self(::core::default::Default::default()) }
}Default)]
203pub struct MetavarSpansMap(FreezeLock<UnordMap<Span, (Span, bool)>>);
204
205impl MetavarSpansMap {
206 pub fn insert(&self, span: Span, var_span: Span) -> bool {
207 match self.0.write().try_insert(span, (var_span, false)) {
208 Ok(_) => true,
209 Err(entry) => entry.entry.get().0 == var_span,
210 }
211 }
212
213 pub fn get(&self, span: Span) -> Option<Span> {
215 if let Some(mut mspans) = self.0.try_write() {
216 if let Some((var_span, read)) = mspans.get_mut(&span) {
217 *read = true;
218 Some(*var_span)
219 } else {
220 None
221 }
222 } else {
223 if let Some((span, true)) = self.0.read().get(&span) { Some(*span) } else { None }
224 }
225 }
226
227 pub fn freeze_and_get_read_spans(&self) -> UnordMap<Span, Span> {
231 self.0.freeze().items().filter(|(_, (_, b))| *b).map(|(s1, (s2, _))| (*s1, *s2)).collect()
232 }
233}
234
235#[inline]
236pub fn with_metavar_spans<R>(f: impl FnOnce(&MetavarSpansMap) -> R) -> R {
237 with_session_globals(|session_globals| f(&session_globals.metavar_spans))
238}
239
240#[doc =
r" Scopes used to determined if it need to apply to `--remap-path-prefix`"]
pub struct RemapPathScopeComponents(<RemapPathScopeComponents as
::bitflags::__private::PublicFlags>::Internal);
#[automatically_derived]
impl ::core::fmt::Debug for RemapPathScopeComponents {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"RemapPathScopeComponents", &&self.0)
}
}
#[automatically_derived]
impl ::core::cmp::Eq for RemapPathScopeComponents {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _:
::core::cmp::AssertParamIsEq<<RemapPathScopeComponents as
::bitflags::__private::PublicFlags>::Internal>;
}
}
#[automatically_derived]
impl ::core::marker::StructuralPartialEq for RemapPathScopeComponents { }
#[automatically_derived]
impl ::core::cmp::PartialEq for RemapPathScopeComponents {
#[inline]
fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for RemapPathScopeComponents { }
#[automatically_derived]
impl ::core::clone::Clone for RemapPathScopeComponents {
#[inline]
fn clone(&self) -> Self {
let _:
::core::clone::AssertParamIsClone<<RemapPathScopeComponents as
::bitflags::__private::PublicFlags>::Internal>;
*self
}
}
#[automatically_derived]
impl ::core::marker::Copy for RemapPathScopeComponents { }
#[automatically_derived]
impl ::core::cmp::Ord for RemapPathScopeComponents {
#[inline]
fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
::core::cmp::Ord::cmp(&self.0, &other.0)
}
}
#[automatically_derived]
impl ::core::cmp::PartialOrd for RemapPathScopeComponents {
#[inline]
fn partial_cmp(&self, other: &Self)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}
#[automatically_derived]
impl ::core::hash::Hash for RemapPathScopeComponents {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}
impl RemapPathScopeComponents {
#[doc = r" Apply remappings to the expansion of `std::file!()` macro"]
#[allow(deprecated, non_upper_case_globals,)]
pub const MACRO: Self = Self::from_bits_retain(1 << 0);
#[doc = r" Apply remappings to printed compiler diagnostics"]
#[allow(deprecated, non_upper_case_globals,)]
pub const DIAGNOSTICS: Self = Self::from_bits_retain(1 << 1);
#[doc = r" Apply remappings to debug information"]
#[allow(deprecated, non_upper_case_globals,)]
pub const DEBUGINFO: Self = Self::from_bits_retain(1 << 3);
#[doc = r" Apply remappings to coverage information"]
#[allow(deprecated, non_upper_case_globals,)]
pub const COVERAGE: Self = Self::from_bits_retain(1 << 4);
#[doc = r" Apply remappings to documentation information"]
#[allow(deprecated, non_upper_case_globals,)]
pub const DOCUMENTATION: Self = Self::from_bits_retain(1 << 5);
#[doc =
r" An alias for `macro`, `debuginfo` and `coverage`. This ensures all paths in compiled"]
#[doc =
r" executables, libraries and objects are remapped but not elsewhere."]
#[allow(deprecated, non_upper_case_globals,)]
pub const OBJECT: Self =
Self::from_bits_retain(Self::MACRO.bits() | Self::DEBUGINFO.bits() |
Self::COVERAGE.bits());
}
impl ::bitflags::Flags for RemapPathScopeComponents {
const FLAGS: &'static [::bitflags::Flag<RemapPathScopeComponents>] =
&[{
#[allow(deprecated, non_upper_case_globals,)]
::bitflags::Flag::new("MACRO",
RemapPathScopeComponents::MACRO)
},
{
#[allow(deprecated, non_upper_case_globals,)]
::bitflags::Flag::new("DIAGNOSTICS",
RemapPathScopeComponents::DIAGNOSTICS)
},
{
#[allow(deprecated, non_upper_case_globals,)]
::bitflags::Flag::new("DEBUGINFO",
RemapPathScopeComponents::DEBUGINFO)
},
{
#[allow(deprecated, non_upper_case_globals,)]
::bitflags::Flag::new("COVERAGE",
RemapPathScopeComponents::COVERAGE)
},
{
#[allow(deprecated, non_upper_case_globals,)]
::bitflags::Flag::new("DOCUMENTATION",
RemapPathScopeComponents::DOCUMENTATION)
},
{
#[allow(deprecated, non_upper_case_globals,)]
::bitflags::Flag::new("OBJECT",
RemapPathScopeComponents::OBJECT)
}];
type Bits = u8;
fn bits(&self) -> u8 { RemapPathScopeComponents::bits(self) }
fn from_bits_retain(bits: u8) -> RemapPathScopeComponents {
RemapPathScopeComponents::from_bits_retain(bits)
}
}
#[allow(dead_code, deprecated, unused_doc_comments, unused_attributes,
unused_mut, unused_imports, non_upper_case_globals, clippy ::
assign_op_pattern, clippy :: indexing_slicing, clippy :: same_name_method,
clippy :: iter_without_into_iter,)]
const _: () =
{
#[repr(transparent)]
pub struct InternalBitFlags(u8);
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for InternalBitFlags { }
#[automatically_derived]
impl ::core::clone::Clone for InternalBitFlags {
#[inline]
fn clone(&self) -> 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 {
#[inline]
pub const fn empty() -> Self {
Self(<u8 as ::bitflags::Bits>::EMPTY)
}
#[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)
}
#[inline]
pub const fn bits(&self) -> u8 { self.0 }
#[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 }
}
#[inline]
pub const fn from_bits_truncate(bits: u8) -> Self {
Self(bits & Self::all().0)
}
#[inline]
pub const fn from_bits_retain(bits: u8) -> Self { Self(bits) }
#[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
}
#[inline]
pub const fn is_empty(&self) -> bool {
self.0 == <u8 as ::bitflags::Bits>::EMPTY
}
#[inline]
pub const fn is_all(&self) -> bool {
Self::all().0 | self.0 == self.0
}
#[inline]
pub const fn intersects(&self, other: Self) -> bool {
self.0 & other.0 != <u8 as ::bitflags::Bits>::EMPTY
}
#[inline]
pub const fn contains(&self, other: Self) -> bool {
self.0 & other.0 == other.0
}
#[inline]
pub fn insert(&mut self, other: Self) {
*self = Self(self.0).union(other);
}
#[inline]
pub fn remove(&mut self, other: Self) {
*self = Self(self.0).difference(other);
}
#[inline]
pub fn toggle(&mut self, other: Self) {
*self = Self(self.0).symmetric_difference(other);
}
#[inline]
pub fn set(&mut self, other: Self, value: bool) {
if value { self.insert(other); } else { self.remove(other); }
}
#[inline]
#[must_use]
pub const fn intersection(self, other: Self) -> Self {
Self(self.0 & other.0)
}
#[inline]
#[must_use]
pub const fn union(self, other: Self) -> Self {
Self(self.0 | other.0)
}
#[inline]
#[must_use]
pub const fn difference(self, other: Self) -> Self {
Self(self.0 & !other.0)
}
#[inline]
#[must_use]
pub const fn symmetric_difference(self, other: Self) -> Self {
Self(self.0 ^ other.0)
}
#[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;
#[inline]
fn bitor(self, other: InternalBitFlags) -> Self {
self.union(other)
}
}
impl ::bitflags::__private::core::ops::BitOrAssign for
InternalBitFlags {
#[inline]
fn bitor_assign(&mut self, other: Self) { self.insert(other); }
}
impl ::bitflags::__private::core::ops::BitXor for InternalBitFlags {
type Output = Self;
#[inline]
fn bitxor(self, other: Self) -> Self {
self.symmetric_difference(other)
}
}
impl ::bitflags::__private::core::ops::BitXorAssign for
InternalBitFlags {
#[inline]
fn bitxor_assign(&mut self, other: Self) { self.toggle(other); }
}
impl ::bitflags::__private::core::ops::BitAnd for InternalBitFlags {
type Output = Self;
#[inline]
fn bitand(self, other: Self) -> Self { self.intersection(other) }
}
impl ::bitflags::__private::core::ops::BitAndAssign for
InternalBitFlags {
#[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;
#[inline]
fn sub(self, other: Self) -> Self { self.difference(other) }
}
impl ::bitflags::__private::core::ops::SubAssign for InternalBitFlags
{
#[inline]
fn sub_assign(&mut self, other: Self) { self.remove(other); }
}
impl ::bitflags::__private::core::ops::Not for InternalBitFlags {
type Output = Self;
#[inline]
fn not(self) -> Self { self.complement() }
}
impl ::bitflags::__private::core::iter::Extend<InternalBitFlags> for
InternalBitFlags {
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 {
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 {
#[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()))
}
#[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 {
#[inline]
pub fn bits_mut(&mut self) -> &mut u8 { &mut self.0 }
}
#[allow(dead_code, deprecated, unused_attributes)]
impl RemapPathScopeComponents {
#[inline]
pub const fn empty() -> Self { Self(InternalBitFlags::empty()) }
#[inline]
pub const fn all() -> Self { Self(InternalBitFlags::all()) }
#[inline]
pub const fn bits(&self) -> u8 { self.0.bits() }
#[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,
}
}
#[inline]
pub const fn from_bits_truncate(bits: u8) -> Self {
Self(InternalBitFlags::from_bits_truncate(bits))
}
#[inline]
pub const fn from_bits_retain(bits: u8) -> Self {
Self(InternalBitFlags::from_bits_retain(bits))
}
#[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,
}
}
#[inline]
pub const fn is_empty(&self) -> bool { self.0.is_empty() }
#[inline]
pub const fn is_all(&self) -> bool { self.0.is_all() }
#[inline]
pub const fn intersects(&self, other: Self) -> bool {
self.0.intersects(other.0)
}
#[inline]
pub const fn contains(&self, other: Self) -> bool {
self.0.contains(other.0)
}
#[inline]
pub fn insert(&mut self, other: Self) { self.0.insert(other.0) }
#[inline]
pub fn remove(&mut self, other: Self) { self.0.remove(other.0) }
#[inline]
pub fn toggle(&mut self, other: Self) { self.0.toggle(other.0) }
#[inline]
pub fn set(&mut self, other: Self, value: bool) {
self.0.set(other.0, value)
}
#[inline]
#[must_use]
pub const fn intersection(self, other: Self) -> Self {
Self(self.0.intersection(other.0))
}
#[inline]
#[must_use]
pub const fn union(self, other: Self) -> Self {
Self(self.0.union(other.0))
}
#[inline]
#[must_use]
pub const fn difference(self, other: Self) -> Self {
Self(self.0.difference(other.0))
}
#[inline]
#[must_use]
pub const fn symmetric_difference(self, other: Self) -> Self {
Self(self.0.symmetric_difference(other.0))
}
#[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;
#[inline]
fn bitor(self, other: RemapPathScopeComponents) -> Self {
self.union(other)
}
}
impl ::bitflags::__private::core::ops::BitOrAssign for
RemapPathScopeComponents {
#[inline]
fn bitor_assign(&mut self, other: Self) { self.insert(other); }
}
impl ::bitflags::__private::core::ops::BitXor for
RemapPathScopeComponents {
type Output = Self;
#[inline]
fn bitxor(self, other: Self) -> Self {
self.symmetric_difference(other)
}
}
impl ::bitflags::__private::core::ops::BitXorAssign for
RemapPathScopeComponents {
#[inline]
fn bitxor_assign(&mut self, other: Self) { self.toggle(other); }
}
impl ::bitflags::__private::core::ops::BitAnd for
RemapPathScopeComponents {
type Output = Self;
#[inline]
fn bitand(self, other: Self) -> Self { self.intersection(other) }
}
impl ::bitflags::__private::core::ops::BitAndAssign for
RemapPathScopeComponents {
#[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;
#[inline]
fn sub(self, other: Self) -> Self { self.difference(other) }
}
impl ::bitflags::__private::core::ops::SubAssign for
RemapPathScopeComponents {
#[inline]
fn sub_assign(&mut self, other: Self) { self.remove(other); }
}
impl ::bitflags::__private::core::ops::Not for
RemapPathScopeComponents {
type Output = Self;
#[inline]
fn not(self) -> Self { self.complement() }
}
impl ::bitflags::__private::core::iter::Extend<RemapPathScopeComponents>
for RemapPathScopeComponents {
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 {
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 {
#[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()))
}
#[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! {
241 #[derive(Debug, Eq, PartialEq, Clone, Copy, Ord, PartialOrd, Hash)]
243 pub struct RemapPathScopeComponents: u8 {
244 const MACRO = 1 << 0;
246 const DIAGNOSTICS = 1 << 1;
248 const DEBUGINFO = 1 << 3;
250 const COVERAGE = 1 << 4;
252 const DOCUMENTATION = 1 << 5;
254
255 const OBJECT = Self::MACRO.bits() | Self::DEBUGINFO.bits() | Self::COVERAGE.bits();
258 }
259}
260
261impl<E: Encoder> Encodable<E> for RemapPathScopeComponents {
262 #[inline]
263 fn encode(&self, s: &mut E) {
264 s.emit_u8(self.bits());
265 }
266}
267
268impl<D: Decoder> Decodable<D> for RemapPathScopeComponents {
269 #[inline]
270 fn decode(s: &mut D) -> RemapPathScopeComponents {
271 RemapPathScopeComponents::from_bits(s.read_u8())
272 .expect("invalid bits for RemapPathScopeComponents")
273 }
274}
275
276#[derive(#[automatically_derived]
impl ::core::fmt::Debug for RealFileName {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f, "RealFileName",
"local", &self.local, "maybe_remapped", &self.maybe_remapped,
"scopes", &&self.scopes)
}
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for RealFileName {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Option<InnerRealFileName>>;
let _: ::core::cmp::AssertParamIsEq<InnerRealFileName>;
let _: ::core::cmp::AssertParamIsEq<RemapPathScopeComponents>;
}
}Eq, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for RealFileName { }
#[automatically_derived]
impl ::core::cmp::PartialEq for RealFileName {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.local == other.local &&
self.maybe_remapped == other.maybe_remapped &&
self.scopes == other.scopes
}
}PartialEq, #[automatically_derived]
impl ::core::clone::Clone for RealFileName {
#[inline]
fn clone(&self) -> Self {
Self {
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)]
308pub struct RealFileName {
309 local: Option<InnerRealFileName>,
311 maybe_remapped: InnerRealFileName,
313 scopes: RemapPathScopeComponents,
315}
316
317#[derive(#[automatically_derived]
impl ::core::fmt::Debug for InnerRealFileName {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"InnerRealFileName", "name", &self.name, "working_directory",
&self.working_directory, "embeddable_name",
&&self.embeddable_name)
}
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for InnerRealFileName {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<PathBuf>;
}
}Eq, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for InnerRealFileName { }
#[automatically_derived]
impl ::core::cmp::PartialEq for InnerRealFileName {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.name == other.name &&
self.working_directory == other.working_directory &&
self.embeddable_name == other.embeddable_name
}
}PartialEq, #[automatically_derived]
impl ::core::clone::Clone for InnerRealFileName {
#[inline]
fn clone(&self) -> Self {
Self {
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<__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, #[automatically_derived]
impl ::core::hash::Hash for InnerRealFileName {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.name, state);
::core::hash::Hash::hash(&self.working_directory, state);
::core::hash::Hash::hash(&self.embeddable_name, state)
}
}Hash)]
321struct InnerRealFileName {
322 name: PathBuf,
324 working_directory: PathBuf,
326 embeddable_name: PathBuf,
328}
329
330impl Hash for RealFileName {
331 #[inline]
332 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
333 if !self.was_fully_remapped() {
338 self.local.hash(state);
339 }
340 self.maybe_remapped.hash(state);
341 self.scopes.bits().hash(state);
342 }
343}
344
345impl RealFileName {
346 #[inline]
352 pub fn path(&self, scope: RemapPathScopeComponents) -> &Path {
353 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!(
354 scope.bits().count_ones() == 1,
355 "one and only one scope should be passed to `RealFileName::path`: {scope:?}"
356 );
357 if !self.scopes.contains(scope)
358 && let Some(local_name) = &self.local
359 {
360 local_name.name.as_path()
361 } else {
362 self.maybe_remapped.name.as_path()
363 }
364 }
365
366 #[inline]
377 pub fn embeddable_name(&self, scope: RemapPathScopeComponents) -> (&Path, &Path) {
378 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!(
379 scope.bits().count_ones() == 1,
380 "one and only one scope should be passed to `RealFileName::embeddable_path`: {scope:?}"
381 );
382 if !self.scopes.contains(scope)
383 && let Some(local_name) = &self.local
384 {
385 (&local_name.working_directory, &local_name.embeddable_name)
386 } else {
387 (&self.maybe_remapped.working_directory, &self.maybe_remapped.embeddable_name)
388 }
389 }
390
391 #[inline]
398 pub fn local_path(&self) -> Option<&Path> {
399 if self.was_not_remapped() {
400 Some(&self.maybe_remapped.name)
401 } else if let Some(local) = &self.local {
402 Some(&local.name)
403 } else {
404 None
405 }
406 }
407
408 #[inline]
415 pub fn into_local_path(self) -> Option<PathBuf> {
416 if self.was_not_remapped() {
417 Some(self.maybe_remapped.name)
418 } else if let Some(local) = self.local {
419 Some(local.name)
420 } else {
421 None
422 }
423 }
424
425 #[inline]
427 pub(crate) fn was_remapped(&self) -> bool {
428 !self.scopes.is_empty()
429 }
430
431 #[inline]
433 fn was_fully_remapped(&self) -> bool {
434 self.scopes.is_all()
435 }
436
437 #[inline]
439 fn was_not_remapped(&self) -> bool {
440 self.scopes.is_empty()
441 }
442
443 #[inline]
447 pub fn empty() -> RealFileName {
448 RealFileName {
449 local: Some(InnerRealFileName {
450 name: PathBuf::new(),
451 working_directory: PathBuf::new(),
452 embeddable_name: PathBuf::new(),
453 }),
454 maybe_remapped: InnerRealFileName {
455 name: PathBuf::new(),
456 working_directory: PathBuf::new(),
457 embeddable_name: PathBuf::new(),
458 },
459 scopes: RemapPathScopeComponents::empty(),
460 }
461 }
462
463 pub fn from_virtual_path(path: &Path) -> RealFileName {
467 let name = InnerRealFileName {
468 name: path.to_owned(),
469 embeddable_name: path.to_owned(),
470 working_directory: PathBuf::new(),
471 };
472 RealFileName { local: None, maybe_remapped: name, scopes: RemapPathScopeComponents::all() }
473 }
474
475 #[inline]
480 pub fn update_for_crate_metadata(&mut self) {
481 if self.was_fully_remapped() || self.was_not_remapped() {
482 self.local = None;
487 }
488 }
489
490 fn to_string_lossy<'a>(&'a self, display_pref: FileNameDisplayPreference) -> Cow<'a, str> {
494 match display_pref {
495 FileNameDisplayPreference::Remapped => self.maybe_remapped.name.to_string_lossy(),
496 FileNameDisplayPreference::Local => {
497 self.local.as_ref().unwrap_or(&self.maybe_remapped).name.to_string_lossy()
498 }
499 FileNameDisplayPreference::Short => self
500 .maybe_remapped
501 .name
502 .file_name()
503 .map_or_else(|| "".into(), |f| f.to_string_lossy()),
504 FileNameDisplayPreference::Scope(scope) => self.path(scope).to_string_lossy(),
505 }
506 }
507}
508
509#[derive(#[automatically_derived]
impl ::core::fmt::Debug for FileName {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Real(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Real",
&__self_0),
Self::CfgSpec(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"CfgSpec", &__self_0),
Self::Anon(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Anon",
&__self_0),
Self::MacroExpansion(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"MacroExpansion", &__self_0),
Self::ProcMacroSourceCode(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ProcMacroSourceCode", &__self_0),
Self::CliCrateAttr(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"CliCrateAttr", &__self_0),
Self::Custom(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Custom",
&__self_0),
Self::DocTest(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"DocTest", __self_0, &__self_1),
Self::InlineAsm(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"InlineAsm", &__self_0),
}
}
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for FileName {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<RealFileName>;
let _: ::core::cmp::AssertParamIsEq<Hash64>;
let _: ::core::cmp::AssertParamIsEq<String>;
let _: ::core::cmp::AssertParamIsEq<PathBuf>;
let _: ::core::cmp::AssertParamIsEq<isize>;
}
}Eq, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for FileName { }
#[automatically_derived]
impl ::core::cmp::PartialEq for FileName {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::Real(__self_0), Self::Real(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::CfgSpec(__self_0), Self::CfgSpec(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::Anon(__self_0), Self::Anon(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::MacroExpansion(__self_0),
Self::MacroExpansion(__arg1_0)) => __self_0 == __arg1_0,
(Self::ProcMacroSourceCode(__self_0),
Self::ProcMacroSourceCode(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::CliCrateAttr(__self_0), Self::CliCrateAttr(__arg1_0))
=> __self_0 == __arg1_0,
(Self::Custom(__self_0), Self::Custom(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::DocTest(__self_0, __self_1),
Self::DocTest(__arg1_0, __arg1_1)) =>
__self_0 == __arg1_0 && __self_1 == __arg1_1,
(Self::InlineAsm(__self_0), Self::InlineAsm(__arg1_0)) =>
__self_0 == __arg1_0,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq, #[automatically_derived]
impl ::core::clone::Clone for FileName {
#[inline]
fn clone(&self) -> Self {
match self {
Self::Real(__self_0) =>
Self::Real(::core::clone::Clone::clone(__self_0)),
Self::CfgSpec(__self_0) =>
Self::CfgSpec(::core::clone::Clone::clone(__self_0)),
Self::Anon(__self_0) =>
Self::Anon(::core::clone::Clone::clone(__self_0)),
Self::MacroExpansion(__self_0) =>
Self::MacroExpansion(::core::clone::Clone::clone(__self_0)),
Self::ProcMacroSourceCode(__self_0) =>
Self::ProcMacroSourceCode(::core::clone::Clone::clone(__self_0)),
Self::CliCrateAttr(__self_0) =>
Self::CliCrateAttr(::core::clone::Clone::clone(__self_0)),
Self::Custom(__self_0) =>
Self::Custom(::core::clone::Clone::clone(__self_0)),
Self::DocTest(__self_0, __self_1) =>
Self::DocTest(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1)),
Self::InlineAsm(__self_0) =>
Self::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, #[automatically_derived]
impl ::core::hash::Hash for FileName {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
state);
match self {
Self::Real(__self_0) => ::core::hash::Hash::hash(__self_0, state),
Self::CfgSpec(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
Self::Anon(__self_0) => ::core::hash::Hash::hash(__self_0, state),
Self::MacroExpansion(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
Self::ProcMacroSourceCode(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
Self::CliCrateAttr(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
Self::Custom(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
Self::DocTest(__self_0, __self_1) => {
::core::hash::Hash::hash(__self_0, state);
::core::hash::Hash::hash(__self_1, state)
}
Self::InlineAsm(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
}
}
}Hash, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for FileName {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => {
FileName::Real(::rustc_serialize::Decodable::decode(__decoder))
}
1usize => {
FileName::CfgSpec(::rustc_serialize::Decodable::decode(__decoder))
}
2usize => {
FileName::Anon(::rustc_serialize::Decodable::decode(__decoder))
}
3usize => {
FileName::MacroExpansion(::rustc_serialize::Decodable::decode(__decoder))
}
4usize => {
FileName::ProcMacroSourceCode(::rustc_serialize::Decodable::decode(__decoder))
}
5usize => {
FileName::CliCrateAttr(::rustc_serialize::Decodable::decode(__decoder))
}
6usize => {
FileName::Custom(::rustc_serialize::Decodable::decode(__decoder))
}
7usize => {
FileName::DocTest(::rustc_serialize::Decodable::decode(__decoder),
::rustc_serialize::Decodable::decode(__decoder))
}
8usize => {
FileName::InlineAsm(::rustc_serialize::Decodable::decode(__decoder))
}
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `FileName`, expected 0..9, actual {0}",
n));
}
}
}
}
};Decodable, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for FileName {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
FileName::Real(ref __binding_0) => { 0usize }
FileName::CfgSpec(ref __binding_0) => { 1usize }
FileName::Anon(ref __binding_0) => { 2usize }
FileName::MacroExpansion(ref __binding_0) => { 3usize }
FileName::ProcMacroSourceCode(ref __binding_0) => { 4usize }
FileName::CliCrateAttr(ref __binding_0) => { 5usize }
FileName::Custom(ref __binding_0) => { 6usize }
FileName::DocTest(ref __binding_0, ref __binding_1) => {
7usize
}
FileName::InlineAsm(ref __binding_0) => { 8usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
match *self {
FileName::Real(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
FileName::CfgSpec(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
FileName::Anon(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
FileName::MacroExpansion(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
FileName::ProcMacroSourceCode(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
FileName::CliCrateAttr(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
FileName::Custom(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
FileName::DocTest(ref __binding_0, ref __binding_1) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
}
FileName::InlineAsm(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
}
}
}
};Encodable)]
511pub enum FileName {
512 Real(RealFileName),
513 CfgSpec(Hash64),
515 Anon(Hash64),
517 MacroExpansion(Hash64),
520 ProcMacroSourceCode(Hash64),
521 CliCrateAttr(Hash64),
523 Custom(String),
525 DocTest(PathBuf, isize),
526 InlineAsm(Hash64),
528}
529
530pub struct FileNameDisplay<'a> {
531 inner: &'a FileName,
532 display_pref: FileNameDisplayPreference,
533}
534
535#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for FileNameDisplayPreference { }
#[automatically_derived]
impl ::core::clone::Clone for FileNameDisplayPreference {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<RemapPathScopeComponents>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for FileNameDisplayPreference { }Copy)]
537enum FileNameDisplayPreference {
538 Remapped,
539 Local,
540 Short,
541 Scope(RemapPathScopeComponents),
542}
543
544impl fmt::Display for FileNameDisplay<'_> {
545 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
546 use FileName::*;
547 match *self.inner {
548 Real(ref name) => {
549 fmt.write_fmt(format_args!("{0}", name.to_string_lossy(self.display_pref)))write!(fmt, "{}", name.to_string_lossy(self.display_pref))
550 }
551 CfgSpec(_) => fmt.write_fmt(format_args!("<cfgspec>"))write!(fmt, "<cfgspec>"),
552 MacroExpansion(_) => fmt.write_fmt(format_args!("<macro expansion>"))write!(fmt, "<macro expansion>"),
553 Anon(_) => fmt.write_fmt(format_args!("<anon>"))write!(fmt, "<anon>"),
554 ProcMacroSourceCode(_) => fmt.write_fmt(format_args!("<proc-macro source code>"))write!(fmt, "<proc-macro source code>"),
555 CliCrateAttr(_) => fmt.write_fmt(format_args!("<crate attribute>"))write!(fmt, "<crate attribute>"),
556 Custom(ref s) => fmt.write_fmt(format_args!("<{0}>", s))write!(fmt, "<{s}>"),
557 DocTest(ref path, _) => fmt.write_fmt(format_args!("{0}", path.display()))write!(fmt, "{}", path.display()),
558 InlineAsm(_) => fmt.write_fmt(format_args!("<inline asm>"))write!(fmt, "<inline asm>"),
559 }
560 }
561}
562
563impl<'a> FileNameDisplay<'a> {
564 pub fn to_string_lossy(&self) -> Cow<'a, str> {
565 match self.inner {
566 FileName::Real(inner) => inner.to_string_lossy(self.display_pref),
567 _ => Cow::from(self.to_string()),
568 }
569 }
570}
571
572impl FileName {
573 pub fn is_real(&self) -> bool {
574 use FileName::*;
575 match *self {
576 Real(_) => true,
577 Anon(_)
578 | MacroExpansion(_)
579 | ProcMacroSourceCode(_)
580 | CliCrateAttr(_)
581 | Custom(_)
582 | CfgSpec(_)
583 | DocTest(_, _)
584 | InlineAsm(_) => false,
585 }
586 }
587
588 #[inline]
593 pub fn prefer_remapped_unconditionally(&self) -> FileNameDisplay<'_> {
594 FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Remapped }
595 }
596
597 #[inline]
602 pub fn prefer_local_unconditionally(&self) -> FileNameDisplay<'_> {
603 FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Local }
604 }
605
606 #[inline]
608 pub fn short(&self) -> FileNameDisplay<'_> {
609 FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Short }
610 }
611
612 #[inline]
614 pub fn display(&self, scope: RemapPathScopeComponents) -> FileNameDisplay<'_> {
615 FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Scope(scope) }
616 }
617
618 pub fn macro_expansion_source_code(src: &str) -> FileName {
619 let mut hasher = StableHasher::new();
620 src.hash(&mut hasher);
621 FileName::MacroExpansion(hasher.finish())
622 }
623
624 pub fn anon_source_code(src: &str) -> FileName {
625 let mut hasher = StableHasher::new();
626 src.hash(&mut hasher);
627 FileName::Anon(hasher.finish())
628 }
629
630 pub fn proc_macro_source_code(src: &str) -> FileName {
631 let mut hasher = StableHasher::new();
632 src.hash(&mut hasher);
633 FileName::ProcMacroSourceCode(hasher.finish())
634 }
635
636 pub fn cfg_spec_source_code(src: &str) -> FileName {
637 let mut hasher = StableHasher::new();
638 src.hash(&mut hasher);
639 FileName::CfgSpec(hasher.finish())
640 }
641
642 pub fn cli_crate_attr_source_code(src: &str) -> FileName {
643 let mut hasher = StableHasher::new();
644 src.hash(&mut hasher);
645 FileName::CliCrateAttr(hasher.finish())
646 }
647
648 pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName {
649 FileName::DocTest(path, line)
650 }
651
652 pub fn inline_asm_source_code(src: &str) -> FileName {
653 let mut hasher = StableHasher::new();
654 src.hash(&mut hasher);
655 FileName::InlineAsm(hasher.finish())
656 }
657
658 pub fn into_local_path(self) -> Option<PathBuf> {
663 match self {
664 FileName::Real(path) => path.into_local_path(),
665 FileName::DocTest(path, _) => Some(path),
666 _ => None,
667 }
668 }
669}
670
671#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for SpanData { }
#[automatically_derived]
impl ::core::clone::Clone for SpanData {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<BytePos>;
let _: ::core::clone::AssertParamIsClone<SyntaxContext>;
let _: ::core::clone::AssertParamIsClone<Option<LocalDefId>>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for SpanData { }Copy, #[automatically_derived]
impl ::core::hash::Hash for SpanData {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.lo, state);
::core::hash::Hash::hash(&self.hi, state);
::core::hash::Hash::hash(&self.ctxt, state);
::core::hash::Hash::hash(&self.parent, state)
}
}Hash, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for SpanData { }
#[automatically_derived]
impl ::core::cmp::PartialEq for SpanData {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.lo == other.lo && self.hi == other.hi && self.ctxt == other.ctxt
&& self.parent == other.parent
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for SpanData {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<BytePos>;
let _: ::core::cmp::AssertParamIsEq<SyntaxContext>;
let _: ::core::cmp::AssertParamIsEq<Option<LocalDefId>>;
}
}Eq)]
687#[automatically_derived]
impl ::core::cmp::PartialOrd for SpanData {
#[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 SpanData {
#[inline]
fn cmp(&self, __other: &Self) -> ::core::cmp::Ordering {
match (self, __other) {
(SpanData {
lo: ref __field_lo,
hi: ref __field_hi,
ctxt: ref __field_ctxt,
parent: ref __field_parent }, SpanData {
lo: ref __other_field_lo,
hi: ref __other_field_hi,
ctxt: ref __other_field_ctxt,
parent: ref __other_field_parent }) =>
match ::core::cmp::Ord::cmp(__field_lo, __other_field_lo) {
::core::cmp::Ordering::Equal =>
match ::core::cmp::Ord::cmp(__field_hi, __other_field_hi) {
::core::cmp::Ordering::Equal =>
::core::cmp::Ordering::Equal,
__cmp => __cmp,
},
__cmp => __cmp,
},
}
}
}#[derive_where(PartialOrd, Ord)]
688pub struct SpanData {
689 pub lo: BytePos,
690 pub hi: BytePos,
691 #[derive_where(skip)]
694 pub ctxt: SyntaxContext,
697 #[derive_where(skip)]
698 pub parent: Option<LocalDefId>,
701}
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 #[inline]
718 fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
719 Span::new(self.lo, self.hi, ctxt, self.parent)
720 }
721 #[inline]
723 fn with_parent(&self, parent: Option<LocalDefId>) -> Span {
724 Span::new(self.lo, self.hi, self.ctxt, parent)
725 }
726 #[inline]
728 pub fn is_dummy(self) -> bool {
729 self.lo.0 == 0 && self.hi.0 == 0
730 }
731 pub fn contains(self, other: Self) -> bool {
733 self.lo <= other.lo && other.hi <= self.hi
734 }
735}
736
737impl Default for SpanData {
738 fn default() -> Self {
739 Self { lo: BytePos(0), hi: BytePos(0), ctxt: SyntaxContext::root(), parent: None }
740 }
741}
742
743impl PartialOrd for Span {
744 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
745 Some(self.cmp(rhs))
746 }
747}
748impl Ord for Span {
749 fn cmp(&self, rhs: &Self) -> Ordering {
750 Ord::cmp(&self.data(), &rhs.data())
751 }
752}
753
754impl Span {
755 #[inline]
756 pub fn lo(self) -> BytePos {
757 self.data().lo
758 }
759 #[inline]
760 pub fn with_lo(self, lo: BytePos) -> Span {
761 self.data().with_lo(lo)
762 }
763 #[inline]
764 pub fn hi(self) -> BytePos {
765 self.data().hi
766 }
767 #[inline]
768 pub fn with_hi(self, hi: BytePos) -> Span {
769 self.data().with_hi(hi)
770 }
771 #[inline]
772 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
773 self.map_ctxt(|_| ctxt)
774 }
775
776 #[inline]
777 pub fn is_visible(self, sm: &SourceMap) -> bool {
778 !self.is_dummy() && sm.is_span_accessible(self)
779 }
780
781 #[inline]
786 pub fn in_external_macro(self, sm: &SourceMap) -> bool {
787 self.ctxt().in_external_macro(sm)
788 }
789
790 pub fn in_derive_expansion(self) -> bool {
792 #[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, _))
793 }
794
795 pub fn is_from_async_await(self) -> bool {
797 #[allow(non_exhaustive_omitted_patterns)] match self.ctxt().outer_expn_data().kind
{
ExpnKind::Desugaring(DesugaringKind::Async | DesugaringKind::Await) =>
true,
_ => false,
}matches!(
798 self.ctxt().outer_expn_data().kind,
799 ExpnKind::Desugaring(DesugaringKind::Async | DesugaringKind::Await),
800 )
801 }
802
803 pub fn can_be_used_for_suggestions(self) -> bool {
805 !self.from_expansion()
806 || (self.in_derive_expansion()
810 && self.parent_callsite().map(|p| (p.lo(), p.hi())) != Some((self.lo(), self.hi())))
811 }
812
813 #[inline]
814 pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
815 Span::new(lo, hi, SyntaxContext::root(), None)
816 }
817
818 #[inline]
820 pub fn shrink_to_lo(self) -> Span {
821 let span = self.data_untracked();
822 span.with_hi(span.lo)
823 }
824 #[inline]
826 pub fn shrink_to_hi(self) -> Span {
827 let span = self.data_untracked();
828 span.with_lo(span.hi)
829 }
830
831 #[inline]
832 pub fn is_empty(self) -> bool {
834 let span = self.data_untracked();
835 span.hi == span.lo
836 }
837
838 pub fn substitute_dummy(self, other: Span) -> Span {
840 if self.is_dummy() { other } else { self }
841 }
842
843 pub fn contains(self, other: Span) -> bool {
845 let span = self.data();
846 let other = other.data();
847 span.contains(other)
848 }
849
850 pub fn overlaps(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 pub fn overlaps_or_adjacent(self, other: Span) -> bool {
859 let span = self.data();
860 let other = other.data();
861 span.lo <= other.hi && other.lo <= span.hi
862 }
863
864 pub fn source_equal(self, other: Span) -> bool {
869 let span = self.data();
870 let other = other.data();
871 span.lo == other.lo && span.hi == other.hi
872 }
873
874 pub fn trim_start(self, other: Span) -> Option<Span> {
876 let span = self.data();
877 let other = other.data();
878 if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None }
879 }
880
881 pub fn trim_end(self, other: Span) -> Option<Span> {
883 let span = self.data();
884 let other = other.data();
885 if span.lo < other.lo { Some(span.with_hi(cmp::min(span.hi, other.lo))) } else { None }
886 }
887
888 pub fn source_callsite(self) -> Span {
891 let ctxt = self.ctxt();
892 if !ctxt.is_root() { ctxt.outer_expn_data().call_site.source_callsite() } else { self }
893 }
894
895 pub fn parent_callsite(self) -> Option<Span> {
898 let ctxt = self.ctxt();
899 (!ctxt.is_root()).then(|| ctxt.outer_expn_data().call_site)
900 }
901
902 pub fn find_ancestor_inside(mut self, outer: Span) -> Option<Span> {
915 while !outer.contains(self) {
916 self = self.parent_callsite()?;
917 }
918 Some(self)
919 }
920
921 pub fn find_ancestor_in_same_ctxt(mut self, other: Span) -> Option<Span> {
934 while !self.eq_ctxt(other) {
935 self = self.parent_callsite()?;
936 }
937 Some(self)
938 }
939
940 pub fn find_ancestor_inside_same_ctxt(mut self, outer: Span) -> Option<Span> {
953 while !outer.contains(self) || !self.eq_ctxt(outer) {
954 self = self.parent_callsite()?;
955 }
956 Some(self)
957 }
958
959 pub fn find_ancestor_not_from_extern_macro(mut self, sm: &SourceMap) -> Option<Span> {
973 while self.in_external_macro(sm) {
974 self = self.parent_callsite()?;
975 }
976 Some(self)
977 }
978
979 pub fn find_ancestor_not_from_macro(mut self) -> Option<Span> {
992 while self.from_expansion() {
993 self = self.parent_callsite()?;
994 }
995 Some(self)
996 }
997
998 pub fn edition(self) -> edition::Edition {
1000 self.ctxt().edition()
1001 }
1002
1003 #[inline]
1005 pub fn is_rust_2015(self) -> bool {
1006 self.edition().is_rust_2015()
1007 }
1008
1009 #[inline]
1011 pub fn at_least_rust_2018(self) -> bool {
1012 self.edition().at_least_rust_2018()
1013 }
1014
1015 #[inline]
1017 pub fn at_least_rust_2021(self) -> bool {
1018 self.edition().at_least_rust_2021()
1019 }
1020
1021 #[inline]
1023 pub fn at_least_rust_2024(self) -> bool {
1024 self.edition().at_least_rust_2024()
1025 }
1026
1027 pub fn source_callee(self) -> Option<ExpnData> {
1033 let mut ctxt = self.ctxt();
1034 let mut opt_expn_data = None;
1035 while !ctxt.is_root() {
1036 let expn_data = ctxt.outer_expn_data();
1037 ctxt = expn_data.call_site.ctxt();
1038 opt_expn_data = Some(expn_data);
1039 }
1040 opt_expn_data
1041 }
1042
1043 pub fn allows_unstable(self, feature: Symbol) -> bool {
1047 self.ctxt()
1048 .outer_expn_data()
1049 .allow_internal_unstable
1050 .is_some_and(|features| features.contains(&feature))
1051 }
1052
1053 pub fn is_desugaring(self, kind: DesugaringKind) -> bool {
1055 match self.ctxt().outer_expn_data().kind {
1056 ExpnKind::Desugaring(k) => k == kind,
1057 _ => false,
1058 }
1059 }
1060
1061 pub fn desugaring_kind(self) -> Option<DesugaringKind> {
1064 match self.ctxt().outer_expn_data().kind {
1065 ExpnKind::Desugaring(k) => Some(k),
1066 _ => None,
1067 }
1068 }
1069
1070 pub fn allows_unsafe(self) -> bool {
1074 self.ctxt().outer_expn_data().allow_internal_unsafe
1075 }
1076
1077 pub fn macro_backtrace(mut self) -> impl Iterator<Item = ExpnData> {
1078 let mut prev_span = DUMMY_SP;
1079 iter::from_fn(move || {
1080 loop {
1081 let ctxt = self.ctxt();
1082 if ctxt.is_root() {
1083 return None;
1084 }
1085
1086 let expn_data = ctxt.outer_expn_data();
1087 let is_recursive = expn_data.call_site.source_equal(prev_span);
1088
1089 prev_span = self;
1090 self = expn_data.call_site;
1091
1092 if !is_recursive {
1094 return Some(expn_data);
1095 }
1096 }
1097 })
1098 }
1099
1100 pub fn split_at(self, pos: u32) -> (Span, Span) {
1102 let len = self.hi().0 - self.lo().0;
1103 if true {
if !(pos <= len) {
::core::panicking::panic("assertion failed: pos <= len")
};
};debug_assert!(pos <= len);
1104
1105 let split_pos = BytePos(self.lo().0 + pos);
1106 (
1107 Span::new(self.lo(), split_pos, self.ctxt(), self.parent()),
1108 Span::new(split_pos, self.hi(), self.ctxt(), self.parent()),
1109 )
1110 }
1111
1112 fn try_metavars(a: SpanData, b: SpanData, a_orig: Span, b_orig: Span) -> (SpanData, SpanData) {
1114 match with_metavar_spans(|mspans| (mspans.get(a_orig), mspans.get(b_orig))) {
1115 (None, None) => {}
1116 (Some(meta_a), None) => {
1117 let meta_a = meta_a.data();
1118 if meta_a.ctxt == b.ctxt {
1119 return (meta_a, b);
1120 }
1121 }
1122 (None, Some(meta_b)) => {
1123 let meta_b = meta_b.data();
1124 if a.ctxt == meta_b.ctxt {
1125 return (a, meta_b);
1126 }
1127 }
1128 (Some(meta_a), Some(meta_b)) => {
1129 let meta_b = meta_b.data();
1130 if a.ctxt == meta_b.ctxt {
1131 return (a, meta_b);
1132 }
1133 let meta_a = meta_a.data();
1134 if meta_a.ctxt == b.ctxt {
1135 return (meta_a, b);
1136 } else if meta_a.ctxt == meta_b.ctxt {
1137 return (meta_a, meta_b);
1138 }
1139 }
1140 }
1141
1142 (a, b)
1143 }
1144
1145 fn prepare_to_combine(
1147 a_orig: Span,
1148 b_orig: Span,
1149 ) -> Result<(SpanData, SpanData, Option<LocalDefId>), Span> {
1150 let (a, b) = (a_orig.data(), b_orig.data());
1151 if a.ctxt == b.ctxt {
1152 return Ok((a, b, if a.parent == b.parent { a.parent } else { None }));
1153 }
1154
1155 let (a, b) = Span::try_metavars(a, b, a_orig, b_orig);
1156 if a.ctxt == b.ctxt {
1157 return Ok((a, b, if a.parent == b.parent { a.parent } else { None }));
1158 }
1159
1160 let a_is_callsite = a.ctxt.is_root() || a.ctxt == b.span().source_callsite().ctxt();
1168 Err(if a_is_callsite { b_orig } else { a_orig })
1169 }
1170
1171 pub fn with_neighbor(self, neighbor: Span) -> Span {
1173 match Span::prepare_to_combine(self, neighbor) {
1174 Ok((this, ..)) => this.span(),
1175 Err(_) => self,
1176 }
1177 }
1178
1179 pub fn to(self, end: Span) -> Span {
1190 match Span::prepare_to_combine(self, end) {
1191 Ok((from, to, parent)) => {
1192 Span::new(cmp::min(from.lo, to.lo), cmp::max(from.hi, to.hi), from.ctxt, parent)
1193 }
1194 Err(fallback) => fallback,
1195 }
1196 }
1197
1198 pub fn between(self, end: Span) -> Span {
1206 match Span::prepare_to_combine(self, end) {
1207 Ok((from, to, parent)) => {
1208 Span::new(cmp::min(from.hi, to.hi), cmp::max(from.lo, to.lo), from.ctxt, parent)
1209 }
1210 Err(fallback) => fallback,
1211 }
1212 }
1213
1214 pub fn until(self, end: Span) -> Span {
1222 match Span::prepare_to_combine(self, end) {
1223 Ok((from, to, parent)) => {
1224 Span::new(cmp::min(from.lo, to.lo), cmp::max(from.lo, to.lo), from.ctxt, parent)
1225 }
1226 Err(fallback) => fallback,
1227 }
1228 }
1229
1230 pub fn within_macro(self, within: Span, sm: &SourceMap) -> Option<Span> {
1245 let (self_, _, parent) = Span::prepare_to_combine(self, within).ok()?;
1246
1247 if self.data().contains(self_) || sm.is_imported(within) {
1254 return None;
1255 }
1256
1257 if within.data().ctxt.outer_expn_data().diagnostic_opaque {
1260 return None;
1261 }
1262
1263 Some(Span::new(self_.lo, self_.hi, self_.ctxt, parent))
1264 }
1265
1266 pub fn from_inner(self, inner: InnerSpan) -> Span {
1267 let span = self.data();
1268 Span::new(
1269 span.lo + BytePos::from_usize(inner.start),
1270 span.lo + BytePos::from_usize(inner.end),
1271 span.ctxt,
1272 span.parent,
1273 )
1274 }
1275
1276 pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
1279 self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
1280 }
1281
1282 pub fn with_call_site_ctxt(self, expn_id: ExpnId) -> Span {
1285 self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
1286 }
1287
1288 pub fn with_mixed_site_ctxt(self, expn_id: ExpnId) -> Span {
1291 self.with_ctxt_from_mark(expn_id, Transparency::SemiOpaque)
1292 }
1293
1294 fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
1298 self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
1299 }
1300
1301 #[inline]
1302 pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
1303 self.map_ctxt(|ctxt| ctxt.apply_mark(expn_id, transparency))
1304 }
1305
1306 #[inline]
1307 pub fn remove_mark(&mut self) -> ExpnId {
1308 let mut mark = ExpnId::root();
1309 *self = self.map_ctxt(|mut ctxt| {
1310 mark = ctxt.remove_mark();
1311 ctxt
1312 });
1313 mark
1314 }
1315
1316 #[inline]
1317 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
1318 let mut mark = None;
1319 *self = self.map_ctxt(|mut ctxt| {
1320 mark = ctxt.adjust(expn_id);
1321 ctxt
1322 });
1323 mark
1324 }
1325
1326 #[inline]
1327 pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
1328 let mut mark = None;
1329 *self = self.map_ctxt(|mut ctxt| {
1330 mark = ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
1331 ctxt
1332 });
1333 mark
1334 }
1335
1336 #[inline]
1337 pub fn normalize_to_macros_2_0(self) -> Span {
1338 self.map_ctxt(|ctxt| ctxt.normalize_to_macros_2_0())
1339 }
1340
1341 #[inline]
1342 pub fn normalize_to_macro_rules(self) -> Span {
1343 self.map_ctxt(|ctxt| ctxt.normalize_to_macro_rules())
1344 }
1345}
1346
1347impl Default for Span {
1348 fn default() -> Self {
1349 DUMMY_SP
1350 }
1351}
1352
1353#[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! {
1354 #[orderable]
1355 #[debug_format = "AttrId({})"]
1356 pub struct AttrId {}
1357}
1358
1359pub trait SpanEncoder: Encoder {
1362 fn encode_span(&mut self, span: Span);
1363 fn encode_symbol(&mut self, sym: Symbol);
1364 fn encode_byte_symbol(&mut self, byte_sym: ByteSymbol);
1365 fn encode_expn_id(&mut self, expn_id: ExpnId);
1366 fn encode_syntax_context(&mut self, syntax_context: SyntaxContext);
1367 fn encode_crate_num(&mut self, crate_num: CrateNum);
1370 fn encode_def_index(&mut self, def_index: DefIndex);
1371 fn encode_def_id(&mut self, def_id: DefId);
1372}
1373
1374impl SpanEncoder for FileEncoder<'_> {
1375 fn encode_span(&mut self, span: Span) {
1376 let span = span.data();
1377 span.lo.encode(self);
1378 span.hi.encode(self);
1379 }
1380
1381 fn encode_symbol(&mut self, sym: Symbol) {
1382 self.emit_str(sym.as_str());
1383 }
1384
1385 fn encode_byte_symbol(&mut self, byte_sym: ByteSymbol) {
1386 self.emit_byte_str(byte_sym.as_byte_str());
1387 }
1388
1389 fn encode_expn_id(&mut self, _expn_id: ExpnId) {
1390 {
::core::panicking::panic_fmt(format_args!("cannot encode `ExpnId` with `FileEncoder`"));
};panic!("cannot encode `ExpnId` with `FileEncoder`");
1391 }
1392
1393 fn encode_syntax_context(&mut self, _syntax_context: SyntaxContext) {
1394 {
::core::panicking::panic_fmt(format_args!("cannot encode `SyntaxContext` with `FileEncoder`"));
};panic!("cannot encode `SyntaxContext` with `FileEncoder`");
1395 }
1396
1397 fn encode_crate_num(&mut self, crate_num: CrateNum) {
1398 self.emit_u32(crate_num.as_u32());
1399 }
1400
1401 fn encode_def_index(&mut self, _def_index: DefIndex) {
1402 {
::core::panicking::panic_fmt(format_args!("cannot encode `DefIndex` with `FileEncoder`"));
};panic!("cannot encode `DefIndex` with `FileEncoder`");
1403 }
1404
1405 fn encode_def_id(&mut self, def_id: DefId) {
1406 def_id.krate.encode(self);
1407 def_id.index.encode(self);
1408 }
1409}
1410
1411impl SpanEncoder for MemEncoder {
1412 fn encode_span(&mut self, span: Span) {
1413 let span = span.data();
1414 span.lo.encode(self);
1415 span.hi.encode(self);
1416 }
1417
1418 fn encode_symbol(&mut self, sym: Symbol) {
1419 self.emit_str(sym.as_str());
1420 }
1421
1422 fn encode_byte_symbol(&mut self, byte_sym: ByteSymbol) {
1423 self.emit_byte_str(byte_sym.as_byte_str());
1424 }
1425
1426 fn encode_expn_id(&mut self, _expn_id: ExpnId) {
1427 {
::core::panicking::panic_fmt(format_args!("cannot encode `ExpnId` with `FileEncoder`"));
};panic!("cannot encode `ExpnId` with `FileEncoder`");
1428 }
1429
1430 fn encode_syntax_context(&mut self, _syntax_context: SyntaxContext) {
1431 {
::core::panicking::panic_fmt(format_args!("cannot encode `SyntaxContext` with `FileEncoder`"));
};panic!("cannot encode `SyntaxContext` with `FileEncoder`");
1432 }
1433
1434 fn encode_crate_num(&mut self, crate_num: CrateNum) {
1435 self.emit_u32(crate_num.as_u32());
1436 }
1437
1438 fn encode_def_index(&mut self, _def_index: DefIndex) {
1439 {
::core::panicking::panic_fmt(format_args!("cannot encode `DefIndex` with `FileEncoder`"));
};panic!("cannot encode `DefIndex` with `FileEncoder`");
1440 }
1441
1442 fn encode_def_id(&mut self, def_id: DefId) {
1443 def_id.krate.encode(self);
1444 def_id.index.encode(self);
1445 }
1446}
1447
1448impl<E: SpanEncoder> Encodable<E> for Span {
1449 fn encode(&self, s: &mut E) {
1450 s.encode_span(*self);
1451 }
1452}
1453
1454impl<E: SpanEncoder> Encodable<E> for Symbol {
1455 fn encode(&self, s: &mut E) {
1456 s.encode_symbol(*self);
1457 }
1458}
1459
1460impl<E: SpanEncoder> Encodable<E> for ByteSymbol {
1461 fn encode(&self, s: &mut E) {
1462 s.encode_byte_symbol(*self);
1463 }
1464}
1465
1466impl<E: SpanEncoder> Encodable<E> for ExpnId {
1467 fn encode(&self, s: &mut E) {
1468 s.encode_expn_id(*self)
1469 }
1470}
1471
1472impl<E: SpanEncoder> Encodable<E> for SyntaxContext {
1473 fn encode(&self, s: &mut E) {
1474 s.encode_syntax_context(*self)
1475 }
1476}
1477
1478impl<E: SpanEncoder> Encodable<E> for CrateNum {
1479 fn encode(&self, s: &mut E) {
1480 s.encode_crate_num(*self)
1481 }
1482}
1483
1484impl<E: SpanEncoder> Encodable<E> for DefIndex {
1485 fn encode(&self, s: &mut E) {
1486 s.encode_def_index(*self)
1487 }
1488}
1489
1490impl<E: SpanEncoder> Encodable<E> for DefId {
1491 fn encode(&self, s: &mut E) {
1492 s.encode_def_id(*self)
1493 }
1494}
1495
1496impl<E: SpanEncoder> Encodable<E> for AttrId {
1497 fn encode(&self, _s: &mut E) {
1498 }
1500}
1501
1502pub trait BlobDecoder: Decoder {
1503 fn decode_symbol(&mut self) -> Symbol;
1504 fn decode_byte_symbol(&mut self) -> ByteSymbol;
1505 fn decode_def_index(&mut self) -> DefIndex;
1506}
1507
1508pub trait SpanDecoder: BlobDecoder {
1525 fn decode_span(&mut self) -> Span;
1526 fn decode_expn_id(&mut self) -> ExpnId;
1527 fn decode_syntax_context(&mut self) -> SyntaxContext;
1528 fn decode_crate_num(&mut self) -> CrateNum;
1529 fn decode_def_id(&mut self) -> DefId;
1530 fn decode_attr_id(&mut self) -> AttrId;
1531}
1532
1533impl BlobDecoder for MemDecoder<'_> {
1534 fn decode_symbol(&mut self) -> Symbol {
1535 Symbol::intern(self.read_str())
1536 }
1537
1538 fn decode_byte_symbol(&mut self) -> ByteSymbol {
1539 ByteSymbol::intern(self.read_byte_str())
1540 }
1541
1542 fn decode_def_index(&mut self) -> DefIndex {
1543 {
::core::panicking::panic_fmt(format_args!("cannot decode `DefIndex` with `MemDecoder`"));
};panic!("cannot decode `DefIndex` with `MemDecoder`");
1544 }
1545}
1546
1547impl SpanDecoder for MemDecoder<'_> {
1548 fn decode_span(&mut self) -> Span {
1549 let lo = Decodable::decode(self);
1550 let hi = Decodable::decode(self);
1551
1552 Span::new(lo, hi, SyntaxContext::root(), None)
1553 }
1554
1555 fn decode_expn_id(&mut self) -> ExpnId {
1556 {
::core::panicking::panic_fmt(format_args!("cannot decode `ExpnId` with `MemDecoder`"));
};panic!("cannot decode `ExpnId` with `MemDecoder`");
1557 }
1558
1559 fn decode_syntax_context(&mut self) -> SyntaxContext {
1560 {
::core::panicking::panic_fmt(format_args!("cannot decode `SyntaxContext` with `MemDecoder`"));
};panic!("cannot decode `SyntaxContext` with `MemDecoder`");
1561 }
1562
1563 fn decode_crate_num(&mut self) -> CrateNum {
1564 CrateNum::from_u32(self.read_u32())
1565 }
1566
1567 fn decode_def_id(&mut self) -> DefId {
1568 DefId { krate: Decodable::decode(self), index: Decodable::decode(self) }
1569 }
1570
1571 fn decode_attr_id(&mut self) -> AttrId {
1572 {
::core::panicking::panic_fmt(format_args!("cannot decode `AttrId` with `MemDecoder`"));
};panic!("cannot decode `AttrId` with `MemDecoder`");
1573 }
1574}
1575
1576impl<D: SpanDecoder> Decodable<D> for Span {
1577 fn decode(s: &mut D) -> Span {
1578 s.decode_span()
1579 }
1580}
1581
1582impl<D: BlobDecoder> Decodable<D> for Symbol {
1583 fn decode(s: &mut D) -> Symbol {
1584 s.decode_symbol()
1585 }
1586}
1587
1588impl<D: BlobDecoder> Decodable<D> for ByteSymbol {
1589 fn decode(s: &mut D) -> ByteSymbol {
1590 s.decode_byte_symbol()
1591 }
1592}
1593
1594impl<D: SpanDecoder> Decodable<D> for ExpnId {
1595 fn decode(s: &mut D) -> ExpnId {
1596 s.decode_expn_id()
1597 }
1598}
1599
1600impl<D: SpanDecoder> Decodable<D> for SyntaxContext {
1601 fn decode(s: &mut D) -> SyntaxContext {
1602 s.decode_syntax_context()
1603 }
1604}
1605
1606impl<D: SpanDecoder> Decodable<D> for CrateNum {
1607 fn decode(s: &mut D) -> CrateNum {
1608 s.decode_crate_num()
1609 }
1610}
1611
1612impl<D: BlobDecoder> Decodable<D> for DefIndex {
1613 fn decode(s: &mut D) -> DefIndex {
1614 s.decode_def_index()
1615 }
1616}
1617
1618impl<D: SpanDecoder> Decodable<D> for DefId {
1619 fn decode(s: &mut D) -> DefId {
1620 s.decode_def_id()
1621 }
1622}
1623
1624impl<D: SpanDecoder> Decodable<D> for AttrId {
1625 fn decode(s: &mut D) -> AttrId {
1626 s.decode_attr_id()
1627 }
1628}
1629
1630impl fmt::Debug for Span {
1631 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1632 fn fallback(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1636 f.debug_struct("Span")
1637 .field("lo", &span.lo())
1638 .field("hi", &span.hi())
1639 .field("ctxt", &span.ctxt())
1640 .finish()
1641 }
1642
1643 if SESSION_GLOBALS.is_set() {
1644 with_session_globals(|session_globals| {
1645 if let Some(source_map) = &session_globals.source_map {
1646 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())
1647 } else {
1648 fallback(*self, f)
1649 }
1650 })
1651 } else {
1652 fallback(*self, f)
1653 }
1654 }
1655}
1656
1657impl fmt::Debug for SpanData {
1658 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1659 fmt::Debug::fmt(&self.span(), f)
1660 }
1661}
1662
1663#[derive(#[automatically_derived]
impl ::core::marker::Copy for MultiByteChar { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for MultiByteChar { }
#[automatically_derived]
impl ::core::clone::Clone for MultiByteChar {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<RelativeBytePos>;
let _: ::core::clone::AssertParamIsClone<u8>;
*self
}
}Clone, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for MultiByteChar {
fn encode(&self, __encoder: &mut __E) {
let MultiByteChar {
pos: ref __binding_0, bytes: ref __binding_1 } = *self;
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for MultiByteChar {
fn decode(__decoder: &mut __D) -> Self {
MultiByteChar {
pos: ::rustc_serialize::Decodable::decode(__decoder),
bytes: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable, #[automatically_derived]
impl ::core::cmp::Eq for MultiByteChar {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<RelativeBytePos>;
let _: ::core::cmp::AssertParamIsEq<u8>;
}
}Eq, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for MultiByteChar { }
#[automatically_derived]
impl ::core::cmp::PartialEq for MultiByteChar {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.bytes == other.bytes && self.pos == other.pos
}
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for MultiByteChar {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "MultiByteChar",
"pos", &self.pos, "bytes", &&self.bytes)
}
}Debug, const _: () =
{
impl ::rustc_data_structures::stable_hash::StableHash for
MultiByteChar {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
match *self {
MultiByteChar { pos: ref __binding_0, bytes: ref __binding_1
} => {
{ __binding_0.stable_hash(__hcx, __hasher); }
{ __binding_1.stable_hash(__hcx, __hasher); }
}
}
}
}
};StableHash)]
1665pub struct MultiByteChar {
1666 pub pos: RelativeBytePos,
1668 pub bytes: u8,
1670}
1671
1672#[derive(#[automatically_derived]
impl ::core::marker::Copy for NormalizedPos { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for NormalizedPos { }
#[automatically_derived]
impl ::core::clone::Clone for NormalizedPos {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<RelativeBytePos>;
let _: ::core::clone::AssertParamIsClone<u32>;
*self
}
}Clone, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for NormalizedPos {
fn encode(&self, __encoder: &mut __E) {
let NormalizedPos {
pos: ref __binding_0, diff: ref __binding_1 } = *self;
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for NormalizedPos {
fn decode(__decoder: &mut __D) -> Self {
NormalizedPos {
pos: ::rustc_serialize::Decodable::decode(__decoder),
diff: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable, #[automatically_derived]
impl ::core::cmp::Eq for NormalizedPos {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<RelativeBytePos>;
let _: ::core::cmp::AssertParamIsEq<u32>;
}
}Eq, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for NormalizedPos { }
#[automatically_derived]
impl ::core::cmp::PartialEq for NormalizedPos {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.diff == other.diff && self.pos == other.pos
}
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for NormalizedPos {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "NormalizedPos",
"pos", &self.pos, "diff", &&self.diff)
}
}Debug, const _: () =
{
impl ::rustc_data_structures::stable_hash::StableHash for
NormalizedPos {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
match *self {
NormalizedPos { pos: ref __binding_0, diff: ref __binding_1
} => {
{ __binding_0.stable_hash(__hcx, __hasher); }
{ __binding_1.stable_hash(__hcx, __hasher); }
}
}
}
}
};StableHash)]
1674pub struct NormalizedPos {
1675 pub pos: RelativeBytePos,
1677 pub diff: u32,
1679}
1680
1681#[derive(#[automatically_derived]
impl ::core::marker::StructuralPartialEq for ExternalSource { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ExternalSource {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::Foreign { kind: __self_0, metadata_index: __self_1 },
Self::Foreign { kind: __arg1_0, metadata_index: __arg1_1 })
=> __self_1 == __arg1_1 && __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ExternalSource {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<ExternalSourceKind>;
let _: ::core::cmp::AssertParamIsEq<u32>;
}
}Eq, #[automatically_derived]
impl ::core::clone::Clone for ExternalSource {
#[inline]
fn clone(&self) -> Self {
match self {
Self::Unneeded => Self::Unneeded,
Self::Foreign { kind: __self_0, metadata_index: __self_1 } =>
Self::Foreign {
kind: ::core::clone::Clone::clone(__self_0),
metadata_index: ::core::clone::Clone::clone(__self_1),
},
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ExternalSource {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Unneeded =>
::core::fmt::Formatter::write_str(f, "Unneeded"),
Self::Foreign { kind: __self_0, metadata_index: __self_1 } =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Foreign", "kind", __self_0, "metadata_index", &__self_1),
}
}
}Debug)]
1682pub enum ExternalSource {
1683 Unneeded,
1685 Foreign {
1686 kind: ExternalSourceKind,
1687 metadata_index: u32,
1689 },
1690}
1691
1692#[derive(#[automatically_derived]
impl ::core::marker::StructuralPartialEq for ExternalSourceKind { }
#[automatically_derived]
impl ::core::cmp::PartialEq for ExternalSourceKind {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::Present(__self_0), Self::Present(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ExternalSourceKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Arc<String>>;
}
}Eq, #[automatically_derived]
impl ::core::clone::Clone for ExternalSourceKind {
#[inline]
fn clone(&self) -> Self {
match self {
Self::Present(__self_0) =>
Self::Present(::core::clone::Clone::clone(__self_0)),
Self::AbsentOk => Self::AbsentOk,
Self::AbsentErr => Self::AbsentErr,
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ExternalSourceKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Present(__self_0) =>
::core::fmt::Formatter::debug_tuple_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)]
1694pub enum ExternalSourceKind {
1695 Present(Arc<String>),
1697 AbsentOk,
1699 AbsentErr,
1701}
1702
1703impl ExternalSource {
1704 pub fn get_source(&self) -> Option<&str> {
1705 match self {
1706 ExternalSource::Foreign { kind: ExternalSourceKind::Present(src), .. } => Some(src),
1707 _ => None,
1708 }
1709 }
1710}
1711
1712#[derive(#[automatically_derived]
impl ::core::fmt::Debug for OffsetOverflowError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f, "OffsetOverflowError")
}
}Debug)]
1713pub struct OffsetOverflowError;
1714
1715#[derive(#[automatically_derived]
impl ::core::marker::Copy for SourceFileHashAlgorithm { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for SourceFileHashAlgorithm { }
#[automatically_derived]
impl ::core::clone::Clone for SourceFileHashAlgorithm {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for SourceFileHashAlgorithm {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
SourceFileHashAlgorithm::Md5 => "Md5",
SourceFileHashAlgorithm::Sha1 => "Sha1",
SourceFileHashAlgorithm::Sha256 => "Sha256",
SourceFileHashAlgorithm::Blake3 => "Blake3",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for SourceFileHashAlgorithm { }
#[automatically_derived]
impl ::core::cmp::PartialEq for SourceFileHashAlgorithm {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for SourceFileHashAlgorithm { }Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for SourceFileHashAlgorithm {
#[inline]
fn partial_cmp(&self, other: &Self)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for SourceFileHashAlgorithm {
#[inline]
fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
::core::cmp::Ord::cmp(&::core::intrinsics::discriminant_value(self),
&::core::intrinsics::discriminant_value(other))
}
}Ord, #[automatically_derived]
impl ::core::hash::Hash for SourceFileHashAlgorithm {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
state)
}
}Hash, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for SourceFileHashAlgorithm {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
SourceFileHashAlgorithm::Md5 => { 0usize }
SourceFileHashAlgorithm::Sha1 => { 1usize }
SourceFileHashAlgorithm::Sha256 => { 2usize }
SourceFileHashAlgorithm::Blake3 => { 3usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for SourceFileHashAlgorithm {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => { SourceFileHashAlgorithm::Md5 }
1usize => { SourceFileHashAlgorithm::Sha1 }
2usize => { SourceFileHashAlgorithm::Sha256 }
3usize => { SourceFileHashAlgorithm::Blake3 }
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `SourceFileHashAlgorithm`, expected 0..4, actual {0}",
n));
}
}
}
}
};Decodable)]
1716#[derive(const _: () =
{
impl ::rustc_data_structures::stable_hash::StableHash for
SourceFileHashAlgorithm {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
::std::mem::discriminant(self).stable_hash(__hcx, __hasher);
match *self {
SourceFileHashAlgorithm::Md5 => {}
SourceFileHashAlgorithm::Sha1 => {}
SourceFileHashAlgorithm::Sha256 => {}
SourceFileHashAlgorithm::Blake3 => {}
}
}
}
};StableHash)]
1717pub enum SourceFileHashAlgorithm {
1718 Md5,
1719 Sha1,
1720 Sha256,
1721 Blake3,
1722}
1723
1724impl Display for SourceFileHashAlgorithm {
1725 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1726 f.write_str(match self {
1727 Self::Md5 => "md5",
1728 Self::Sha1 => "sha1",
1729 Self::Sha256 => "sha256",
1730 Self::Blake3 => "blake3",
1731 })
1732 }
1733}
1734
1735impl FromStr for SourceFileHashAlgorithm {
1736 type Err = ();
1737
1738 fn from_str(s: &str) -> Result<SourceFileHashAlgorithm, ()> {
1739 match s {
1740 "md5" => Ok(SourceFileHashAlgorithm::Md5),
1741 "sha1" => Ok(SourceFileHashAlgorithm::Sha1),
1742 "sha256" => Ok(SourceFileHashAlgorithm::Sha256),
1743 "blake3" => Ok(SourceFileHashAlgorithm::Blake3),
1744 _ => Err(()),
1745 }
1746 }
1747}
1748
1749#[derive(#[automatically_derived]
impl ::core::marker::Copy for SourceFileHash { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for SourceFileHash { }
#[automatically_derived]
impl ::core::clone::Clone for SourceFileHash {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<SourceFileHashAlgorithm>;
let _: ::core::clone::AssertParamIsClone<[u8; 32]>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for SourceFileHash { }
#[automatically_derived]
impl ::core::cmp::PartialEq for SourceFileHash {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.kind == other.kind && self.value == other.value
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for SourceFileHash {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<SourceFileHashAlgorithm>;
let _: ::core::cmp::AssertParamIsEq<[u8; 32]>;
}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for SourceFileHash {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"SourceFileHash", "kind", &self.kind, "value", &&self.value)
}
}Debug, #[automatically_derived]
impl ::core::hash::Hash for SourceFileHash {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.kind, state);
::core::hash::Hash::hash(&self.value, state)
}
}Hash)]
1751#[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)]
1752pub struct SourceFileHash {
1753 pub kind: SourceFileHashAlgorithm,
1754 value: [u8; 32],
1755}
1756
1757impl Display for SourceFileHash {
1758 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1759 f.write_fmt(format_args!("{0}=", self.kind))write!(f, "{}=", self.kind)?;
1760 for byte in self.value[0..self.hash_len()].into_iter() {
1761 f.write_fmt(format_args!("{0:02x}", byte))write!(f, "{byte:02x}")?;
1762 }
1763 Ok(())
1764 }
1765}
1766
1767impl SourceFileHash {
1768 pub fn new_in_memory(kind: SourceFileHashAlgorithm, src: impl AsRef<[u8]>) -> SourceFileHash {
1769 let mut hash = SourceFileHash { kind, value: Default::default() };
1770 let len = hash.hash_len();
1771 let value = &mut hash.value[..len];
1772 let data = src.as_ref();
1773 match kind {
1774 SourceFileHashAlgorithm::Md5 => {
1775 value.copy_from_slice(&Md5::digest(data));
1776 }
1777 SourceFileHashAlgorithm::Sha1 => {
1778 value.copy_from_slice(&Sha1::digest(data));
1779 }
1780 SourceFileHashAlgorithm::Sha256 => {
1781 value.copy_from_slice(&Sha256::digest(data));
1782 }
1783 SourceFileHashAlgorithm::Blake3 => value.copy_from_slice(blake3::hash(data).as_bytes()),
1784 };
1785 hash
1786 }
1787
1788 pub fn new(kind: SourceFileHashAlgorithm, src: impl Read) -> Result<SourceFileHash, io::Error> {
1789 let mut hash = SourceFileHash { kind, value: Default::default() };
1790 let len = hash.hash_len();
1791 let value = &mut hash.value[..len];
1792 let mut buf = ::alloc::vec::from_elem(0, 16 * 1024)vec![0; 16 * 1024];
1795
1796 fn digest<T>(
1797 mut hasher: T,
1798 mut update: impl FnMut(&mut T, &[u8]),
1799 finish: impl FnOnce(T, &mut [u8]),
1800 mut src: impl Read,
1801 buf: &mut [u8],
1802 value: &mut [u8],
1803 ) -> Result<(), io::Error> {
1804 loop {
1805 let bytes_read = src.read(buf)?;
1806 if bytes_read == 0 {
1807 break;
1808 }
1809 update(&mut hasher, &buf[0..bytes_read]);
1810 }
1811 finish(hasher, value);
1812 Ok(())
1813 }
1814
1815 match kind {
1816 SourceFileHashAlgorithm::Sha256 => {
1817 digest(
1818 Sha256::new(),
1819 |h, b| {
1820 h.update(b);
1821 },
1822 |h, out| out.copy_from_slice(&h.finalize()),
1823 src,
1824 &mut buf,
1825 value,
1826 )?;
1827 }
1828 SourceFileHashAlgorithm::Sha1 => {
1829 digest(
1830 Sha1::new(),
1831 |h, b| {
1832 h.update(b);
1833 },
1834 |h, out| out.copy_from_slice(&h.finalize()),
1835 src,
1836 &mut buf,
1837 value,
1838 )?;
1839 }
1840 SourceFileHashAlgorithm::Md5 => {
1841 digest(
1842 Md5::new(),
1843 |h, b| {
1844 h.update(b);
1845 },
1846 |h, out| out.copy_from_slice(&h.finalize()),
1847 src,
1848 &mut buf,
1849 value,
1850 )?;
1851 }
1852 SourceFileHashAlgorithm::Blake3 => {
1853 digest(
1854 blake3::Hasher::new(),
1855 |h, b| {
1856 h.update(b);
1857 },
1858 |h, out| out.copy_from_slice(h.finalize().as_bytes()),
1859 src,
1860 &mut buf,
1861 value,
1862 )?;
1863 }
1864 }
1865 Ok(hash)
1866 }
1867
1868 pub fn matches(&self, src: &str) -> bool {
1870 Self::new_in_memory(self.kind, src.as_bytes()) == *self
1871 }
1872
1873 pub fn hash_bytes(&self) -> &[u8] {
1875 let len = self.hash_len();
1876 &self.value[..len]
1877 }
1878
1879 fn hash_len(&self) -> usize {
1880 match self.kind {
1881 SourceFileHashAlgorithm::Md5 => 16,
1882 SourceFileHashAlgorithm::Sha1 => 20,
1883 SourceFileHashAlgorithm::Sha256 | SourceFileHashAlgorithm::Blake3 => 32,
1884 }
1885 }
1886}
1887
1888#[derive(#[automatically_derived]
impl ::core::clone::Clone for SourceFileLines {
#[inline]
fn clone(&self) -> Self {
match self {
Self::Lines(__self_0) =>
Self::Lines(::core::clone::Clone::clone(__self_0)),
Self::Diffs(__self_0) =>
Self::Diffs(::core::clone::Clone::clone(__self_0)),
}
}
}Clone)]
1889pub enum SourceFileLines {
1890 Lines(Vec<RelativeBytePos>),
1892
1893 Diffs(SourceFileDiffs),
1895}
1896
1897impl SourceFileLines {
1898 pub fn is_lines(&self) -> bool {
1899 #[allow(non_exhaustive_omitted_patterns)] match self {
SourceFileLines::Lines(_) => true,
_ => false,
}matches!(self, SourceFileLines::Lines(_))
1900 }
1901}
1902
1903#[derive(#[automatically_derived]
impl ::core::clone::Clone for SourceFileDiffs {
#[inline]
fn clone(&self) -> Self {
Self {
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)]
1911pub struct SourceFileDiffs {
1912 bytes_per_diff: usize,
1916
1917 num_diffs: usize,
1920
1921 raw_diffs: Vec<u8>,
1927}
1928
1929pub struct SourceFile {
1931 pub name: FileName,
1935 pub src: Option<Arc<String>>,
1937 pub src_hash: SourceFileHash,
1939 pub checksum_hash: Option<SourceFileHash>,
1943 pub external_src: FreezeLock<ExternalSource>,
1946 pub start_pos: BytePos,
1948 pub normalized_source_len: RelativeBytePos,
1950 pub unnormalized_source_len: u32,
1952 pub lines: FreezeLock<SourceFileLines>,
1954 pub multibyte_chars: Vec<MultiByteChar>,
1956 pub normalized_pos: Vec<NormalizedPos>,
1958 pub stable_id: StableSourceFileId,
1962 pub cnum: CrateNum,
1964}
1965
1966impl Clone for SourceFile {
1967 fn clone(&self) -> Self {
1968 Self {
1969 name: self.name.clone(),
1970 src: self.src.clone(),
1971 src_hash: self.src_hash,
1972 checksum_hash: self.checksum_hash,
1973 external_src: self.external_src.clone(),
1974 start_pos: self.start_pos,
1975 normalized_source_len: self.normalized_source_len,
1976 unnormalized_source_len: self.unnormalized_source_len,
1977 lines: self.lines.clone(),
1978 multibyte_chars: self.multibyte_chars.clone(),
1979 normalized_pos: self.normalized_pos.clone(),
1980 stable_id: self.stable_id,
1981 cnum: self.cnum,
1982 }
1983 }
1984}
1985
1986impl<S: SpanEncoder> Encodable<S> for SourceFile {
1987 fn encode(&self, s: &mut S) {
1988 self.name.encode(s);
1989 self.src_hash.encode(s);
1990 self.checksum_hash.encode(s);
1991 self.normalized_source_len.encode(s);
1993 self.unnormalized_source_len.encode(s);
1994
1995 if !self.lines.read().is_lines() {
::core::panicking::panic("assertion failed: self.lines.read().is_lines()")
};assert!(self.lines.read().is_lines());
1997 let lines = self.lines();
1998 s.emit_u32(lines.len() as u32);
2000
2001 if lines.len() != 0 {
2003 let max_line_length = if lines.len() == 1 {
2004 0
2005 } else {
2006 lines
2007 .array_windows()
2008 .map(|&[fst, snd]| snd - fst)
2009 .map(|bp| bp.to_usize())
2010 .max()
2011 .unwrap()
2012 };
2013
2014 let bytes_per_diff: usize = match max_line_length {
2015 0..=0xFF => 1,
2016 0x100..=0xFFFF => 2,
2017 _ => 4,
2018 };
2019
2020 s.emit_u8(bytes_per_diff as u8);
2022
2023 {
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));
2025
2026 let diff_iter = lines.array_windows().map(|&[fst, snd]| snd - fst);
2028 let num_diffs = lines.len() - 1;
2029 let mut raw_diffs;
2030 match bytes_per_diff {
2031 1 => {
2032 raw_diffs = Vec::with_capacity(num_diffs);
2033 for diff in diff_iter {
2034 raw_diffs.push(diff.0 as u8);
2035 }
2036 }
2037 2 => {
2038 raw_diffs = Vec::with_capacity(bytes_per_diff * num_diffs);
2039 for diff in diff_iter {
2040 raw_diffs.extend_from_slice(&(diff.0 as u16).to_le_bytes());
2041 }
2042 }
2043 4 => {
2044 raw_diffs = Vec::with_capacity(bytes_per_diff * num_diffs);
2045 for diff in diff_iter {
2046 raw_diffs.extend_from_slice(&(diff.0).to_le_bytes());
2047 }
2048 }
2049 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
2050 }
2051 s.emit_raw_bytes(&raw_diffs);
2052 }
2053
2054 self.multibyte_chars.encode(s);
2055 self.stable_id.encode(s);
2056 self.normalized_pos.encode(s);
2057 self.cnum.encode(s);
2058 }
2059}
2060
2061impl<D: SpanDecoder> Decodable<D> for SourceFile {
2062 fn decode(d: &mut D) -> SourceFile {
2063 let name: FileName = Decodable::decode(d);
2064 let src_hash: SourceFileHash = Decodable::decode(d);
2065 let checksum_hash: Option<SourceFileHash> = Decodable::decode(d);
2066 let normalized_source_len: RelativeBytePos = Decodable::decode(d);
2067 let unnormalized_source_len = Decodable::decode(d);
2068 let lines = {
2069 let num_lines: u32 = Decodable::decode(d);
2070 if num_lines > 0 {
2071 let bytes_per_diff = d.read_u8() as usize;
2073
2074 let num_diffs = num_lines as usize - 1;
2076 let raw_diffs = d.read_raw_bytes(bytes_per_diff * num_diffs).to_vec();
2077 SourceFileLines::Diffs(SourceFileDiffs { bytes_per_diff, num_diffs, raw_diffs })
2078 } else {
2079 SourceFileLines::Lines(::alloc::vec::Vec::new()vec![])
2080 }
2081 };
2082 let multibyte_chars: Vec<MultiByteChar> = Decodable::decode(d);
2083 let stable_id = Decodable::decode(d);
2084 let normalized_pos: Vec<NormalizedPos> = Decodable::decode(d);
2085 let cnum: CrateNum = Decodable::decode(d);
2086 SourceFile {
2087 name,
2088 start_pos: BytePos::from_u32(0),
2089 normalized_source_len,
2090 unnormalized_source_len,
2091 src: None,
2092 src_hash,
2093 checksum_hash,
2094 external_src: FreezeLock::frozen(ExternalSource::Unneeded),
2097 lines: FreezeLock::new(lines),
2098 multibyte_chars,
2099 normalized_pos,
2100 stable_id,
2101 cnum,
2102 }
2103 }
2104}
2105
2106impl fmt::Debug for SourceFile {
2107 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2108 fmt.write_fmt(format_args!("SourceFile({0:?})", self.name))write!(fmt, "SourceFile({:?})", self.name)
2109 }
2110}
2111
2112#[derive(#[automatically_derived]
impl ::core::fmt::Debug for StableSourceFileId {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"StableSourceFileId", &&self.0)
}
}Debug, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for StableSourceFileId { }
#[automatically_derived]
impl ::core::clone::Clone for StableSourceFileId {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<Hash128>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for StableSourceFileId { }Copy, #[automatically_derived]
impl ::core::hash::Hash for StableSourceFileId {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}Hash, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for StableSourceFileId { }
#[automatically_derived]
impl ::core::cmp::PartialEq for StableSourceFileId {
#[inline]
fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for StableSourceFileId {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Hash128>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for StableSourceFileId {
#[inline]
fn partial_cmp(&self, other: &Self)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd, #[automatically_derived]
impl ::core::default::Default for StableSourceFileId {
#[inline]
fn default() -> Self { Self(::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)]
2134#[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)]
2135pub struct StableSourceFileId(Hash128);
2136
2137impl StableSourceFileId {
2138 fn from_filename_in_current_crate(filename: &FileName) -> Self {
2139 Self::from_filename_and_stable_crate_id(filename, None)
2140 }
2141
2142 pub fn from_filename_for_export(
2143 filename: &FileName,
2144 local_crate_stable_crate_id: StableCrateId,
2145 ) -> Self {
2146 Self::from_filename_and_stable_crate_id(filename, Some(local_crate_stable_crate_id))
2147 }
2148
2149 fn from_filename_and_stable_crate_id(
2150 filename: &FileName,
2151 stable_crate_id: Option<StableCrateId>,
2152 ) -> Self {
2153 let mut hasher = StableHasher::new();
2154 filename.hash(&mut hasher);
2155 stable_crate_id.hash(&mut hasher);
2156 StableSourceFileId(hasher.finish())
2157 }
2158}
2159
2160impl SourceFile {
2161 const MAX_FILE_SIZE: u32 = u32::MAX - 1;
2162
2163 pub fn new(
2164 name: FileName,
2165 mut src: String,
2166 hash_kind: SourceFileHashAlgorithm,
2167 checksum_hash_kind: Option<SourceFileHashAlgorithm>,
2168 ) -> Result<Self, OffsetOverflowError> {
2169 let src_hash = SourceFileHash::new_in_memory(hash_kind, src.as_bytes());
2171 let checksum_hash = checksum_hash_kind.map(|checksum_hash_kind| {
2172 if checksum_hash_kind == hash_kind {
2173 src_hash
2174 } else {
2175 SourceFileHash::new_in_memory(checksum_hash_kind, src.as_bytes())
2176 }
2177 });
2178 let unnormalized_source_len = u32::try_from(src.len()).map_err(|_| OffsetOverflowError)?;
2180 if unnormalized_source_len > Self::MAX_FILE_SIZE {
2181 return Err(OffsetOverflowError);
2182 }
2183
2184 let normalized_pos = normalize_src(&mut src);
2185
2186 let stable_id = StableSourceFileId::from_filename_in_current_crate(&name);
2187 let normalized_source_len = u32::try_from(src.len()).map_err(|_| OffsetOverflowError)?;
2188 if normalized_source_len > Self::MAX_FILE_SIZE {
2189 return Err(OffsetOverflowError);
2190 }
2191
2192 let (lines, multibyte_chars) = analyze_source_file::analyze_source_file(&src);
2193
2194 Ok(SourceFile {
2195 name,
2196 src: Some(Arc::new(src)),
2197 src_hash,
2198 checksum_hash,
2199 external_src: FreezeLock::frozen(ExternalSource::Unneeded),
2200 start_pos: BytePos::from_u32(0),
2201 normalized_source_len: RelativeBytePos::from_u32(normalized_source_len),
2202 unnormalized_source_len,
2203 lines: FreezeLock::frozen(SourceFileLines::Lines(lines)),
2204 multibyte_chars,
2205 normalized_pos,
2206 stable_id,
2207 cnum: LOCAL_CRATE,
2208 })
2209 }
2210
2211 fn convert_diffs_to_lines_frozen(&self) {
2214 let mut guard = if let Some(guard) = self.lines.try_write() { guard } else { return };
2215
2216 let SourceFileDiffs { bytes_per_diff, num_diffs, raw_diffs } = match &*guard {
2217 SourceFileLines::Diffs(diffs) => diffs,
2218 SourceFileLines::Lines(..) => {
2219 FreezeWriteGuard::freeze(guard);
2220 return;
2221 }
2222 };
2223
2224 let num_lines = num_diffs + 1;
2226 let mut lines = Vec::with_capacity(num_lines);
2227 let mut line_start = RelativeBytePos(0);
2228 lines.push(line_start);
2229
2230 {
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);
2231 match bytes_per_diff {
2232 1 => {
2233 lines.extend(raw_diffs.into_iter().map(|&diff| {
2234 line_start = line_start + RelativeBytePos(diff as u32);
2235 line_start
2236 }));
2237 }
2238 2 => {
2239 lines.extend((0..*num_diffs).map(|i| {
2240 let pos = bytes_per_diff * i;
2241 let bytes = [raw_diffs[pos], raw_diffs[pos + 1]];
2242 let diff = u16::from_le_bytes(bytes);
2243 line_start = line_start + RelativeBytePos(diff as u32);
2244 line_start
2245 }));
2246 }
2247 4 => {
2248 lines.extend((0..*num_diffs).map(|i| {
2249 let pos = bytes_per_diff * i;
2250 let bytes = [
2251 raw_diffs[pos],
2252 raw_diffs[pos + 1],
2253 raw_diffs[pos + 2],
2254 raw_diffs[pos + 3],
2255 ];
2256 let diff = u32::from_le_bytes(bytes);
2257 line_start = line_start + RelativeBytePos(diff);
2258 line_start
2259 }));
2260 }
2261 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
2262 }
2263
2264 *guard = SourceFileLines::Lines(lines);
2265
2266 FreezeWriteGuard::freeze(guard);
2267 }
2268
2269 pub fn lines(&self) -> &[RelativeBytePos] {
2270 if let Some(SourceFileLines::Lines(lines)) = self.lines.get() {
2271 return &lines[..];
2272 }
2273
2274 outline(|| {
2275 self.convert_diffs_to_lines_frozen();
2276 if let Some(SourceFileLines::Lines(lines)) = self.lines.get() {
2277 return &lines[..];
2278 }
2279 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
2280 })
2281 }
2282
2283 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
2285 let pos = self.relative_position(pos);
2286 let line_index = self.lookup_line(pos).unwrap();
2287 let line_start_pos = self.lines()[line_index];
2288 self.absolute_position(line_start_pos)
2289 }
2290
2291 pub fn add_external_src<F>(&self, get_src: F) -> bool
2296 where
2297 F: FnOnce() -> Option<String>,
2298 {
2299 if !self.external_src.is_frozen() {
2300 let src = get_src();
2301 let src = src.and_then(|mut src| {
2302 self.src_hash.matches(&src).then(|| {
2304 normalize_src(&mut src);
2305 src
2306 })
2307 });
2308
2309 self.external_src.try_write().map(|mut external_src| {
2310 if let ExternalSource::Foreign {
2311 kind: src_kind @ ExternalSourceKind::AbsentOk,
2312 ..
2313 } = &mut *external_src
2314 {
2315 *src_kind = if let Some(src) = src {
2316 ExternalSourceKind::Present(Arc::new(src))
2317 } else {
2318 ExternalSourceKind::AbsentErr
2319 };
2320 } else {
2321 {
::core::panicking::panic_fmt(format_args!("unexpected state {0:?}",
*external_src));
}panic!("unexpected state {:?}", *external_src)
2322 }
2323
2324 FreezeWriteGuard::freeze(external_src)
2326 });
2327 }
2328
2329 self.src.is_some() || self.external_src.read().get_source().is_some()
2330 }
2331
2332 pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
2335 fn get_until_newline(src: &str, begin: usize) -> &str {
2336 let slice = &src[begin..];
2340 match slice.find('\n') {
2341 Some(e) => &slice[..e],
2342 None => slice,
2343 }
2344 }
2345
2346 let begin = {
2347 let line = self.lines().get(line_number).copied()?;
2348 line.to_usize()
2349 };
2350
2351 if let Some(ref src) = self.src {
2352 Some(Cow::from(get_until_newline(src, begin)))
2353 } else {
2354 self.external_src
2355 .borrow()
2356 .get_source()
2357 .map(|src| Cow::Owned(String::from(get_until_newline(src, begin))))
2358 }
2359 }
2360
2361 pub fn is_real_file(&self) -> bool {
2362 self.name.is_real()
2363 }
2364
2365 #[inline]
2366 pub fn is_imported(&self) -> bool {
2367 self.src.is_none()
2368 }
2369
2370 pub fn count_lines(&self) -> usize {
2371 self.lines().len()
2372 }
2373
2374 #[inline]
2375 pub fn absolute_position(&self, pos: RelativeBytePos) -> BytePos {
2376 BytePos::from_u32(pos.to_u32() + self.start_pos.to_u32())
2377 }
2378
2379 #[inline]
2380 pub fn relative_position(&self, pos: BytePos) -> RelativeBytePos {
2381 RelativeBytePos::from_u32(pos.to_u32() - self.start_pos.to_u32())
2382 }
2383
2384 #[inline]
2385 pub fn end_position(&self) -> BytePos {
2386 self.absolute_position(self.normalized_source_len)
2387 }
2388
2389 pub fn lookup_line(&self, pos: RelativeBytePos) -> Option<usize> {
2394 self.lines().partition_point(|x| x <= &pos).checked_sub(1)
2395 }
2396
2397 pub fn line_bounds(&self, line_index: usize) -> Range<BytePos> {
2398 if self.is_empty() {
2399 return self.start_pos..self.start_pos;
2400 }
2401
2402 let lines = self.lines();
2403 if !(line_index < lines.len()) {
::core::panicking::panic("assertion failed: line_index < lines.len()")
};assert!(line_index < lines.len());
2404 if line_index == (lines.len() - 1) {
2405 self.absolute_position(lines[line_index])..self.end_position()
2406 } else {
2407 self.absolute_position(lines[line_index])..self.absolute_position(lines[line_index + 1])
2408 }
2409 }
2410
2411 #[inline]
2416 pub fn contains(&self, byte_pos: BytePos) -> bool {
2417 byte_pos >= self.start_pos && byte_pos <= self.end_position()
2418 }
2419
2420 #[inline]
2421 pub fn is_empty(&self) -> bool {
2422 self.normalized_source_len.to_u32() == 0
2423 }
2424
2425 pub fn original_relative_byte_pos(&self, pos: BytePos) -> RelativeBytePos {
2428 let pos = self.relative_position(pos);
2429
2430 let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) {
2434 Ok(i) => self.normalized_pos[i].diff,
2435 Err(0) => 0,
2436 Err(i) => self.normalized_pos[i - 1].diff,
2437 };
2438
2439 RelativeBytePos::from_u32(pos.0 + diff)
2440 }
2441
2442 pub fn normalized_byte_pos(&self, offset: u32) -> BytePos {
2452 let diff =
2453 match self.normalized_pos.binary_search_by(|np| (np.pos.0 + np.diff).cmp(&offset)) {
2454 Ok(i) => self.normalized_pos[i].diff,
2455 Err(0) => 0,
2456 Err(i) => self.normalized_pos[i - 1].diff,
2457 };
2458
2459 BytePos::from_u32(self.start_pos.0 + offset - diff)
2460 }
2461
2462 fn bytepos_to_file_charpos(&self, bpos: RelativeBytePos) -> CharPos {
2464 let mut total_extra_bytes = 0;
2466
2467 for mbc in self.multibyte_chars.iter() {
2468 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_span/src/lib.rs:2468",
"rustc_span", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_span/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2468u32),
::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);
2469 if mbc.pos < bpos {
2470 total_extra_bytes += mbc.bytes as u32 - 1;
2473 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);
2476 } else {
2477 break;
2478 }
2479 }
2480
2481 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());
2482 CharPos(bpos.to_usize() - total_extra_bytes as usize)
2483 }
2484
2485 fn lookup_file_pos(&self, pos: RelativeBytePos) -> (usize, CharPos) {
2488 let chpos = self.bytepos_to_file_charpos(pos);
2489 match self.lookup_line(pos) {
2490 Some(a) => {
2491 let line = a + 1; let linebpos = self.lines()[a];
2493 let linechpos = self.bytepos_to_file_charpos(linebpos);
2494 let col = chpos - linechpos;
2495 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_span/src/lib.rs:2495",
"rustc_span", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_span/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2495u32),
::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);
2496 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_span/src/lib.rs:2496",
"rustc_span", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_span/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2496u32),
::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);
2497 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_span/src/lib.rs:2497",
"rustc_span", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_span/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2497u32),
::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);
2498 if !(chpos >= linechpos) {
::core::panicking::panic("assertion failed: chpos >= linechpos")
};assert!(chpos >= linechpos);
2499 (line, col)
2500 }
2501 None => (0, chpos),
2502 }
2503 }
2504
2505 pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) {
2508 let pos = self.relative_position(pos);
2509 let (line, col_or_chpos) = self.lookup_file_pos(pos);
2510 if line > 0 {
2511 let Some(code) = self.get_line(line - 1) else {
2512 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_span/src/lib.rs:2519",
"rustc_span", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_span/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2519u32),
::tracing_core::__macro_support::Option::Some("rustc_span"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::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);
2520 return (line, col_or_chpos, col_or_chpos.0);
2521 };
2522 let display_col = code.chars().take(col_or_chpos.0).map(|ch| char_width(ch)).sum();
2523 (line, col_or_chpos, display_col)
2524 } else {
2525 (0, col_or_chpos, col_or_chpos.0)
2527 }
2528 }
2529}
2530
2531pub fn char_width(ch: char) -> usize {
2532 match ch {
2535 '\t' => 4,
2536 '\u{0000}' | '\u{0001}' | '\u{0002}' | '\u{0003}' | '\u{0004}' | '\u{0005}'
2540 | '\u{0006}' | '\u{0007}' | '\u{0008}' | '\u{000B}' | '\u{000C}' | '\u{000D}'
2541 | '\u{000E}' | '\u{000F}' | '\u{0010}' | '\u{0011}' | '\u{0012}' | '\u{0013}'
2542 | '\u{0014}' | '\u{0015}' | '\u{0016}' | '\u{0017}' | '\u{0018}' | '\u{0019}'
2543 | '\u{001A}' | '\u{001B}' | '\u{001C}' | '\u{001D}' | '\u{001E}' | '\u{001F}'
2544 | '\u{007F}' | '\u{202A}' | '\u{202B}' | '\u{202D}' | '\u{202E}' | '\u{2066}'
2545 | '\u{2067}' | '\u{2068}' | '\u{202C}' | '\u{2069}' => 1,
2546 _ => unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1),
2547 }
2548}
2549
2550pub fn str_width(s: &str) -> usize {
2551 s.chars().map(char_width).sum()
2552}
2553
2554fn normalize_src(src: &mut String) -> Vec<NormalizedPos> {
2556 let mut normalized_pos = ::alloc::vec::Vec::new()vec![];
2557 remove_bom(src, &mut normalized_pos);
2558 normalize_newlines(src, &mut normalized_pos);
2559 normalized_pos
2560}
2561
2562fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
2564 if src.starts_with('\u{feff}') {
2565 src.drain(..3);
2566 normalized_pos.push(NormalizedPos { pos: RelativeBytePos(0), diff: 3 });
2567 }
2568}
2569
2570fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
2574 if !src.as_bytes().contains(&b'\r') {
2575 return;
2576 }
2577
2578 let mut buf = std::mem::take(src).into_bytes();
2584 let mut gap_len = 0;
2585 let mut tail = buf.as_mut_slice();
2586 let mut cursor = 0;
2587 let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
2588 loop {
2589 let idx = match find_crlf(&tail[gap_len..]) {
2590 None => tail.len(),
2591 Some(idx) => idx + gap_len,
2592 };
2593 tail.copy_within(gap_len..idx, 0);
2594 tail = &mut tail[idx - gap_len..];
2595 if tail.len() == gap_len {
2596 break;
2597 }
2598 cursor += idx - gap_len;
2599 gap_len += 1;
2600 normalized_pos.push(NormalizedPos {
2601 pos: RelativeBytePos::from_usize(cursor + 1),
2602 diff: original_gap + gap_len as u32,
2603 });
2604 }
2605
2606 let new_len = buf.len() - gap_len;
2609 unsafe {
2610 buf.set_len(new_len);
2611 *src = String::from_utf8_unchecked(buf);
2612 }
2613
2614 fn find_crlf(src: &[u8]) -> Option<usize> {
2615 let mut search_idx = 0;
2616 while let Some(idx) = find_cr(&src[search_idx..]) {
2617 if src[search_idx..].get(idx + 1) != Some(&b'\n') {
2618 search_idx += idx + 1;
2619 continue;
2620 }
2621 return Some(search_idx + idx);
2622 }
2623 None
2624 }
2625
2626 fn find_cr(src: &[u8]) -> Option<usize> {
2627 src.iter().position(|&b| b == b'\r')
2628 }
2629}
2630
2631pub trait Pos {
2636 fn from_usize(n: usize) -> Self;
2637 fn to_usize(&self) -> usize;
2638 fn from_u32(n: u32) -> Self;
2639 fn to_u32(&self) -> u32;
2640}
2641
2642macro_rules! impl_pos {
2643 (
2644 $(
2645 $(#[$attr:meta])*
2646 $vis:vis struct $ident:ident($inner_vis:vis $inner_ty:ty);
2647 )*
2648 ) => {
2649 $(
2650 $(#[$attr])*
2651 $vis struct $ident($inner_vis $inner_ty);
2652
2653 impl Pos for $ident {
2654 #[inline(always)]
2655 fn from_usize(n: usize) -> $ident {
2656 $ident(n as $inner_ty)
2657 }
2658
2659 #[inline(always)]
2660 fn to_usize(&self) -> usize {
2661 self.0 as usize
2662 }
2663
2664 #[inline(always)]
2665 fn from_u32(n: u32) -> $ident {
2666 $ident(n as $inner_ty)
2667 }
2668
2669 #[inline(always)]
2670 fn to_u32(&self) -> u32 {
2671 self.0 as u32
2672 }
2673 }
2674
2675 impl Add for $ident {
2676 type Output = $ident;
2677
2678 #[inline(always)]
2679 fn add(self, rhs: $ident) -> $ident {
2680 $ident(self.0 + rhs.0)
2681 }
2682 }
2683
2684 impl Sub for $ident {
2685 type Output = $ident;
2686
2687 #[inline(always)]
2688 fn sub(self, rhs: $ident) -> $ident {
2689 $ident(self.0 - rhs.0)
2690 }
2691 }
2692 )*
2693 };
2694}
2695
2696#[doc = r" A byte offset."]
#[doc = r""]
#[doc =
r" Keep this small (currently 32-bits), as AST contains a lot of them."]
pub struct BytePos(pub u32);
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for BytePos { }
#[automatically_derived]
impl ::core::clone::Clone for BytePos {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<u32>;
*self
}
}
#[automatically_derived]
impl ::core::marker::Copy for BytePos { }
#[automatically_derived]
impl ::core::marker::StructuralPartialEq for BytePos { }
#[automatically_derived]
impl ::core::cmp::PartialEq for BytePos {
#[inline]
fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}
#[automatically_derived]
impl ::core::cmp::Eq for BytePos {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<u32>;
}
}
#[automatically_derived]
impl ::core::hash::Hash for BytePos {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}
#[automatically_derived]
impl ::core::cmp::PartialOrd for BytePos {
#[inline]
fn partial_cmp(&self, other: &Self)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}
#[automatically_derived]
impl ::core::cmp::Ord for BytePos {
#[inline]
fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
::core::cmp::Ord::cmp(&self.0, &other.0)
}
}
#[automatically_derived]
impl ::core::fmt::Debug for BytePos {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f, "BytePos",
&&self.0)
}
}
impl Pos for BytePos {
#[inline(always)]
fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
#[inline(always)]
fn to_usize(&self) -> usize { self.0 as usize }
#[inline(always)]
fn from_u32(n: u32) -> BytePos { BytePos(n as u32) }
#[inline(always)]
fn to_u32(&self) -> u32 { self.0 as u32 }
}
impl Add for BytePos {
type Output = BytePos;
#[inline(always)]
fn add(self, rhs: BytePos) -> BytePos { BytePos(self.0 + rhs.0) }
}
impl Sub for BytePos {
type Output = BytePos;
#[inline(always)]
fn sub(self, rhs: BytePos) -> BytePos { BytePos(self.0 - rhs.0) }
}
#[doc = r" A byte offset relative to file beginning."]
pub struct RelativeBytePos(pub u32);
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for RelativeBytePos { }
#[automatically_derived]
impl ::core::clone::Clone for RelativeBytePos {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<u32>;
*self
}
}
#[automatically_derived]
impl ::core::marker::Copy for RelativeBytePos { }
#[automatically_derived]
impl ::core::marker::StructuralPartialEq for RelativeBytePos { }
#[automatically_derived]
impl ::core::cmp::PartialEq for RelativeBytePos {
#[inline]
fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}
#[automatically_derived]
impl ::core::cmp::Eq for RelativeBytePos {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<u32>;
}
}
#[automatically_derived]
impl ::core::hash::Hash for RelativeBytePos {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}
#[automatically_derived]
impl ::core::cmp::PartialOrd for RelativeBytePos {
#[inline]
fn partial_cmp(&self, other: &Self)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}
#[automatically_derived]
impl ::core::cmp::Ord for RelativeBytePos {
#[inline]
fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
::core::cmp::Ord::cmp(&self.0, &other.0)
}
}
#[automatically_derived]
impl ::core::fmt::Debug for RelativeBytePos {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"RelativeBytePos", &&self.0)
}
}
const _: () =
{
impl ::rustc_data_structures::stable_hash::StableHash for
RelativeBytePos {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
match *self {
RelativeBytePos(ref __binding_0) => {
{ __binding_0.stable_hash(__hcx, __hasher); }
}
}
}
}
};
impl Pos for RelativeBytePos {
#[inline(always)]
fn from_usize(n: usize) -> RelativeBytePos { RelativeBytePos(n as u32) }
#[inline(always)]
fn to_usize(&self) -> usize { self.0 as usize }
#[inline(always)]
fn from_u32(n: u32) -> RelativeBytePos { RelativeBytePos(n as u32) }
#[inline(always)]
fn to_u32(&self) -> u32 { self.0 as u32 }
}
impl Add for RelativeBytePos {
type Output = RelativeBytePos;
#[inline(always)]
fn add(self, rhs: RelativeBytePos) -> RelativeBytePos {
RelativeBytePos(self.0 + rhs.0)
}
}
impl Sub for RelativeBytePos {
type Output = RelativeBytePos;
#[inline(always)]
fn sub(self, rhs: RelativeBytePos) -> RelativeBytePos {
RelativeBytePos(self.0 - rhs.0)
}
}
#[doc = r" A character offset."]
#[doc = r""]
#[doc = r" Because of multibyte UTF-8 characters, a byte offset"]
#[doc =
r" is not equivalent to a character offset. The [`SourceMap`] will convert [`BytePos`]"]
#[doc = r" values to `CharPos` values as necessary."]
pub struct CharPos(pub usize);
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for CharPos { }
#[automatically_derived]
impl ::core::clone::Clone for CharPos {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<usize>;
*self
}
}
#[automatically_derived]
impl ::core::marker::Copy for CharPos { }
#[automatically_derived]
impl ::core::marker::StructuralPartialEq for CharPos { }
#[automatically_derived]
impl ::core::cmp::PartialEq for CharPos {
#[inline]
fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}
#[automatically_derived]
impl ::core::cmp::Eq for CharPos {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<usize>;
}
}
#[automatically_derived]
impl ::core::cmp::PartialOrd for CharPos {
#[inline]
fn partial_cmp(&self, other: &Self)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}
#[automatically_derived]
impl ::core::cmp::Ord for CharPos {
#[inline]
fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
::core::cmp::Ord::cmp(&self.0, &other.0)
}
}
#[automatically_derived]
impl ::core::fmt::Debug for CharPos {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f, "CharPos",
&&self.0)
}
}
impl Pos for CharPos {
#[inline(always)]
fn from_usize(n: usize) -> CharPos { CharPos(n as usize) }
#[inline(always)]
fn to_usize(&self) -> usize { self.0 as usize }
#[inline(always)]
fn from_u32(n: u32) -> CharPos { CharPos(n as usize) }
#[inline(always)]
fn to_u32(&self) -> u32 { self.0 as u32 }
}
impl Add for CharPos {
type Output = CharPos;
#[inline(always)]
fn add(self, rhs: CharPos) -> CharPos { CharPos(self.0 + rhs.0) }
}
impl Sub for CharPos {
type Output = CharPos;
#[inline(always)]
fn sub(self, rhs: CharPos) -> CharPos { CharPos(self.0 - rhs.0) }
}impl_pos! {
2697 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
2701 pub struct BytePos(pub u32);
2702
2703 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, StableHash)]
2705 pub struct RelativeBytePos(pub u32);
2706
2707 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
2713 pub struct CharPos(pub usize);
2714}
2715
2716impl<S: Encoder> Encodable<S> for BytePos {
2717 fn encode(&self, s: &mut S) {
2718 s.emit_u32(self.0);
2719 }
2720}
2721
2722impl<D: Decoder> Decodable<D> for BytePos {
2723 fn decode(d: &mut D) -> BytePos {
2724 BytePos(d.read_u32())
2725 }
2726}
2727
2728impl<S: Encoder> Encodable<S> for RelativeBytePos {
2729 fn encode(&self, s: &mut S) {
2730 s.emit_u32(self.0);
2731 }
2732}
2733
2734impl<D: Decoder> Decodable<D> for RelativeBytePos {
2735 fn decode(d: &mut D) -> RelativeBytePos {
2736 RelativeBytePos(d.read_u32())
2737 }
2738}
2739
2740#[derive(#[automatically_derived]
impl ::core::fmt::Debug for Loc {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f, "Loc", "file",
&self.file, "line", &self.line, "col", &self.col, "col_display",
&&self.col_display)
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for Loc {
#[inline]
fn clone(&self) -> Self {
Self {
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)]
2746pub struct Loc {
2747 pub file: Arc<SourceFile>,
2749 pub line: usize,
2751 pub col: CharPos,
2753 pub col_display: usize,
2755}
2756
2757#[derive(#[automatically_derived]
impl ::core::fmt::Debug for SourceFileAndLine {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"SourceFileAndLine", "sf", &self.sf, "line", &&self.line)
}
}Debug)]
2759pub struct SourceFileAndLine {
2760 pub sf: Arc<SourceFile>,
2761 pub line: usize,
2763}
2764#[derive(#[automatically_derived]
impl ::core::fmt::Debug for SourceFileAndBytePos {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"SourceFileAndBytePos", "sf", &self.sf, "pos", &&self.pos)
}
}Debug)]
2765pub struct SourceFileAndBytePos {
2766 pub sf: Arc<SourceFile>,
2767 pub pos: BytePos,
2768}
2769
2770#[derive(#[automatically_derived]
impl ::core::marker::Copy for LineInfo { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for LineInfo { }
#[automatically_derived]
impl ::core::clone::Clone for LineInfo {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<usize>;
let _: ::core::clone::AssertParamIsClone<CharPos>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for LineInfo {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f, "LineInfo",
"line_index", &self.line_index, "start_col", &self.start_col,
"end_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)]
2771pub struct LineInfo {
2772 pub line_index: usize,
2774
2775 pub start_col: CharPos,
2777
2778 pub end_col: CharPos,
2780}
2781
2782pub struct FileLines {
2783 pub file: Arc<SourceFile>,
2784 pub lines: Vec<LineInfo>,
2785}
2786
2787pub static SPAN_TRACK: AtomicRef<fn(LocalDefId)> = AtomicRef::new(&((|_| {}) as fn(_)));
2788
2789pub type FileLinesResult = Result<FileLines, SpanLinesError>;
2794
2795#[derive(#[automatically_derived]
impl ::core::clone::Clone for SpanLinesError {
#[inline]
fn clone(&self) -> Self {
match self {
Self::DistinctSources(__self_0) =>
Self::DistinctSources(::core::clone::Clone::clone(__self_0)),
}
}
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for SpanLinesError { }
#[automatically_derived]
impl ::core::cmp::PartialEq for SpanLinesError {
#[inline]
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::DistinctSources(__self_0), Self::DistinctSources(__arg1_0))
=> __self_0 == __arg1_0,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for SpanLinesError {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Box<DistinctSources>>;
}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for SpanLinesError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::DistinctSources(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"DistinctSources", &__self_0),
}
}
}Debug)]
2796pub enum SpanLinesError {
2797 DistinctSources(Box<DistinctSources>),
2798}
2799
2800#[derive(#[automatically_derived]
impl ::core::clone::Clone for SpanSnippetError {
#[inline]
fn clone(&self) -> Self {
match self {
Self::IllFormedSpan(__self_0) =>
Self::IllFormedSpan(::core::clone::Clone::clone(__self_0)),
Self::DistinctSources(__self_0) =>
Self::DistinctSources(::core::clone::Clone::clone(__self_0)),
Self::MalformedForSourcemap(__self_0) =>
Self::MalformedForSourcemap(::core::clone::Clone::clone(__self_0)),
Self::SourceNotAvailable { filename: __self_0 } =>
Self::SourceNotAvailable {
filename: ::core::clone::Clone::clone(__self_0),
},
}
}
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for SpanSnippetError { }
#[automatically_derived]
impl ::core::cmp::PartialEq for SpanSnippetError {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::IllFormedSpan(__self_0), Self::IllFormedSpan(__arg1_0))
=> __self_0 == __arg1_0,
(Self::DistinctSources(__self_0),
Self::DistinctSources(__arg1_0)) => __self_0 == __arg1_0,
(Self::MalformedForSourcemap(__self_0),
Self::MalformedForSourcemap(__arg1_0)) =>
__self_0 == __arg1_0,
(Self::SourceNotAvailable { filename: __self_0 },
Self::SourceNotAvailable { filename: __arg1_0 }) =>
__self_0 == __arg1_0,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for SpanSnippetError {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Span>;
let _: ::core::cmp::AssertParamIsEq<Box<DistinctSources>>;
let _: ::core::cmp::AssertParamIsEq<MalformedSourceMapPositions>;
let _: ::core::cmp::AssertParamIsEq<FileName>;
}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for SpanSnippetError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::IllFormedSpan(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"IllFormedSpan", &__self_0),
Self::DistinctSources(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"DistinctSources", &__self_0),
Self::MalformedForSourcemap(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"MalformedForSourcemap", &__self_0),
Self::SourceNotAvailable { filename: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"SourceNotAvailable", "filename", &__self_0),
}
}
}Debug)]
2801pub enum SpanSnippetError {
2802 IllFormedSpan(Span),
2803 DistinctSources(Box<DistinctSources>),
2804 MalformedForSourcemap(MalformedSourceMapPositions),
2805 SourceNotAvailable { filename: FileName },
2806}
2807
2808#[derive(#[automatically_derived]
impl ::core::clone::Clone for DistinctSources {
#[inline]
fn clone(&self) -> Self {
Self {
begin: ::core::clone::Clone::clone(&self.begin),
end: ::core::clone::Clone::clone(&self.end),
}
}
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for DistinctSources { }
#[automatically_derived]
impl ::core::cmp::PartialEq for DistinctSources {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.begin == other.begin && self.end == other.end
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for DistinctSources {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<(FileName, BytePos)>;
let _: ::core::cmp::AssertParamIsEq<(FileName, BytePos)>;
}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for DistinctSources {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"DistinctSources", "begin", &self.begin, "end", &&self.end)
}
}Debug)]
2809pub struct DistinctSources {
2810 pub begin: (FileName, BytePos),
2811 pub end: (FileName, BytePos),
2812}
2813
2814#[derive(#[automatically_derived]
impl ::core::clone::Clone for MalformedSourceMapPositions {
#[inline]
fn clone(&self) -> Self {
Self {
name: ::core::clone::Clone::clone(&self.name),
source_len: ::core::clone::Clone::clone(&self.source_len),
begin_pos: ::core::clone::Clone::clone(&self.begin_pos),
end_pos: ::core::clone::Clone::clone(&self.end_pos),
}
}
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for MalformedSourceMapPositions { }
#[automatically_derived]
impl ::core::cmp::PartialEq for MalformedSourceMapPositions {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.name == other.name && self.source_len == other.source_len &&
self.begin_pos == other.begin_pos &&
self.end_pos == other.end_pos
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for MalformedSourceMapPositions {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<FileName>;
let _: ::core::cmp::AssertParamIsEq<usize>;
let _: ::core::cmp::AssertParamIsEq<BytePos>;
}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for MalformedSourceMapPositions {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f,
"MalformedSourceMapPositions", "name", &self.name, "source_len",
&self.source_len, "begin_pos", &self.begin_pos, "end_pos",
&&self.end_pos)
}
}Debug)]
2815pub struct MalformedSourceMapPositions {
2816 pub name: FileName,
2817 pub source_len: usize,
2818 pub begin_pos: BytePos,
2819 pub end_pos: BytePos,
2820}
2821
2822#[derive(#[automatically_derived]
impl ::core::marker::Copy for InnerSpan { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for InnerSpan { }
#[automatically_derived]
impl ::core::clone::Clone for InnerSpan {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<usize>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for InnerSpan { }
#[automatically_derived]
impl ::core::cmp::PartialEq for InnerSpan {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.start == other.start && self.end == other.end
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for InnerSpan {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<usize>;
}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for InnerSpan {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "InnerSpan",
"start", &self.start, "end", &&self.end)
}
}Debug)]
2824pub struct InnerSpan {
2825 pub start: usize,
2826 pub end: usize,
2827}
2828
2829impl InnerSpan {
2830 pub fn new(start: usize, end: usize) -> InnerSpan {
2831 InnerSpan { start, end }
2832 }
2833}
2834
2835impl StableHash for Span {
2836 fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
2837 hcx.stable_hash_span(self.to_raw_span(), hasher)
2839 }
2840}
2841
2842#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ErrorGuaranteed { }
#[automatically_derived]
impl ::core::clone::Clone for ErrorGuaranteed {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<()>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for ErrorGuaranteed { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for ErrorGuaranteed {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ErrorGuaranteed", &&self.0)
}
}Debug, #[automatically_derived]
impl ::core::hash::Hash for ErrorGuaranteed {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}Hash, #[automatically_derived]
impl ::core::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)]
2848#[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)]
2849pub struct ErrorGuaranteed(());
2850
2851impl ErrorGuaranteed {
2852 #[deprecated = "should only be used in `DiagCtxtInner::emit_diagnostic`"]
2854 pub fn unchecked_error_guaranteed() -> Self {
2855 ErrorGuaranteed(())
2856 }
2857
2858 pub fn raise_fatal(self) -> ! {
2859 FatalError.raise()
2860 }
2861}
2862
2863impl<E: rustc_serialize::Encoder> Encodable<E> for ErrorGuaranteed {
2864 #[inline]
2865 fn encode(&self, _e: &mut E) {
2866 {
::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!(
2867 "should never serialize an `ErrorGuaranteed`, as we do not write metadata or \
2868 incremental caches in case errors occurred"
2869 )
2870 }
2871}
2872impl<D: rustc_serialize::Decoder> Decodable<D> for ErrorGuaranteed {
2873 #[inline]
2874 fn decode(_d: &mut D) -> ErrorGuaranteed {
2875 {
::core::panicking::panic_fmt(format_args!("`ErrorGuaranteed` should never have been serialized to metadata or incremental caches"));
}panic!(
2876 "`ErrorGuaranteed` should never have been serialized to metadata or incremental caches"
2877 )
2878 }
2879}