1#![allow(internal_features)]
20#![cfg_attr(target_arch = "loongarch64", feature(stdarch_loongarch))]
21#![feature(core_io_borrowed_buf)]
22#![feature(diagnostic_on_unknown)]
23#![feature(map_try_insert)]
24#![feature(negative_impls)]
25#![feature(read_buf)]
26#![feature(rustc_attrs)]
27extern crate self as rustc_span;
33
34use derive_where::derive_where;
35use rustc_data_structures::stable_hash::StableHashCtxt;
36use rustc_data_structures::{AtomicRef, outline};
37use rustc_macros::{Decodable, Encodable, StableHash};
38use rustc_serialize::opaque::mem_encoder::MemEncoder;
39use rustc_serialize::opaque::{FileEncoder, MemDecoder};
40use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
41use tracing::debug;
42pub use unicode_width::UNICODE_VERSION;
43
44mod caching_source_map_view;
45pub mod source_map;
46use source_map::{SourceMap, SourceMapInputs};
47
48pub use self::caching_source_map_view::CachingSourceMapView;
49use crate::fatal_error::FatalError;
50
51pub mod edition;
52use edition::Edition;
53pub mod hygiene;
54use hygiene::Transparency;
55pub use hygiene::{
56 DesugaringKind, ExpnData, ExpnHash, ExpnId, ExpnKind, LocalExpnId, MacroKind, SyntaxContext,
57};
58pub mod def_id;
59use def_id::{CrateNum, DefId, DefIndex, LOCAL_CRATE, LocalDefId, StableCrateId};
60pub mod edit_distance;
61mod span_encoding;
62pub use span_encoding::{DUMMY_SP, Span};
63
64pub mod symbol;
65pub use symbol::{
66 ByteSymbol, Ident, MacroRulesNormalizedIdent, STDLIB_STABLE_CRATES, Symbol, kw, sym,
67};
68
69mod analyze_source_file;
70pub mod fatal_error;
71
72pub mod profiling;
73
74use std::borrow::Cow;
75use std::cmp::{self, Ordering};
76use std::fmt::Display;
77use std::hash::Hash;
78use std::io::{self, Read};
79use std::ops::{Add, Range, Sub};
80use std::path::{Path, PathBuf};
81use std::str::FromStr;
82use std::sync::Arc;
83use std::{fmt, iter};
84
85use md5::{Digest, Md5};
86use rustc_data_structures::stable_hash::{StableHash, StableHasher};
87use rustc_data_structures::sync::{FreezeLock, FreezeWriteGuard, Lock};
88use rustc_data_structures::unord::UnordMap;
89use rustc_hashes::{Hash64, Hash128};
90use sha1::Sha1;
91use sha2::Sha256;
92
93#[cfg(test)]
94mod tests;
95
96#[derive(#[automatically_derived]
impl<T: ::core::clone::Clone> ::core::clone::Clone for Spanned<T> {
#[inline]
fn clone(&self) -> Spanned<T> {
Spanned {
node: ::core::clone::Clone::clone(&self.node),
span: ::core::clone::Clone::clone(&self.span),
}
}
}Clone, const _: () =
{
impl<T, __E: ::rustc_span::SpanEncoder>
::rustc_serialize::Encodable<__E> for Spanned<T> where
T: ::rustc_serialize::Encodable<__E> {
fn encode(&self, __encoder: &mut __E) {
match *self {
Spanned { node: ref __binding_0, span: ref __binding_1 } =>
{
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
}
}
}
}
};Encodable, const _: () =
{
impl<T, __D: ::rustc_span::SpanDecoder>
::rustc_serialize::Decodable<__D> for Spanned<T> where
T: ::rustc_serialize::Decodable<__D> {
fn decode(__decoder: &mut __D) -> Self {
Spanned {
node: ::rustc_serialize::Decodable::decode(__decoder),
span: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable, #[automatically_derived]
impl<T: ::core::fmt::Debug> ::core::fmt::Debug for Spanned<T> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "Spanned",
"node", &self.node, "span", &&self.span)
}
}Debug, #[automatically_derived]
impl<T: ::core::marker::Copy> ::core::marker::Copy for Spanned<T> { }Copy, #[automatically_derived]
impl<T: ::core::cmp::PartialEq> ::core::cmp::PartialEq for Spanned<T> {
#[inline]
fn eq(&self, other: &Spanned<T>) -> bool {
self.node == other.node && self.span == other.span
}
}PartialEq, #[automatically_derived]
impl<T: ::core::hash::Hash> ::core::hash::Hash for Spanned<T> {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.node, state);
::core::hash::Hash::hash(&self.span, state)
}
}Hash, const _: () =
{
impl<T> ::rustc_data_structures::stable_hash::StableHash for
Spanned<T> where
T: ::rustc_data_structures::stable_hash::StableHash {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
match *self {
Spanned { node: ref __binding_0, span: ref __binding_1 } =>
{
{ __binding_0.stable_hash(__hcx, __hasher); }
{ __binding_1.stable_hash(__hcx, __hasher); }
}
}
}
}
};StableHash)]
97pub struct Spanned<T> {
98 pub node: T,
99 pub span: Span,
100}
101
102pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
103 Spanned { node: t, span: sp }
104}
105
106pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
107 respan(DUMMY_SP, t)
108}
109
110pub struct SessionGlobals {
115 symbol_interner: symbol::Interner,
116 span_interner: Lock<span_encoding::SpanInterner>,
117 metavar_spans: MetavarSpansMap,
120 hygiene_data: Lock<hygiene::HygieneData>,
121
122 source_map: Option<Arc<SourceMap>>,
126}
127
128impl SessionGlobals {
129 pub fn new(
130 edition: Edition,
131 extra_symbols: &[&'static str],
132 sm_inputs: Option<SourceMapInputs>,
133 ) -> SessionGlobals {
134 SessionGlobals {
135 symbol_interner: symbol::Interner::with_extra_symbols(extra_symbols),
136 span_interner: Lock::new(span_encoding::SpanInterner::default()),
137 metavar_spans: Default::default(),
138 hygiene_data: Lock::new(hygiene::HygieneData::new(edition)),
139 source_map: sm_inputs.map(|inputs| Arc::new(SourceMap::with_inputs(inputs))),
140 }
141 }
142}
143
144pub fn create_session_globals_then<R>(
145 edition: Edition,
146 extra_symbols: &[&'static str],
147 sm_inputs: Option<SourceMapInputs>,
148 f: impl FnOnce() -> R,
149) -> R {
150 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!(
151 !SESSION_GLOBALS.is_set(),
152 "SESSION_GLOBALS should never be overwritten! \
153 Use another thread if you need another SessionGlobals"
154 );
155 let session_globals = SessionGlobals::new(edition, extra_symbols, sm_inputs);
156 SESSION_GLOBALS.set(&session_globals, f)
157}
158
159pub fn set_session_globals_then<R>(session_globals: &SessionGlobals, f: impl FnOnce() -> R) -> R {
160 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!(
161 !SESSION_GLOBALS.is_set(),
162 "SESSION_GLOBALS should never be overwritten! \
163 Use another thread if you need another SessionGlobals"
164 );
165 SESSION_GLOBALS.set(session_globals, f)
166}
167
168pub fn create_session_if_not_set_then<R, F>(edition: Edition, f: F) -> R
170where
171 F: FnOnce(&SessionGlobals) -> R,
172{
173 if !SESSION_GLOBALS.is_set() {
174 let session_globals = SessionGlobals::new(edition, &[], None);
175 SESSION_GLOBALS.set(&session_globals, || SESSION_GLOBALS.with(f))
176 } else {
177 SESSION_GLOBALS.with(f)
178 }
179}
180
181#[inline]
182pub fn with_session_globals<R, F>(f: F) -> R
183where
184 F: FnOnce(&SessionGlobals) -> R,
185{
186 SESSION_GLOBALS.with(f)
187}
188
189pub fn create_default_session_globals_then<R>(f: impl FnOnce() -> R) -> R {
191 create_session_globals_then(edition::DEFAULT_EDITION, &[], None, f)
192}
193
194static SESSION_GLOBALS: ::scoped_tls::ScopedKey<SessionGlobals> =
::scoped_tls::ScopedKey {
inner: {
const FOO: ::std::thread::LocalKey<::std::cell::Cell<*const ()>> =
{
const __RUST_STD_INTERNAL_INIT: ::std::cell::Cell<*const ()>
=
{ ::std::cell::Cell::new(::std::ptr::null()) };
unsafe {
::std::thread::LocalKey::new(const {
if ::std::mem::needs_drop::<::std::cell::Cell<*const ()>>()
{
|_|
{
#[thread_local]
static __RUST_STD_INTERNAL_VAL:
::std::thread::local_impl::EagerStorage<::std::cell::Cell<*const ()>>
=
::std::thread::local_impl::EagerStorage::new(__RUST_STD_INTERNAL_INIT);
__RUST_STD_INTERNAL_VAL.get()
}
} else {
|_|
{
#[thread_local]
static __RUST_STD_INTERNAL_VAL: ::std::cell::Cell<*const ()>
=
__RUST_STD_INTERNAL_INIT;
&__RUST_STD_INTERNAL_VAL
}
}
})
}
};
&FOO
},
_marker: ::std::marker::PhantomData,
};scoped_tls::scoped_thread_local!(static SESSION_GLOBALS: SessionGlobals);
198
199#[derive(#[automatically_derived]
impl ::core::default::Default for MetavarSpansMap {
#[inline]
fn default() -> MetavarSpansMap {
MetavarSpansMap(::core::default::Default::default())
}
}Default)]
200pub struct MetavarSpansMap(FreezeLock<UnordMap<Span, (Span, bool)>>);
201
202impl MetavarSpansMap {
203 pub fn insert(&self, span: Span, var_span: Span) -> bool {
204 match self.0.write().try_insert(span, (var_span, false)) {
205 Ok(_) => true,
206 Err(entry) => entry.entry.get().0 == var_span,
207 }
208 }
209
210 pub fn get(&self, span: Span) -> Option<Span> {
212 if let Some(mut mspans) = self.0.try_write() {
213 if let Some((var_span, read)) = mspans.get_mut(&span) {
214 *read = true;
215 Some(*var_span)
216 } else {
217 None
218 }
219 } else {
220 if let Some((span, true)) = self.0.read().get(&span) { Some(*span) } else { None }
221 }
222 }
223
224 pub fn freeze_and_get_read_spans(&self) -> UnordMap<Span, Span> {
228 self.0.freeze().items().filter(|(_, (_, b))| *b).map(|(s1, (s2, _))| (*s1, *s2)).collect()
229 }
230}
231
232#[inline]
233pub fn with_metavar_spans<R>(f: impl FnOnce(&MetavarSpansMap) -> R) -> R {
234 with_session_globals(|session_globals| f(&session_globals.metavar_spans))
235}
236
237#[doc =
r" Scopes used to determined if it need to apply to `--remap-path-prefix`"]
pub struct RemapPathScopeComponents(<RemapPathScopeComponents as
::bitflags::__private::PublicFlags>::Internal);
#[automatically_derived]
impl ::core::fmt::Debug for RemapPathScopeComponents {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"RemapPathScopeComponents", &&self.0)
}
}
#[automatically_derived]
impl ::core::cmp::Eq for RemapPathScopeComponents {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _:
::core::cmp::AssertParamIsEq<<RemapPathScopeComponents as
::bitflags::__private::PublicFlags>::Internal>;
}
}
#[automatically_derived]
impl ::core::marker::StructuralPartialEq for RemapPathScopeComponents { }
#[automatically_derived]
impl ::core::cmp::PartialEq for RemapPathScopeComponents {
#[inline]
fn eq(&self, other: &RemapPathScopeComponents) -> bool {
self.0 == other.0
}
}
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for RemapPathScopeComponents { }
#[automatically_derived]
impl ::core::clone::Clone for RemapPathScopeComponents {
#[inline]
fn clone(&self) -> RemapPathScopeComponents {
let _:
::core::clone::AssertParamIsClone<<RemapPathScopeComponents as
::bitflags::__private::PublicFlags>::Internal>;
*self
}
}
#[automatically_derived]
impl ::core::marker::Copy for RemapPathScopeComponents { }
#[automatically_derived]
impl ::core::cmp::Ord for RemapPathScopeComponents {
#[inline]
fn cmp(&self, other: &RemapPathScopeComponents) -> ::core::cmp::Ordering {
::core::cmp::Ord::cmp(&self.0, &other.0)
}
}
#[automatically_derived]
impl ::core::cmp::PartialOrd for RemapPathScopeComponents {
#[inline]
fn partial_cmp(&self, other: &RemapPathScopeComponents)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}
#[automatically_derived]
impl ::core::hash::Hash for RemapPathScopeComponents {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}
impl RemapPathScopeComponents {
#[doc = r" Apply remappings to the expansion of `std::file!()` macro"]
#[allow(deprecated, non_upper_case_globals,)]
pub const MACRO: Self = Self::from_bits_retain(1 << 0);
#[doc = r" Apply remappings to printed compiler diagnostics"]
#[allow(deprecated, non_upper_case_globals,)]
pub const DIAGNOSTICS: Self = Self::from_bits_retain(1 << 1);
#[doc = r" Apply remappings to debug information"]
#[allow(deprecated, non_upper_case_globals,)]
pub const DEBUGINFO: Self = Self::from_bits_retain(1 << 3);
#[doc = r" Apply remappings to coverage information"]
#[allow(deprecated, non_upper_case_globals,)]
pub const COVERAGE: Self = Self::from_bits_retain(1 << 4);
#[doc = r" Apply remappings to documentation information"]
#[allow(deprecated, non_upper_case_globals,)]
pub const DOCUMENTATION: Self = Self::from_bits_retain(1 << 5);
#[doc =
r" An alias for `macro`, `debuginfo` and `coverage`. This ensures all paths in compiled"]
#[doc =
r" executables, libraries and objects are remapped but not elsewhere."]
#[allow(deprecated, non_upper_case_globals,)]
pub const OBJECT: Self =
Self::from_bits_retain(Self::MACRO.bits() | Self::DEBUGINFO.bits() |
Self::COVERAGE.bits());
}
impl ::bitflags::Flags for RemapPathScopeComponents {
const FLAGS: &'static [::bitflags::Flag<RemapPathScopeComponents>] =
&[{
#[allow(deprecated, non_upper_case_globals,)]
::bitflags::Flag::new("MACRO",
RemapPathScopeComponents::MACRO)
},
{
#[allow(deprecated, non_upper_case_globals,)]
::bitflags::Flag::new("DIAGNOSTICS",
RemapPathScopeComponents::DIAGNOSTICS)
},
{
#[allow(deprecated, non_upper_case_globals,)]
::bitflags::Flag::new("DEBUGINFO",
RemapPathScopeComponents::DEBUGINFO)
},
{
#[allow(deprecated, non_upper_case_globals,)]
::bitflags::Flag::new("COVERAGE",
RemapPathScopeComponents::COVERAGE)
},
{
#[allow(deprecated, non_upper_case_globals,)]
::bitflags::Flag::new("DOCUMENTATION",
RemapPathScopeComponents::DOCUMENTATION)
},
{
#[allow(deprecated, non_upper_case_globals,)]
::bitflags::Flag::new("OBJECT",
RemapPathScopeComponents::OBJECT)
}];
type Bits = u8;
fn bits(&self) -> u8 { RemapPathScopeComponents::bits(self) }
fn from_bits_retain(bits: u8) -> RemapPathScopeComponents {
RemapPathScopeComponents::from_bits_retain(bits)
}
}
#[allow(dead_code, deprecated, unused_doc_comments, unused_attributes,
unused_mut, unused_imports, non_upper_case_globals, clippy ::
assign_op_pattern, clippy :: indexing_slicing, clippy :: same_name_method,
clippy :: iter_without_into_iter,)]
const _: () =
{
#[repr(transparent)]
pub struct InternalBitFlags(u8);
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for InternalBitFlags { }
#[automatically_derived]
impl ::core::clone::Clone for InternalBitFlags {
#[inline]
fn clone(&self) -> InternalBitFlags {
let _: ::core::clone::AssertParamIsClone<u8>;
*self
}
}
#[automatically_derived]
impl ::core::marker::Copy for InternalBitFlags { }
#[automatically_derived]
impl ::core::marker::StructuralPartialEq for InternalBitFlags { }
#[automatically_derived]
impl ::core::cmp::PartialEq for InternalBitFlags {
#[inline]
fn eq(&self, other: &InternalBitFlags) -> bool {
self.0 == other.0
}
}
#[automatically_derived]
impl ::core::cmp::Eq for InternalBitFlags {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<u8>;
}
}
#[automatically_derived]
impl ::core::cmp::PartialOrd for InternalBitFlags {
#[inline]
fn partial_cmp(&self, other: &InternalBitFlags)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self,
other))
}
}
#[automatically_derived]
impl ::core::cmp::Ord for InternalBitFlags {
#[inline]
fn cmp(&self, other: &InternalBitFlags) -> ::core::cmp::Ordering {
::core::cmp::Ord::cmp(&self.0, &other.0)
}
}
#[automatically_derived]
impl ::core::hash::Hash for InternalBitFlags {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}
impl ::bitflags::__private::PublicFlags for RemapPathScopeComponents {
type Primitive = u8;
type Internal = InternalBitFlags;
}
impl ::bitflags::__private::core::default::Default for
InternalBitFlags {
#[inline]
fn default() -> Self { InternalBitFlags::empty() }
}
impl ::bitflags::__private::core::fmt::Debug for InternalBitFlags {
fn fmt(&self,
f: &mut ::bitflags::__private::core::fmt::Formatter<'_>)
-> ::bitflags::__private::core::fmt::Result {
if self.is_empty() {
f.write_fmt(format_args!("{0:#x}",
<u8 as ::bitflags::Bits>::EMPTY))
} else {
::bitflags::__private::core::fmt::Display::fmt(self, f)
}
}
}
impl ::bitflags::__private::core::fmt::Display for InternalBitFlags {
fn fmt(&self,
f: &mut ::bitflags::__private::core::fmt::Formatter<'_>)
-> ::bitflags::__private::core::fmt::Result {
::bitflags::parser::to_writer(&RemapPathScopeComponents(*self),
f)
}
}
impl ::bitflags::__private::core::str::FromStr for InternalBitFlags {
type Err = ::bitflags::parser::ParseError;
fn from_str(s: &str)
->
::bitflags::__private::core::result::Result<Self,
Self::Err> {
::bitflags::parser::from_str::<RemapPathScopeComponents>(s).map(|flags|
flags.0)
}
}
impl ::bitflags::__private::core::convert::AsRef<u8> for
InternalBitFlags {
fn as_ref(&self) -> &u8 { &self.0 }
}
impl ::bitflags::__private::core::convert::From<u8> for
InternalBitFlags {
fn from(bits: u8) -> Self { Self::from_bits_retain(bits) }
}
#[allow(dead_code, deprecated, unused_attributes)]
impl InternalBitFlags {
#[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! {
238 #[derive(Debug, Eq, PartialEq, Clone, Copy, Ord, PartialOrd, Hash)]
240 pub struct RemapPathScopeComponents: u8 {
241 const MACRO = 1 << 0;
243 const DIAGNOSTICS = 1 << 1;
245 const DEBUGINFO = 1 << 3;
247 const COVERAGE = 1 << 4;
249 const DOCUMENTATION = 1 << 5;
251
252 const OBJECT = Self::MACRO.bits() | Self::DEBUGINFO.bits() | Self::COVERAGE.bits();
255 }
256}
257
258impl<E: Encoder> Encodable<E> for RemapPathScopeComponents {
259 #[inline]
260 fn encode(&self, s: &mut E) {
261 s.emit_u8(self.bits());
262 }
263}
264
265impl<D: Decoder> Decodable<D> for RemapPathScopeComponents {
266 #[inline]
267 fn decode(s: &mut D) -> RemapPathScopeComponents {
268 RemapPathScopeComponents::from_bits(s.read_u8())
269 .expect("invalid bits for RemapPathScopeComponents")
270 }
271}
272
273#[derive(#[automatically_derived]
impl ::core::fmt::Debug for RealFileName {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f, "RealFileName",
"local", &self.local, "maybe_remapped", &self.maybe_remapped,
"scopes", &&self.scopes)
}
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for RealFileName {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Option<InnerRealFileName>>;
let _: ::core::cmp::AssertParamIsEq<InnerRealFileName>;
let _: ::core::cmp::AssertParamIsEq<RemapPathScopeComponents>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for RealFileName {
#[inline]
fn eq(&self, other: &RealFileName) -> bool {
self.local == other.local &&
self.maybe_remapped == other.maybe_remapped &&
self.scopes == other.scopes
}
}PartialEq, #[automatically_derived]
impl ::core::clone::Clone for RealFileName {
#[inline]
fn clone(&self) -> RealFileName {
RealFileName {
local: ::core::clone::Clone::clone(&self.local),
maybe_remapped: ::core::clone::Clone::clone(&self.maybe_remapped),
scopes: ::core::clone::Clone::clone(&self.scopes),
}
}
}Clone, #[automatically_derived]
impl ::core::cmp::Ord for RealFileName {
#[inline]
fn cmp(&self, other: &RealFileName) -> ::core::cmp::Ordering {
match ::core::cmp::Ord::cmp(&self.local, &other.local) {
::core::cmp::Ordering::Equal =>
match ::core::cmp::Ord::cmp(&self.maybe_remapped,
&other.maybe_remapped) {
::core::cmp::Ordering::Equal =>
::core::cmp::Ord::cmp(&self.scopes, &other.scopes),
cmp => cmp,
},
cmp => cmp,
}
}
}Ord, #[automatically_derived]
impl ::core::cmp::PartialOrd for RealFileName {
#[inline]
fn partial_cmp(&self, other: &RealFileName)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for RealFileName {
fn decode(__decoder: &mut __D) -> Self {
RealFileName {
local: ::rustc_serialize::Decodable::decode(__decoder),
maybe_remapped: ::rustc_serialize::Decodable::decode(__decoder),
scopes: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for RealFileName {
fn encode(&self, __encoder: &mut __E) {
match *self {
RealFileName {
local: ref __binding_0,
maybe_remapped: ref __binding_1,
scopes: ref __binding_2 } => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_2,
__encoder);
}
}
}
}
};Encodable)]
305pub struct RealFileName {
306 local: Option<InnerRealFileName>,
308 maybe_remapped: InnerRealFileName,
310 scopes: RemapPathScopeComponents,
312}
313
314#[derive(#[automatically_derived]
impl ::core::fmt::Debug for InnerRealFileName {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"InnerRealFileName", "name", &self.name, "working_directory",
&self.working_directory, "embeddable_name",
&&self.embeddable_name)
}
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for InnerRealFileName {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<PathBuf>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for InnerRealFileName {
#[inline]
fn eq(&self, other: &InnerRealFileName) -> bool {
self.name == other.name &&
self.working_directory == other.working_directory &&
self.embeddable_name == other.embeddable_name
}
}PartialEq, #[automatically_derived]
impl ::core::clone::Clone for InnerRealFileName {
#[inline]
fn clone(&self) -> InnerRealFileName {
InnerRealFileName {
name: ::core::clone::Clone::clone(&self.name),
working_directory: ::core::clone::Clone::clone(&self.working_directory),
embeddable_name: ::core::clone::Clone::clone(&self.embeddable_name),
}
}
}Clone, #[automatically_derived]
impl ::core::cmp::Ord for InnerRealFileName {
#[inline]
fn cmp(&self, other: &InnerRealFileName) -> ::core::cmp::Ordering {
match ::core::cmp::Ord::cmp(&self.name, &other.name) {
::core::cmp::Ordering::Equal =>
match ::core::cmp::Ord::cmp(&self.working_directory,
&other.working_directory) {
::core::cmp::Ordering::Equal =>
::core::cmp::Ord::cmp(&self.embeddable_name,
&other.embeddable_name),
cmp => cmp,
},
cmp => cmp,
}
}
}Ord, #[automatically_derived]
impl ::core::cmp::PartialOrd for InnerRealFileName {
#[inline]
fn partial_cmp(&self, other: &InnerRealFileName)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for InnerRealFileName {
fn decode(__decoder: &mut __D) -> Self {
InnerRealFileName {
name: ::rustc_serialize::Decodable::decode(__decoder),
working_directory: ::rustc_serialize::Decodable::decode(__decoder),
embeddable_name: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for InnerRealFileName {
fn encode(&self, __encoder: &mut __E) {
match *self {
InnerRealFileName {
name: ref __binding_0,
working_directory: ref __binding_1,
embeddable_name: ref __binding_2 } => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_2,
__encoder);
}
}
}
}
};Encodable, #[automatically_derived]
impl ::core::hash::Hash for InnerRealFileName {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.name, state);
::core::hash::Hash::hash(&self.working_directory, state);
::core::hash::Hash::hash(&self.embeddable_name, state)
}
}Hash)]
318struct InnerRealFileName {
319 name: PathBuf,
321 working_directory: PathBuf,
323 embeddable_name: PathBuf,
325}
326
327impl Hash for RealFileName {
328 #[inline]
329 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
330 if !self.was_fully_remapped() {
335 self.local.hash(state);
336 }
337 self.maybe_remapped.hash(state);
338 self.scopes.bits().hash(state);
339 }
340}
341
342impl RealFileName {
343 #[inline]
349 pub fn path(&self, scope: RemapPathScopeComponents) -> &Path {
350 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!(
351 scope.bits().count_ones() == 1,
352 "one and only one scope should be passed to `RealFileName::path`: {scope:?}"
353 );
354 if !self.scopes.contains(scope)
355 && let Some(local_name) = &self.local
356 {
357 local_name.name.as_path()
358 } else {
359 self.maybe_remapped.name.as_path()
360 }
361 }
362
363 #[inline]
374 pub fn embeddable_name(&self, scope: RemapPathScopeComponents) -> (&Path, &Path) {
375 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!(
376 scope.bits().count_ones() == 1,
377 "one and only one scope should be passed to `RealFileName::embeddable_path`: {scope:?}"
378 );
379 if !self.scopes.contains(scope)
380 && let Some(local_name) = &self.local
381 {
382 (&local_name.working_directory, &local_name.embeddable_name)
383 } else {
384 (&self.maybe_remapped.working_directory, &self.maybe_remapped.embeddable_name)
385 }
386 }
387
388 #[inline]
395 pub fn local_path(&self) -> Option<&Path> {
396 if self.was_not_remapped() {
397 Some(&self.maybe_remapped.name)
398 } else if let Some(local) = &self.local {
399 Some(&local.name)
400 } else {
401 None
402 }
403 }
404
405 #[inline]
412 pub fn into_local_path(self) -> Option<PathBuf> {
413 if self.was_not_remapped() {
414 Some(self.maybe_remapped.name)
415 } else if let Some(local) = self.local {
416 Some(local.name)
417 } else {
418 None
419 }
420 }
421
422 #[inline]
424 pub(crate) fn was_remapped(&self) -> bool {
425 !self.scopes.is_empty()
426 }
427
428 #[inline]
430 fn was_fully_remapped(&self) -> bool {
431 self.scopes.is_all()
432 }
433
434 #[inline]
436 fn was_not_remapped(&self) -> bool {
437 self.scopes.is_empty()
438 }
439
440 #[inline]
444 pub fn empty() -> RealFileName {
445 RealFileName {
446 local: Some(InnerRealFileName {
447 name: PathBuf::new(),
448 working_directory: PathBuf::new(),
449 embeddable_name: PathBuf::new(),
450 }),
451 maybe_remapped: InnerRealFileName {
452 name: PathBuf::new(),
453 working_directory: PathBuf::new(),
454 embeddable_name: PathBuf::new(),
455 },
456 scopes: RemapPathScopeComponents::empty(),
457 }
458 }
459
460 pub fn from_virtual_path(path: &Path) -> RealFileName {
464 let name = InnerRealFileName {
465 name: path.to_owned(),
466 embeddable_name: path.to_owned(),
467 working_directory: PathBuf::new(),
468 };
469 RealFileName { local: None, maybe_remapped: name, scopes: RemapPathScopeComponents::all() }
470 }
471
472 #[inline]
477 pub fn update_for_crate_metadata(&mut self) {
478 if self.was_fully_remapped() || self.was_not_remapped() {
479 self.local = None;
484 }
485 }
486
487 fn to_string_lossy<'a>(&'a self, display_pref: FileNameDisplayPreference) -> Cow<'a, str> {
491 match display_pref {
492 FileNameDisplayPreference::Remapped => self.maybe_remapped.name.to_string_lossy(),
493 FileNameDisplayPreference::Local => {
494 self.local.as_ref().unwrap_or(&self.maybe_remapped).name.to_string_lossy()
495 }
496 FileNameDisplayPreference::Short => self
497 .maybe_remapped
498 .name
499 .file_name()
500 .map_or_else(|| "".into(), |f| f.to_string_lossy()),
501 FileNameDisplayPreference::Scope(scope) => self.path(scope).to_string_lossy(),
502 }
503 }
504}
505
506#[derive(#[automatically_derived]
impl ::core::fmt::Debug for FileName {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
FileName::Real(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Real",
&__self_0),
FileName::CfgSpec(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"CfgSpec", &__self_0),
FileName::Anon(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Anon",
&__self_0),
FileName::MacroExpansion(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"MacroExpansion", &__self_0),
FileName::ProcMacroSourceCode(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ProcMacroSourceCode", &__self_0),
FileName::CliCrateAttr(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"CliCrateAttr", &__self_0),
FileName::Custom(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Custom",
&__self_0),
FileName::DocTest(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"DocTest", __self_0, &__self_1),
FileName::InlineAsm(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"InlineAsm", &__self_0),
}
}
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for FileName {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<RealFileName>;
let _: ::core::cmp::AssertParamIsEq<Hash64>;
let _: ::core::cmp::AssertParamIsEq<String>;
let _: ::core::cmp::AssertParamIsEq<PathBuf>;
let _: ::core::cmp::AssertParamIsEq<isize>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for FileName {
#[inline]
fn eq(&self, other: &FileName) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(FileName::Real(__self_0), FileName::Real(__arg1_0)) =>
__self_0 == __arg1_0,
(FileName::CfgSpec(__self_0), FileName::CfgSpec(__arg1_0)) =>
__self_0 == __arg1_0,
(FileName::Anon(__self_0), FileName::Anon(__arg1_0)) =>
__self_0 == __arg1_0,
(FileName::MacroExpansion(__self_0),
FileName::MacroExpansion(__arg1_0)) => __self_0 == __arg1_0,
(FileName::ProcMacroSourceCode(__self_0),
FileName::ProcMacroSourceCode(__arg1_0)) =>
__self_0 == __arg1_0,
(FileName::CliCrateAttr(__self_0),
FileName::CliCrateAttr(__arg1_0)) => __self_0 == __arg1_0,
(FileName::Custom(__self_0), FileName::Custom(__arg1_0)) =>
__self_0 == __arg1_0,
(FileName::DocTest(__self_0, __self_1),
FileName::DocTest(__arg1_0, __arg1_1)) =>
__self_0 == __arg1_0 && __self_1 == __arg1_1,
(FileName::InlineAsm(__self_0), FileName::InlineAsm(__arg1_0))
=> __self_0 == __arg1_0,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq, #[automatically_derived]
impl ::core::clone::Clone for FileName {
#[inline]
fn clone(&self) -> FileName {
match self {
FileName::Real(__self_0) =>
FileName::Real(::core::clone::Clone::clone(__self_0)),
FileName::CfgSpec(__self_0) =>
FileName::CfgSpec(::core::clone::Clone::clone(__self_0)),
FileName::Anon(__self_0) =>
FileName::Anon(::core::clone::Clone::clone(__self_0)),
FileName::MacroExpansion(__self_0) =>
FileName::MacroExpansion(::core::clone::Clone::clone(__self_0)),
FileName::ProcMacroSourceCode(__self_0) =>
FileName::ProcMacroSourceCode(::core::clone::Clone::clone(__self_0)),
FileName::CliCrateAttr(__self_0) =>
FileName::CliCrateAttr(::core::clone::Clone::clone(__self_0)),
FileName::Custom(__self_0) =>
FileName::Custom(::core::clone::Clone::clone(__self_0)),
FileName::DocTest(__self_0, __self_1) =>
FileName::DocTest(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1)),
FileName::InlineAsm(__self_0) =>
FileName::InlineAsm(::core::clone::Clone::clone(__self_0)),
}
}
}Clone, #[automatically_derived]
impl ::core::cmp::Ord for FileName {
#[inline]
fn cmp(&self, other: &FileName) -> ::core::cmp::Ordering {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
match ::core::cmp::Ord::cmp(&__self_discr, &__arg1_discr) {
::core::cmp::Ordering::Equal =>
match (self, other) {
(FileName::Real(__self_0), FileName::Real(__arg1_0)) =>
::core::cmp::Ord::cmp(__self_0, __arg1_0),
(FileName::CfgSpec(__self_0), FileName::CfgSpec(__arg1_0))
=> ::core::cmp::Ord::cmp(__self_0, __arg1_0),
(FileName::Anon(__self_0), FileName::Anon(__arg1_0)) =>
::core::cmp::Ord::cmp(__self_0, __arg1_0),
(FileName::MacroExpansion(__self_0),
FileName::MacroExpansion(__arg1_0)) =>
::core::cmp::Ord::cmp(__self_0, __arg1_0),
(FileName::ProcMacroSourceCode(__self_0),
FileName::ProcMacroSourceCode(__arg1_0)) =>
::core::cmp::Ord::cmp(__self_0, __arg1_0),
(FileName::CliCrateAttr(__self_0),
FileName::CliCrateAttr(__arg1_0)) =>
::core::cmp::Ord::cmp(__self_0, __arg1_0),
(FileName::Custom(__self_0), FileName::Custom(__arg1_0)) =>
::core::cmp::Ord::cmp(__self_0, __arg1_0),
(FileName::DocTest(__self_0, __self_1),
FileName::DocTest(__arg1_0, __arg1_1)) =>
match ::core::cmp::Ord::cmp(__self_0, __arg1_0) {
::core::cmp::Ordering::Equal =>
::core::cmp::Ord::cmp(__self_1, __arg1_1),
cmp => cmp,
},
(FileName::InlineAsm(__self_0),
FileName::InlineAsm(__arg1_0)) =>
::core::cmp::Ord::cmp(__self_0, __arg1_0),
_ => unsafe { ::core::intrinsics::unreachable() }
},
cmp => cmp,
}
}
}Ord, #[automatically_derived]
impl ::core::cmp::PartialOrd for FileName {
#[inline]
fn partial_cmp(&self, other: &FileName)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd, #[automatically_derived]
impl ::core::hash::Hash for FileName {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
let __self_discr = ::core::intrinsics::discriminant_value(self);
::core::hash::Hash::hash(&__self_discr, state);
match self {
FileName::Real(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
FileName::CfgSpec(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
FileName::Anon(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
FileName::MacroExpansion(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
FileName::ProcMacroSourceCode(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
FileName::CliCrateAttr(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
FileName::Custom(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
FileName::DocTest(__self_0, __self_1) => {
::core::hash::Hash::hash(__self_0, state);
::core::hash::Hash::hash(__self_1, state)
}
FileName::InlineAsm(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
}
}
}Hash, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for FileName {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => {
FileName::Real(::rustc_serialize::Decodable::decode(__decoder))
}
1usize => {
FileName::CfgSpec(::rustc_serialize::Decodable::decode(__decoder))
}
2usize => {
FileName::Anon(::rustc_serialize::Decodable::decode(__decoder))
}
3usize => {
FileName::MacroExpansion(::rustc_serialize::Decodable::decode(__decoder))
}
4usize => {
FileName::ProcMacroSourceCode(::rustc_serialize::Decodable::decode(__decoder))
}
5usize => {
FileName::CliCrateAttr(::rustc_serialize::Decodable::decode(__decoder))
}
6usize => {
FileName::Custom(::rustc_serialize::Decodable::decode(__decoder))
}
7usize => {
FileName::DocTest(::rustc_serialize::Decodable::decode(__decoder),
::rustc_serialize::Decodable::decode(__decoder))
}
8usize => {
FileName::InlineAsm(::rustc_serialize::Decodable::decode(__decoder))
}
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `FileName`, expected 0..9, actual {0}",
n));
}
}
}
}
};Decodable, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for FileName {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
FileName::Real(ref __binding_0) => { 0usize }
FileName::CfgSpec(ref __binding_0) => { 1usize }
FileName::Anon(ref __binding_0) => { 2usize }
FileName::MacroExpansion(ref __binding_0) => { 3usize }
FileName::ProcMacroSourceCode(ref __binding_0) => { 4usize }
FileName::CliCrateAttr(ref __binding_0) => { 5usize }
FileName::Custom(ref __binding_0) => { 6usize }
FileName::DocTest(ref __binding_0, ref __binding_1) => {
7usize
}
FileName::InlineAsm(ref __binding_0) => { 8usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
match *self {
FileName::Real(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
FileName::CfgSpec(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
FileName::Anon(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
FileName::MacroExpansion(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
FileName::ProcMacroSourceCode(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
FileName::CliCrateAttr(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
FileName::Custom(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
FileName::DocTest(ref __binding_0, ref __binding_1) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
}
FileName::InlineAsm(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
}
}
}
};Encodable)]
508pub enum FileName {
509 Real(RealFileName),
510 CfgSpec(Hash64),
512 Anon(Hash64),
514 MacroExpansion(Hash64),
517 ProcMacroSourceCode(Hash64),
518 CliCrateAttr(Hash64),
520 Custom(String),
522 DocTest(PathBuf, isize),
523 InlineAsm(Hash64),
525}
526
527pub struct FileNameDisplay<'a> {
528 inner: &'a FileName,
529 display_pref: FileNameDisplayPreference,
530}
531
532#[derive(#[automatically_derived]
impl ::core::clone::Clone for FileNameDisplayPreference {
#[inline]
fn clone(&self) -> FileNameDisplayPreference {
let _: ::core::clone::AssertParamIsClone<RemapPathScopeComponents>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for FileNameDisplayPreference { }Copy)]
534enum FileNameDisplayPreference {
535 Remapped,
536 Local,
537 Short,
538 Scope(RemapPathScopeComponents),
539}
540
541impl fmt::Display for FileNameDisplay<'_> {
542 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
543 use FileName::*;
544 match *self.inner {
545 Real(ref name) => {
546 fmt.write_fmt(format_args!("{0}", name.to_string_lossy(self.display_pref)))write!(fmt, "{}", name.to_string_lossy(self.display_pref))
547 }
548 CfgSpec(_) => fmt.write_fmt(format_args!("<cfgspec>"))write!(fmt, "<cfgspec>"),
549 MacroExpansion(_) => fmt.write_fmt(format_args!("<macro expansion>"))write!(fmt, "<macro expansion>"),
550 Anon(_) => fmt.write_fmt(format_args!("<anon>"))write!(fmt, "<anon>"),
551 ProcMacroSourceCode(_) => fmt.write_fmt(format_args!("<proc-macro source code>"))write!(fmt, "<proc-macro source code>"),
552 CliCrateAttr(_) => fmt.write_fmt(format_args!("<crate attribute>"))write!(fmt, "<crate attribute>"),
553 Custom(ref s) => fmt.write_fmt(format_args!("<{0}>", s))write!(fmt, "<{s}>"),
554 DocTest(ref path, _) => fmt.write_fmt(format_args!("{0}", path.display()))write!(fmt, "{}", path.display()),
555 InlineAsm(_) => fmt.write_fmt(format_args!("<inline asm>"))write!(fmt, "<inline asm>"),
556 }
557 }
558}
559
560impl<'a> FileNameDisplay<'a> {
561 pub fn to_string_lossy(&self) -> Cow<'a, str> {
562 match self.inner {
563 FileName::Real(inner) => inner.to_string_lossy(self.display_pref),
564 _ => Cow::from(self.to_string()),
565 }
566 }
567}
568
569impl FileName {
570 pub fn is_real(&self) -> bool {
571 use FileName::*;
572 match *self {
573 Real(_) => true,
574 Anon(_)
575 | MacroExpansion(_)
576 | ProcMacroSourceCode(_)
577 | CliCrateAttr(_)
578 | Custom(_)
579 | CfgSpec(_)
580 | DocTest(_, _)
581 | InlineAsm(_) => false,
582 }
583 }
584
585 #[inline]
590 pub fn prefer_remapped_unconditionally(&self) -> FileNameDisplay<'_> {
591 FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Remapped }
592 }
593
594 #[inline]
599 pub fn prefer_local_unconditionally(&self) -> FileNameDisplay<'_> {
600 FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Local }
601 }
602
603 #[inline]
605 pub fn short(&self) -> FileNameDisplay<'_> {
606 FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Short }
607 }
608
609 #[inline]
611 pub fn display(&self, scope: RemapPathScopeComponents) -> FileNameDisplay<'_> {
612 FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Scope(scope) }
613 }
614
615 pub fn macro_expansion_source_code(src: &str) -> FileName {
616 let mut hasher = StableHasher::new();
617 src.hash(&mut hasher);
618 FileName::MacroExpansion(hasher.finish())
619 }
620
621 pub fn anon_source_code(src: &str) -> FileName {
622 let mut hasher = StableHasher::new();
623 src.hash(&mut hasher);
624 FileName::Anon(hasher.finish())
625 }
626
627 pub fn proc_macro_source_code(src: &str) -> FileName {
628 let mut hasher = StableHasher::new();
629 src.hash(&mut hasher);
630 FileName::ProcMacroSourceCode(hasher.finish())
631 }
632
633 pub fn cfg_spec_source_code(src: &str) -> FileName {
634 let mut hasher = StableHasher::new();
635 src.hash(&mut hasher);
636 FileName::CfgSpec(hasher.finish())
637 }
638
639 pub fn cli_crate_attr_source_code(src: &str) -> FileName {
640 let mut hasher = StableHasher::new();
641 src.hash(&mut hasher);
642 FileName::CliCrateAttr(hasher.finish())
643 }
644
645 pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName {
646 FileName::DocTest(path, line)
647 }
648
649 pub fn inline_asm_source_code(src: &str) -> FileName {
650 let mut hasher = StableHasher::new();
651 src.hash(&mut hasher);
652 FileName::InlineAsm(hasher.finish())
653 }
654
655 pub fn into_local_path(self) -> Option<PathBuf> {
660 match self {
661 FileName::Real(path) => path.into_local_path(),
662 FileName::DocTest(path, _) => Some(path),
663 _ => None,
664 }
665 }
666}
667
668#[derive(#[automatically_derived]
impl ::core::clone::Clone for SpanData {
#[inline]
fn clone(&self) -> SpanData {
let _: ::core::clone::AssertParamIsClone<BytePos>;
let _: ::core::clone::AssertParamIsClone<SyntaxContext>;
let _: ::core::clone::AssertParamIsClone<Option<LocalDefId>>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for SpanData { }Copy, #[automatically_derived]
impl ::core::hash::Hash for SpanData {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.lo, state);
::core::hash::Hash::hash(&self.hi, state);
::core::hash::Hash::hash(&self.ctxt, state);
::core::hash::Hash::hash(&self.parent, state)
}
}Hash, #[automatically_derived]
impl ::core::cmp::PartialEq for SpanData {
#[inline]
fn eq(&self, other: &SpanData) -> bool {
self.lo == other.lo && self.hi == other.hi && self.ctxt == other.ctxt
&& self.parent == other.parent
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for SpanData {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<BytePos>;
let _: ::core::cmp::AssertParamIsEq<SyntaxContext>;
let _: ::core::cmp::AssertParamIsEq<Option<LocalDefId>>;
}
}Eq)]
684#[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)]
685pub struct SpanData {
686 pub lo: BytePos,
687 pub hi: BytePos,
688 #[derive_where(skip)]
691 pub ctxt: SyntaxContext,
694 #[derive_where(skip)]
695 pub parent: Option<LocalDefId>,
698}
699
700impl SpanData {
701 #[inline]
702 pub fn span(&self) -> Span {
703 Span::new(self.lo, self.hi, self.ctxt, self.parent)
704 }
705 #[inline]
706 pub fn with_lo(&self, lo: BytePos) -> Span {
707 Span::new(lo, self.hi, self.ctxt, self.parent)
708 }
709 #[inline]
710 pub fn with_hi(&self, hi: BytePos) -> Span {
711 Span::new(self.lo, hi, self.ctxt, self.parent)
712 }
713 #[inline]
715 fn with_ctxt(&self, ctxt: SyntaxContext) -> Span {
716 Span::new(self.lo, self.hi, ctxt, self.parent)
717 }
718 #[inline]
720 fn with_parent(&self, parent: Option<LocalDefId>) -> Span {
721 Span::new(self.lo, self.hi, self.ctxt, parent)
722 }
723 #[inline]
725 pub fn is_dummy(self) -> bool {
726 self.lo.0 == 0 && self.hi.0 == 0
727 }
728 pub fn contains(self, other: Self) -> bool {
730 self.lo <= other.lo && other.hi <= self.hi
731 }
732}
733
734impl Default for SpanData {
735 fn default() -> Self {
736 Self { lo: BytePos(0), hi: BytePos(0), ctxt: SyntaxContext::root(), parent: None }
737 }
738}
739
740impl PartialOrd for Span {
741 fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
742 Some(self.cmp(rhs))
743 }
744}
745impl Ord for Span {
746 fn cmp(&self, rhs: &Self) -> Ordering {
747 Ord::cmp(&self.data(), &rhs.data())
748 }
749}
750
751impl Span {
752 #[inline]
753 pub fn lo(self) -> BytePos {
754 self.data().lo
755 }
756 #[inline]
757 pub fn with_lo(self, lo: BytePos) -> Span {
758 self.data().with_lo(lo)
759 }
760 #[inline]
761 pub fn hi(self) -> BytePos {
762 self.data().hi
763 }
764 #[inline]
765 pub fn with_hi(self, hi: BytePos) -> Span {
766 self.data().with_hi(hi)
767 }
768 #[inline]
769 pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span {
770 self.map_ctxt(|_| ctxt)
771 }
772
773 #[inline]
774 pub fn is_visible(self, sm: &SourceMap) -> bool {
775 !self.is_dummy() && sm.is_span_accessible(self)
776 }
777
778 #[inline]
783 pub fn in_external_macro(self, sm: &SourceMap) -> bool {
784 self.ctxt().in_external_macro(sm)
785 }
786
787 pub fn in_derive_expansion(self) -> bool {
789 #[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, _))
790 }
791
792 pub fn is_from_async_await(self) -> bool {
794 #[allow(non_exhaustive_omitted_patterns)] match self.ctxt().outer_expn_data().kind
{
ExpnKind::Desugaring(DesugaringKind::Async | DesugaringKind::Await) =>
true,
_ => false,
}matches!(
795 self.ctxt().outer_expn_data().kind,
796 ExpnKind::Desugaring(DesugaringKind::Async | DesugaringKind::Await),
797 )
798 }
799
800 pub fn can_be_used_for_suggestions(self) -> bool {
802 !self.from_expansion()
803 || (self.in_derive_expansion()
807 && self.parent_callsite().map(|p| (p.lo(), p.hi())) != Some((self.lo(), self.hi())))
808 }
809
810 #[inline]
811 pub fn with_root_ctxt(lo: BytePos, hi: BytePos) -> Span {
812 Span::new(lo, hi, SyntaxContext::root(), None)
813 }
814
815 #[inline]
817 pub fn shrink_to_lo(self) -> Span {
818 let span = self.data_untracked();
819 span.with_hi(span.lo)
820 }
821 #[inline]
823 pub fn shrink_to_hi(self) -> Span {
824 let span = self.data_untracked();
825 span.with_lo(span.hi)
826 }
827
828 #[inline]
829 pub fn is_empty(self) -> bool {
831 let span = self.data_untracked();
832 span.hi == span.lo
833 }
834
835 pub fn substitute_dummy(self, other: Span) -> Span {
837 if self.is_dummy() { other } else { self }
838 }
839
840 pub fn contains(self, other: Span) -> bool {
842 let span = self.data();
843 let other = other.data();
844 span.contains(other)
845 }
846
847 pub fn overlaps(self, other: Span) -> bool {
849 let span = self.data();
850 let other = other.data();
851 span.lo < other.hi && other.lo < span.hi
852 }
853
854 pub fn overlaps_or_adjacent(self, other: Span) -> bool {
856 let span = self.data();
857 let other = other.data();
858 span.lo <= other.hi && other.lo <= span.hi
859 }
860
861 pub fn source_equal(self, other: Span) -> bool {
866 let span = self.data();
867 let other = other.data();
868 span.lo == other.lo && span.hi == other.hi
869 }
870
871 pub fn trim_start(self, other: Span) -> Option<Span> {
873 let span = self.data();
874 let other = other.data();
875 if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None }
876 }
877
878 pub fn trim_end(self, other: Span) -> Option<Span> {
880 let span = self.data();
881 let other = other.data();
882 if span.lo < other.lo { Some(span.with_hi(cmp::min(span.hi, other.lo))) } else { None }
883 }
884
885 pub fn source_callsite(self) -> Span {
888 let ctxt = self.ctxt();
889 if !ctxt.is_root() { ctxt.outer_expn_data().call_site.source_callsite() } else { self }
890 }
891
892 pub fn parent_callsite(self) -> Option<Span> {
895 let ctxt = self.ctxt();
896 (!ctxt.is_root()).then(|| ctxt.outer_expn_data().call_site)
897 }
898
899 pub fn find_ancestor_inside(mut self, outer: Span) -> Option<Span> {
912 while !outer.contains(self) {
913 self = self.parent_callsite()?;
914 }
915 Some(self)
916 }
917
918 pub fn find_ancestor_in_same_ctxt(mut self, other: Span) -> Option<Span> {
931 while !self.eq_ctxt(other) {
932 self = self.parent_callsite()?;
933 }
934 Some(self)
935 }
936
937 pub fn find_ancestor_inside_same_ctxt(mut self, outer: Span) -> Option<Span> {
950 while !outer.contains(self) || !self.eq_ctxt(outer) {
951 self = self.parent_callsite()?;
952 }
953 Some(self)
954 }
955
956 pub fn find_ancestor_not_from_extern_macro(mut self, sm: &SourceMap) -> Option<Span> {
970 while self.in_external_macro(sm) {
971 self = self.parent_callsite()?;
972 }
973 Some(self)
974 }
975
976 pub fn find_ancestor_not_from_macro(mut self) -> Option<Span> {
989 while self.from_expansion() {
990 self = self.parent_callsite()?;
991 }
992 Some(self)
993 }
994
995 pub fn edition(self) -> edition::Edition {
997 self.ctxt().edition()
998 }
999
1000 #[inline]
1002 pub fn is_rust_2015(self) -> bool {
1003 self.edition().is_rust_2015()
1004 }
1005
1006 #[inline]
1008 pub fn at_least_rust_2018(self) -> bool {
1009 self.edition().at_least_rust_2018()
1010 }
1011
1012 #[inline]
1014 pub fn at_least_rust_2021(self) -> bool {
1015 self.edition().at_least_rust_2021()
1016 }
1017
1018 #[inline]
1020 pub fn at_least_rust_2024(self) -> bool {
1021 self.edition().at_least_rust_2024()
1022 }
1023
1024 pub fn source_callee(self) -> Option<ExpnData> {
1030 let mut ctxt = self.ctxt();
1031 let mut opt_expn_data = None;
1032 while !ctxt.is_root() {
1033 let expn_data = ctxt.outer_expn_data();
1034 ctxt = expn_data.call_site.ctxt();
1035 opt_expn_data = Some(expn_data);
1036 }
1037 opt_expn_data
1038 }
1039
1040 pub fn allows_unstable(self, feature: Symbol) -> bool {
1044 self.ctxt()
1045 .outer_expn_data()
1046 .allow_internal_unstable
1047 .is_some_and(|features| features.contains(&feature))
1048 }
1049
1050 pub fn is_desugaring(self, kind: DesugaringKind) -> bool {
1052 match self.ctxt().outer_expn_data().kind {
1053 ExpnKind::Desugaring(k) => k == kind,
1054 _ => false,
1055 }
1056 }
1057
1058 pub fn desugaring_kind(self) -> Option<DesugaringKind> {
1061 match self.ctxt().outer_expn_data().kind {
1062 ExpnKind::Desugaring(k) => Some(k),
1063 _ => None,
1064 }
1065 }
1066
1067 pub fn allows_unsafe(self) -> bool {
1071 self.ctxt().outer_expn_data().allow_internal_unsafe
1072 }
1073
1074 pub fn macro_backtrace(mut self) -> impl Iterator<Item = ExpnData> {
1075 let mut prev_span = DUMMY_SP;
1076 iter::from_fn(move || {
1077 loop {
1078 let ctxt = self.ctxt();
1079 if ctxt.is_root() {
1080 return None;
1081 }
1082
1083 let expn_data = ctxt.outer_expn_data();
1084 let is_recursive = expn_data.call_site.source_equal(prev_span);
1085
1086 prev_span = self;
1087 self = expn_data.call_site;
1088
1089 if !is_recursive {
1091 return Some(expn_data);
1092 }
1093 }
1094 })
1095 }
1096
1097 pub fn split_at(self, pos: u32) -> (Span, Span) {
1099 let len = self.hi().0 - self.lo().0;
1100 if true {
if !(pos <= len) {
::core::panicking::panic("assertion failed: pos <= len")
};
};debug_assert!(pos <= len);
1101
1102 let split_pos = BytePos(self.lo().0 + pos);
1103 (
1104 Span::new(self.lo(), split_pos, self.ctxt(), self.parent()),
1105 Span::new(split_pos, self.hi(), self.ctxt(), self.parent()),
1106 )
1107 }
1108
1109 fn try_metavars(a: SpanData, b: SpanData, a_orig: Span, b_orig: Span) -> (SpanData, SpanData) {
1111 match with_metavar_spans(|mspans| (mspans.get(a_orig), mspans.get(b_orig))) {
1112 (None, None) => {}
1113 (Some(meta_a), None) => {
1114 let meta_a = meta_a.data();
1115 if meta_a.ctxt == b.ctxt {
1116 return (meta_a, b);
1117 }
1118 }
1119 (None, Some(meta_b)) => {
1120 let meta_b = meta_b.data();
1121 if a.ctxt == meta_b.ctxt {
1122 return (a, meta_b);
1123 }
1124 }
1125 (Some(meta_a), Some(meta_b)) => {
1126 let meta_b = meta_b.data();
1127 if a.ctxt == meta_b.ctxt {
1128 return (a, meta_b);
1129 }
1130 let meta_a = meta_a.data();
1131 if meta_a.ctxt == b.ctxt {
1132 return (meta_a, b);
1133 } else if meta_a.ctxt == meta_b.ctxt {
1134 return (meta_a, meta_b);
1135 }
1136 }
1137 }
1138
1139 (a, b)
1140 }
1141
1142 fn prepare_to_combine(
1144 a_orig: Span,
1145 b_orig: Span,
1146 ) -> Result<(SpanData, SpanData, Option<LocalDefId>), Span> {
1147 let (a, b) = (a_orig.data(), b_orig.data());
1148 if a.ctxt == b.ctxt {
1149 return Ok((a, b, if a.parent == b.parent { a.parent } else { None }));
1150 }
1151
1152 let (a, b) = Span::try_metavars(a, b, a_orig, b_orig);
1153 if a.ctxt == b.ctxt {
1154 return Ok((a, b, if a.parent == b.parent { a.parent } else { None }));
1155 }
1156
1157 let a_is_callsite = a.ctxt.is_root() || a.ctxt == b.span().source_callsite().ctxt();
1165 Err(if a_is_callsite { b_orig } else { a_orig })
1166 }
1167
1168 pub fn with_neighbor(self, neighbor: Span) -> Span {
1170 match Span::prepare_to_combine(self, neighbor) {
1171 Ok((this, ..)) => this.span(),
1172 Err(_) => self,
1173 }
1174 }
1175
1176 pub fn to(self, end: Span) -> Span {
1187 match Span::prepare_to_combine(self, end) {
1188 Ok((from, to, parent)) => {
1189 Span::new(cmp::min(from.lo, to.lo), cmp::max(from.hi, to.hi), from.ctxt, parent)
1190 }
1191 Err(fallback) => fallback,
1192 }
1193 }
1194
1195 pub fn between(self, end: Span) -> Span {
1203 match Span::prepare_to_combine(self, end) {
1204 Ok((from, to, parent)) => {
1205 Span::new(cmp::min(from.hi, to.hi), cmp::max(from.lo, to.lo), from.ctxt, parent)
1206 }
1207 Err(fallback) => fallback,
1208 }
1209 }
1210
1211 pub fn until(self, end: Span) -> Span {
1219 match Span::prepare_to_combine(self, end) {
1220 Ok((from, to, parent)) => {
1221 Span::new(cmp::min(from.lo, to.lo), cmp::max(from.lo, to.lo), from.ctxt, parent)
1222 }
1223 Err(fallback) => fallback,
1224 }
1225 }
1226
1227 pub fn within_macro(self, within: Span, sm: &SourceMap) -> Option<Span> {
1242 let (self_, _, parent) = Span::prepare_to_combine(self, within).ok()?;
1243
1244 if self.data().contains(self_) || sm.is_imported(within) {
1251 return None;
1252 }
1253
1254 if within.data().ctxt.outer_expn_data().diagnostic_opaque {
1257 return None;
1258 }
1259
1260 Some(Span::new(self_.lo, self_.hi, self_.ctxt, parent))
1261 }
1262
1263 pub fn from_inner(self, inner: InnerSpan) -> Span {
1264 let span = self.data();
1265 Span::new(
1266 span.lo + BytePos::from_usize(inner.start),
1267 span.lo + BytePos::from_usize(inner.end),
1268 span.ctxt,
1269 span.parent,
1270 )
1271 }
1272
1273 pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span {
1276 self.with_ctxt_from_mark(expn_id, Transparency::Opaque)
1277 }
1278
1279 pub fn with_call_site_ctxt(self, expn_id: ExpnId) -> Span {
1282 self.with_ctxt_from_mark(expn_id, Transparency::Transparent)
1283 }
1284
1285 pub fn with_mixed_site_ctxt(self, expn_id: ExpnId) -> Span {
1288 self.with_ctxt_from_mark(expn_id, Transparency::SemiOpaque)
1289 }
1290
1291 fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
1295 self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency))
1296 }
1297
1298 #[inline]
1299 pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span {
1300 self.map_ctxt(|ctxt| ctxt.apply_mark(expn_id, transparency))
1301 }
1302
1303 #[inline]
1304 pub fn remove_mark(&mut self) -> ExpnId {
1305 let mut mark = ExpnId::root();
1306 *self = self.map_ctxt(|mut ctxt| {
1307 mark = ctxt.remove_mark();
1308 ctxt
1309 });
1310 mark
1311 }
1312
1313 #[inline]
1314 pub fn adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
1315 let mut mark = None;
1316 *self = self.map_ctxt(|mut ctxt| {
1317 mark = ctxt.adjust(expn_id);
1318 ctxt
1319 });
1320 mark
1321 }
1322
1323 #[inline]
1324 pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option<ExpnId> {
1325 let mut mark = None;
1326 *self = self.map_ctxt(|mut ctxt| {
1327 mark = ctxt.normalize_to_macros_2_0_and_adjust(expn_id);
1328 ctxt
1329 });
1330 mark
1331 }
1332
1333 #[inline]
1334 pub fn normalize_to_macros_2_0(self) -> Span {
1335 self.map_ctxt(|ctxt| ctxt.normalize_to_macros_2_0())
1336 }
1337
1338 #[inline]
1339 pub fn normalize_to_macro_rules(self) -> Span {
1340 self.map_ctxt(|ctxt| ctxt.normalize_to_macro_rules())
1341 }
1342}
1343
1344impl Default for Span {
1345 fn default() -> Self {
1346 DUMMY_SP
1347 }
1348}
1349
1350impl ::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! {
1351 #[orderable]
1352 #[debug_format = "AttrId({})"]
1353 pub struct AttrId {}
1354}
1355
1356pub trait SpanEncoder: Encoder {
1359 fn encode_span(&mut self, span: Span);
1360 fn encode_symbol(&mut self, sym: Symbol);
1361 fn encode_byte_symbol(&mut self, byte_sym: ByteSymbol);
1362 fn encode_expn_id(&mut self, expn_id: ExpnId);
1363 fn encode_syntax_context(&mut self, syntax_context: SyntaxContext);
1364 fn encode_crate_num(&mut self, crate_num: CrateNum);
1367 fn encode_def_index(&mut self, def_index: DefIndex);
1368 fn encode_def_id(&mut self, def_id: DefId);
1369}
1370
1371impl SpanEncoder for FileEncoder<'_> {
1372 fn encode_span(&mut self, span: Span) {
1373 let span = span.data();
1374 span.lo.encode(self);
1375 span.hi.encode(self);
1376 }
1377
1378 fn encode_symbol(&mut self, sym: Symbol) {
1379 self.emit_str(sym.as_str());
1380 }
1381
1382 fn encode_byte_symbol(&mut self, byte_sym: ByteSymbol) {
1383 self.emit_byte_str(byte_sym.as_byte_str());
1384 }
1385
1386 fn encode_expn_id(&mut self, _expn_id: ExpnId) {
1387 {
::core::panicking::panic_fmt(format_args!("cannot encode `ExpnId` with `FileEncoder`"));
};panic!("cannot encode `ExpnId` with `FileEncoder`");
1388 }
1389
1390 fn encode_syntax_context(&mut self, _syntax_context: SyntaxContext) {
1391 {
::core::panicking::panic_fmt(format_args!("cannot encode `SyntaxContext` with `FileEncoder`"));
};panic!("cannot encode `SyntaxContext` with `FileEncoder`");
1392 }
1393
1394 fn encode_crate_num(&mut self, crate_num: CrateNum) {
1395 self.emit_u32(crate_num.as_u32());
1396 }
1397
1398 fn encode_def_index(&mut self, _def_index: DefIndex) {
1399 {
::core::panicking::panic_fmt(format_args!("cannot encode `DefIndex` with `FileEncoder`"));
};panic!("cannot encode `DefIndex` with `FileEncoder`");
1400 }
1401
1402 fn encode_def_id(&mut self, def_id: DefId) {
1403 def_id.krate.encode(self);
1404 def_id.index.encode(self);
1405 }
1406}
1407
1408impl SpanEncoder for MemEncoder {
1409 fn encode_span(&mut self, span: Span) {
1410 let span = span.data();
1411 span.lo.encode(self);
1412 span.hi.encode(self);
1413 }
1414
1415 fn encode_symbol(&mut self, sym: Symbol) {
1416 self.emit_str(sym.as_str());
1417 }
1418
1419 fn encode_byte_symbol(&mut self, byte_sym: ByteSymbol) {
1420 self.emit_byte_str(byte_sym.as_byte_str());
1421 }
1422
1423 fn encode_expn_id(&mut self, _expn_id: ExpnId) {
1424 {
::core::panicking::panic_fmt(format_args!("cannot encode `ExpnId` with `FileEncoder`"));
};panic!("cannot encode `ExpnId` with `FileEncoder`");
1425 }
1426
1427 fn encode_syntax_context(&mut self, _syntax_context: SyntaxContext) {
1428 {
::core::panicking::panic_fmt(format_args!("cannot encode `SyntaxContext` with `FileEncoder`"));
};panic!("cannot encode `SyntaxContext` with `FileEncoder`");
1429 }
1430
1431 fn encode_crate_num(&mut self, crate_num: CrateNum) {
1432 self.emit_u32(crate_num.as_u32());
1433 }
1434
1435 fn encode_def_index(&mut self, _def_index: DefIndex) {
1436 {
::core::panicking::panic_fmt(format_args!("cannot encode `DefIndex` with `FileEncoder`"));
};panic!("cannot encode `DefIndex` with `FileEncoder`");
1437 }
1438
1439 fn encode_def_id(&mut self, def_id: DefId) {
1440 def_id.krate.encode(self);
1441 def_id.index.encode(self);
1442 }
1443}
1444
1445impl<E: SpanEncoder> Encodable<E> for Span {
1446 fn encode(&self, s: &mut E) {
1447 s.encode_span(*self);
1448 }
1449}
1450
1451impl<E: SpanEncoder> Encodable<E> for Symbol {
1452 fn encode(&self, s: &mut E) {
1453 s.encode_symbol(*self);
1454 }
1455}
1456
1457impl<E: SpanEncoder> Encodable<E> for ByteSymbol {
1458 fn encode(&self, s: &mut E) {
1459 s.encode_byte_symbol(*self);
1460 }
1461}
1462
1463impl<E: SpanEncoder> Encodable<E> for ExpnId {
1464 fn encode(&self, s: &mut E) {
1465 s.encode_expn_id(*self)
1466 }
1467}
1468
1469impl<E: SpanEncoder> Encodable<E> for SyntaxContext {
1470 fn encode(&self, s: &mut E) {
1471 s.encode_syntax_context(*self)
1472 }
1473}
1474
1475impl<E: SpanEncoder> Encodable<E> for CrateNum {
1476 fn encode(&self, s: &mut E) {
1477 s.encode_crate_num(*self)
1478 }
1479}
1480
1481impl<E: SpanEncoder> Encodable<E> for DefIndex {
1482 fn encode(&self, s: &mut E) {
1483 s.encode_def_index(*self)
1484 }
1485}
1486
1487impl<E: SpanEncoder> Encodable<E> for DefId {
1488 fn encode(&self, s: &mut E) {
1489 s.encode_def_id(*self)
1490 }
1491}
1492
1493impl<E: SpanEncoder> Encodable<E> for AttrId {
1494 fn encode(&self, _s: &mut E) {
1495 }
1497}
1498
1499pub trait BlobDecoder: Decoder {
1500 fn decode_symbol(&mut self) -> Symbol;
1501 fn decode_byte_symbol(&mut self) -> ByteSymbol;
1502 fn decode_def_index(&mut self) -> DefIndex;
1503}
1504
1505pub trait SpanDecoder: BlobDecoder {
1522 fn decode_span(&mut self) -> Span;
1523 fn decode_expn_id(&mut self) -> ExpnId;
1524 fn decode_syntax_context(&mut self) -> SyntaxContext;
1525 fn decode_crate_num(&mut self) -> CrateNum;
1526 fn decode_def_id(&mut self) -> DefId;
1527 fn decode_attr_id(&mut self) -> AttrId;
1528}
1529
1530impl BlobDecoder for MemDecoder<'_> {
1531 fn decode_symbol(&mut self) -> Symbol {
1532 Symbol::intern(self.read_str())
1533 }
1534
1535 fn decode_byte_symbol(&mut self) -> ByteSymbol {
1536 ByteSymbol::intern(self.read_byte_str())
1537 }
1538
1539 fn decode_def_index(&mut self) -> DefIndex {
1540 {
::core::panicking::panic_fmt(format_args!("cannot decode `DefIndex` with `MemDecoder`"));
};panic!("cannot decode `DefIndex` with `MemDecoder`");
1541 }
1542}
1543
1544impl SpanDecoder for MemDecoder<'_> {
1545 fn decode_span(&mut self) -> Span {
1546 let lo = Decodable::decode(self);
1547 let hi = Decodable::decode(self);
1548
1549 Span::new(lo, hi, SyntaxContext::root(), None)
1550 }
1551
1552 fn decode_expn_id(&mut self) -> ExpnId {
1553 {
::core::panicking::panic_fmt(format_args!("cannot decode `ExpnId` with `MemDecoder`"));
};panic!("cannot decode `ExpnId` with `MemDecoder`");
1554 }
1555
1556 fn decode_syntax_context(&mut self) -> SyntaxContext {
1557 {
::core::panicking::panic_fmt(format_args!("cannot decode `SyntaxContext` with `MemDecoder`"));
};panic!("cannot decode `SyntaxContext` with `MemDecoder`");
1558 }
1559
1560 fn decode_crate_num(&mut self) -> CrateNum {
1561 CrateNum::from_u32(self.read_u32())
1562 }
1563
1564 fn decode_def_id(&mut self) -> DefId {
1565 DefId { krate: Decodable::decode(self), index: Decodable::decode(self) }
1566 }
1567
1568 fn decode_attr_id(&mut self) -> AttrId {
1569 {
::core::panicking::panic_fmt(format_args!("cannot decode `AttrId` with `MemDecoder`"));
};panic!("cannot decode `AttrId` with `MemDecoder`");
1570 }
1571}
1572
1573impl<D: SpanDecoder> Decodable<D> for Span {
1574 fn decode(s: &mut D) -> Span {
1575 s.decode_span()
1576 }
1577}
1578
1579impl<D: BlobDecoder> Decodable<D> for Symbol {
1580 fn decode(s: &mut D) -> Symbol {
1581 s.decode_symbol()
1582 }
1583}
1584
1585impl<D: BlobDecoder> Decodable<D> for ByteSymbol {
1586 fn decode(s: &mut D) -> ByteSymbol {
1587 s.decode_byte_symbol()
1588 }
1589}
1590
1591impl<D: SpanDecoder> Decodable<D> for ExpnId {
1592 fn decode(s: &mut D) -> ExpnId {
1593 s.decode_expn_id()
1594 }
1595}
1596
1597impl<D: SpanDecoder> Decodable<D> for SyntaxContext {
1598 fn decode(s: &mut D) -> SyntaxContext {
1599 s.decode_syntax_context()
1600 }
1601}
1602
1603impl<D: SpanDecoder> Decodable<D> for CrateNum {
1604 fn decode(s: &mut D) -> CrateNum {
1605 s.decode_crate_num()
1606 }
1607}
1608
1609impl<D: BlobDecoder> Decodable<D> for DefIndex {
1610 fn decode(s: &mut D) -> DefIndex {
1611 s.decode_def_index()
1612 }
1613}
1614
1615impl<D: SpanDecoder> Decodable<D> for DefId {
1616 fn decode(s: &mut D) -> DefId {
1617 s.decode_def_id()
1618 }
1619}
1620
1621impl<D: SpanDecoder> Decodable<D> for AttrId {
1622 fn decode(s: &mut D) -> AttrId {
1623 s.decode_attr_id()
1624 }
1625}
1626
1627impl fmt::Debug for Span {
1628 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1629 fn fallback(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1633 f.debug_struct("Span")
1634 .field("lo", &span.lo())
1635 .field("hi", &span.hi())
1636 .field("ctxt", &span.ctxt())
1637 .finish()
1638 }
1639
1640 if SESSION_GLOBALS.is_set() {
1641 with_session_globals(|session_globals| {
1642 if let Some(source_map) = &session_globals.source_map {
1643 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())
1644 } else {
1645 fallback(*self, f)
1646 }
1647 })
1648 } else {
1649 fallback(*self, f)
1650 }
1651 }
1652}
1653
1654impl fmt::Debug for SpanData {
1655 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1656 fmt::Debug::fmt(&self.span(), f)
1657 }
1658}
1659
1660#[derive(#[automatically_derived]
impl ::core::marker::Copy for MultiByteChar { }Copy, #[automatically_derived]
impl ::core::clone::Clone for MultiByteChar {
#[inline]
fn clone(&self) -> MultiByteChar {
let _: ::core::clone::AssertParamIsClone<RelativeBytePos>;
let _: ::core::clone::AssertParamIsClone<u8>;
*self
}
}Clone, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for MultiByteChar {
fn encode(&self, __encoder: &mut __E) {
match *self {
MultiByteChar { pos: ref __binding_0, bytes: ref __binding_1
} => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for MultiByteChar {
fn decode(__decoder: &mut __D) -> Self {
MultiByteChar {
pos: ::rustc_serialize::Decodable::decode(__decoder),
bytes: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable, #[automatically_derived]
impl ::core::cmp::Eq for MultiByteChar {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<RelativeBytePos>;
let _: ::core::cmp::AssertParamIsEq<u8>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for MultiByteChar {
#[inline]
fn eq(&self, other: &MultiByteChar) -> bool {
self.bytes == other.bytes && self.pos == other.pos
}
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for MultiByteChar {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "MultiByteChar",
"pos", &self.pos, "bytes", &&self.bytes)
}
}Debug, const _: () =
{
impl ::rustc_data_structures::stable_hash::StableHash for
MultiByteChar {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
match *self {
MultiByteChar { pos: ref __binding_0, bytes: ref __binding_1
} => {
{ __binding_0.stable_hash(__hcx, __hasher); }
{ __binding_1.stable_hash(__hcx, __hasher); }
}
}
}
}
};StableHash)]
1662pub struct MultiByteChar {
1663 pub pos: RelativeBytePos,
1665 pub bytes: u8,
1667}
1668
1669#[derive(#[automatically_derived]
impl ::core::marker::Copy for NormalizedPos { }Copy, #[automatically_derived]
impl ::core::clone::Clone for NormalizedPos {
#[inline]
fn clone(&self) -> NormalizedPos {
let _: ::core::clone::AssertParamIsClone<RelativeBytePos>;
let _: ::core::clone::AssertParamIsClone<u32>;
*self
}
}Clone, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for NormalizedPos {
fn encode(&self, __encoder: &mut __E) {
match *self {
NormalizedPos { pos: ref __binding_0, diff: ref __binding_1
} => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for NormalizedPos {
fn decode(__decoder: &mut __D) -> Self {
NormalizedPos {
pos: ::rustc_serialize::Decodable::decode(__decoder),
diff: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable, #[automatically_derived]
impl ::core::cmp::Eq for NormalizedPos {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<RelativeBytePos>;
let _: ::core::cmp::AssertParamIsEq<u32>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for NormalizedPos {
#[inline]
fn eq(&self, other: &NormalizedPos) -> bool {
self.diff == other.diff && self.pos == other.pos
}
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for NormalizedPos {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "NormalizedPos",
"pos", &self.pos, "diff", &&self.diff)
}
}Debug, const _: () =
{
impl ::rustc_data_structures::stable_hash::StableHash for
NormalizedPos {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
match *self {
NormalizedPos { pos: ref __binding_0, diff: ref __binding_1
} => {
{ __binding_0.stable_hash(__hcx, __hasher); }
{ __binding_1.stable_hash(__hcx, __hasher); }
}
}
}
}
};StableHash)]
1671pub struct NormalizedPos {
1672 pub pos: RelativeBytePos,
1674 pub diff: u32,
1676}
1677
1678#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for ExternalSource {
#[inline]
fn eq(&self, other: &ExternalSource) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(ExternalSource::Foreign {
kind: __self_0, metadata_index: __self_1 },
ExternalSource::Foreign {
kind: __arg1_0, metadata_index: __arg1_1 }) =>
__self_1 == __arg1_1 && __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ExternalSource {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<ExternalSourceKind>;
let _: ::core::cmp::AssertParamIsEq<u32>;
}
}Eq, #[automatically_derived]
impl ::core::clone::Clone for ExternalSource {
#[inline]
fn clone(&self) -> ExternalSource {
match self {
ExternalSource::Unneeded => ExternalSource::Unneeded,
ExternalSource::Foreign { kind: __self_0, metadata_index: __self_1
} =>
ExternalSource::Foreign {
kind: ::core::clone::Clone::clone(__self_0),
metadata_index: ::core::clone::Clone::clone(__self_1),
},
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ExternalSource {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ExternalSource::Unneeded =>
::core::fmt::Formatter::write_str(f, "Unneeded"),
ExternalSource::Foreign { kind: __self_0, metadata_index: __self_1
} =>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Foreign", "kind", __self_0, "metadata_index", &__self_1),
}
}
}Debug)]
1679pub enum ExternalSource {
1680 Unneeded,
1682 Foreign {
1683 kind: ExternalSourceKind,
1684 metadata_index: u32,
1686 },
1687}
1688
1689#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for ExternalSourceKind {
#[inline]
fn eq(&self, other: &ExternalSourceKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(ExternalSourceKind::Present(__self_0),
ExternalSourceKind::Present(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ExternalSourceKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Arc<String>>;
}
}Eq, #[automatically_derived]
impl ::core::clone::Clone for ExternalSourceKind {
#[inline]
fn clone(&self) -> ExternalSourceKind {
match self {
ExternalSourceKind::Present(__self_0) =>
ExternalSourceKind::Present(::core::clone::Clone::clone(__self_0)),
ExternalSourceKind::AbsentOk => ExternalSourceKind::AbsentOk,
ExternalSourceKind::AbsentErr => ExternalSourceKind::AbsentErr,
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ExternalSourceKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ExternalSourceKind::Present(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"Present", &__self_0),
ExternalSourceKind::AbsentOk =>
::core::fmt::Formatter::write_str(f, "AbsentOk"),
ExternalSourceKind::AbsentErr =>
::core::fmt::Formatter::write_str(f, "AbsentErr"),
}
}
}Debug)]
1691pub enum ExternalSourceKind {
1692 Present(Arc<String>),
1694 AbsentOk,
1696 AbsentErr,
1698}
1699
1700impl ExternalSource {
1701 pub fn get_source(&self) -> Option<&str> {
1702 match self {
1703 ExternalSource::Foreign { kind: ExternalSourceKind::Present(src), .. } => Some(src),
1704 _ => None,
1705 }
1706 }
1707}
1708
1709#[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)]
1710pub struct OffsetOverflowError;
1711
1712#[derive(#[automatically_derived]
impl ::core::marker::Copy for SourceFileHashAlgorithm { }Copy, #[automatically_derived]
impl ::core::clone::Clone for SourceFileHashAlgorithm {
#[inline]
fn clone(&self) -> SourceFileHashAlgorithm { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for SourceFileHashAlgorithm {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
SourceFileHashAlgorithm::Md5 => "Md5",
SourceFileHashAlgorithm::Sha1 => "Sha1",
SourceFileHashAlgorithm::Sha256 => "Sha256",
SourceFileHashAlgorithm::Blake3 => "Blake3",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for SourceFileHashAlgorithm {
#[inline]
fn eq(&self, other: &SourceFileHashAlgorithm) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for SourceFileHashAlgorithm {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for SourceFileHashAlgorithm {
#[inline]
fn partial_cmp(&self, other: &SourceFileHashAlgorithm)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for SourceFileHashAlgorithm {
#[inline]
fn cmp(&self, other: &SourceFileHashAlgorithm) -> ::core::cmp::Ordering {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
::core::cmp::Ord::cmp(&__self_discr, &__arg1_discr)
}
}Ord, #[automatically_derived]
impl ::core::hash::Hash for SourceFileHashAlgorithm {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
let __self_discr = ::core::intrinsics::discriminant_value(self);
::core::hash::Hash::hash(&__self_discr, state)
}
}Hash, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for SourceFileHashAlgorithm {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
SourceFileHashAlgorithm::Md5 => { 0usize }
SourceFileHashAlgorithm::Sha1 => { 1usize }
SourceFileHashAlgorithm::Sha256 => { 2usize }
SourceFileHashAlgorithm::Blake3 => { 3usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
match *self {
SourceFileHashAlgorithm::Md5 => {}
SourceFileHashAlgorithm::Sha1 => {}
SourceFileHashAlgorithm::Sha256 => {}
SourceFileHashAlgorithm::Blake3 => {}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for SourceFileHashAlgorithm {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => { SourceFileHashAlgorithm::Md5 }
1usize => { SourceFileHashAlgorithm::Sha1 }
2usize => { SourceFileHashAlgorithm::Sha256 }
3usize => { SourceFileHashAlgorithm::Blake3 }
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `SourceFileHashAlgorithm`, expected 0..4, actual {0}",
n));
}
}
}
}
};Decodable)]
1713#[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)]
1714pub enum SourceFileHashAlgorithm {
1715 Md5,
1716 Sha1,
1717 Sha256,
1718 Blake3,
1719}
1720
1721impl Display for SourceFileHashAlgorithm {
1722 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1723 f.write_str(match self {
1724 Self::Md5 => "md5",
1725 Self::Sha1 => "sha1",
1726 Self::Sha256 => "sha256",
1727 Self::Blake3 => "blake3",
1728 })
1729 }
1730}
1731
1732impl FromStr for SourceFileHashAlgorithm {
1733 type Err = ();
1734
1735 fn from_str(s: &str) -> Result<SourceFileHashAlgorithm, ()> {
1736 match s {
1737 "md5" => Ok(SourceFileHashAlgorithm::Md5),
1738 "sha1" => Ok(SourceFileHashAlgorithm::Sha1),
1739 "sha256" => Ok(SourceFileHashAlgorithm::Sha256),
1740 "blake3" => Ok(SourceFileHashAlgorithm::Blake3),
1741 _ => Err(()),
1742 }
1743 }
1744}
1745
1746#[derive(#[automatically_derived]
impl ::core::marker::Copy for SourceFileHash { }Copy, #[automatically_derived]
impl ::core::clone::Clone for SourceFileHash {
#[inline]
fn clone(&self) -> SourceFileHash {
let _: ::core::clone::AssertParamIsClone<SourceFileHashAlgorithm>;
let _: ::core::clone::AssertParamIsClone<[u8; 32]>;
*self
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for SourceFileHash {
#[inline]
fn eq(&self, other: &SourceFileHash) -> bool {
self.kind == other.kind && self.value == other.value
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for SourceFileHash {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<SourceFileHashAlgorithm>;
let _: ::core::cmp::AssertParamIsEq<[u8; 32]>;
}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for SourceFileHash {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"SourceFileHash", "kind", &self.kind, "value", &&self.value)
}
}Debug, #[automatically_derived]
impl ::core::hash::Hash for SourceFileHash {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.kind, state);
::core::hash::Hash::hash(&self.value, state)
}
}Hash)]
1748#[derive(const _: () =
{
impl ::rustc_data_structures::stable_hash::StableHash for
SourceFileHash {
#[inline]
fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
__hcx: &mut __Hcx,
__hasher:
&mut ::rustc_data_structures::stable_hash::StableHasher) {
match *self {
SourceFileHash {
kind: ref __binding_0, value: ref __binding_1 } => {
{ __binding_0.stable_hash(__hcx, __hasher); }
{ __binding_1.stable_hash(__hcx, __hasher); }
}
}
}
}
};StableHash, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for SourceFileHash {
fn encode(&self, __encoder: &mut __E) {
match *self {
SourceFileHash {
kind: ref __binding_0, value: ref __binding_1 } => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for SourceFileHash {
fn decode(__decoder: &mut __D) -> Self {
SourceFileHash {
kind: ::rustc_serialize::Decodable::decode(__decoder),
value: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
1749pub struct SourceFileHash {
1750 pub kind: SourceFileHashAlgorithm,
1751 value: [u8; 32],
1752}
1753
1754impl Display for SourceFileHash {
1755 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1756 f.write_fmt(format_args!("{0}=", self.kind))write!(f, "{}=", self.kind)?;
1757 for byte in self.value[0..self.hash_len()].into_iter() {
1758 f.write_fmt(format_args!("{0:02x}", byte))write!(f, "{byte:02x}")?;
1759 }
1760 Ok(())
1761 }
1762}
1763
1764impl SourceFileHash {
1765 pub fn new_in_memory(kind: SourceFileHashAlgorithm, src: impl AsRef<[u8]>) -> SourceFileHash {
1766 let mut hash = SourceFileHash { kind, value: Default::default() };
1767 let len = hash.hash_len();
1768 let value = &mut hash.value[..len];
1769 let data = src.as_ref();
1770 match kind {
1771 SourceFileHashAlgorithm::Md5 => {
1772 value.copy_from_slice(&Md5::digest(data));
1773 }
1774 SourceFileHashAlgorithm::Sha1 => {
1775 value.copy_from_slice(&Sha1::digest(data));
1776 }
1777 SourceFileHashAlgorithm::Sha256 => {
1778 value.copy_from_slice(&Sha256::digest(data));
1779 }
1780 SourceFileHashAlgorithm::Blake3 => value.copy_from_slice(blake3::hash(data).as_bytes()),
1781 };
1782 hash
1783 }
1784
1785 pub fn new(kind: SourceFileHashAlgorithm, src: impl Read) -> Result<SourceFileHash, io::Error> {
1786 let mut hash = SourceFileHash { kind, value: Default::default() };
1787 let len = hash.hash_len();
1788 let value = &mut hash.value[..len];
1789 let mut buf = ::alloc::vec::from_elem(0, 16 * 1024)vec![0; 16 * 1024];
1792
1793 fn digest<T>(
1794 mut hasher: T,
1795 mut update: impl FnMut(&mut T, &[u8]),
1796 finish: impl FnOnce(T, &mut [u8]),
1797 mut src: impl Read,
1798 buf: &mut [u8],
1799 value: &mut [u8],
1800 ) -> Result<(), io::Error> {
1801 loop {
1802 let bytes_read = src.read(buf)?;
1803 if bytes_read == 0 {
1804 break;
1805 }
1806 update(&mut hasher, &buf[0..bytes_read]);
1807 }
1808 finish(hasher, value);
1809 Ok(())
1810 }
1811
1812 match kind {
1813 SourceFileHashAlgorithm::Sha256 => {
1814 digest(
1815 Sha256::new(),
1816 |h, b| {
1817 h.update(b);
1818 },
1819 |h, out| out.copy_from_slice(&h.finalize()),
1820 src,
1821 &mut buf,
1822 value,
1823 )?;
1824 }
1825 SourceFileHashAlgorithm::Sha1 => {
1826 digest(
1827 Sha1::new(),
1828 |h, b| {
1829 h.update(b);
1830 },
1831 |h, out| out.copy_from_slice(&h.finalize()),
1832 src,
1833 &mut buf,
1834 value,
1835 )?;
1836 }
1837 SourceFileHashAlgorithm::Md5 => {
1838 digest(
1839 Md5::new(),
1840 |h, b| {
1841 h.update(b);
1842 },
1843 |h, out| out.copy_from_slice(&h.finalize()),
1844 src,
1845 &mut buf,
1846 value,
1847 )?;
1848 }
1849 SourceFileHashAlgorithm::Blake3 => {
1850 digest(
1851 blake3::Hasher::new(),
1852 |h, b| {
1853 h.update(b);
1854 },
1855 |h, out| out.copy_from_slice(h.finalize().as_bytes()),
1856 src,
1857 &mut buf,
1858 value,
1859 )?;
1860 }
1861 }
1862 Ok(hash)
1863 }
1864
1865 pub fn matches(&self, src: &str) -> bool {
1867 Self::new_in_memory(self.kind, src.as_bytes()) == *self
1868 }
1869
1870 pub fn hash_bytes(&self) -> &[u8] {
1872 let len = self.hash_len();
1873 &self.value[..len]
1874 }
1875
1876 fn hash_len(&self) -> usize {
1877 match self.kind {
1878 SourceFileHashAlgorithm::Md5 => 16,
1879 SourceFileHashAlgorithm::Sha1 => 20,
1880 SourceFileHashAlgorithm::Sha256 | SourceFileHashAlgorithm::Blake3 => 32,
1881 }
1882 }
1883}
1884
1885#[derive(#[automatically_derived]
impl ::core::clone::Clone for SourceFileLines {
#[inline]
fn clone(&self) -> SourceFileLines {
match self {
SourceFileLines::Lines(__self_0) =>
SourceFileLines::Lines(::core::clone::Clone::clone(__self_0)),
SourceFileLines::Diffs(__self_0) =>
SourceFileLines::Diffs(::core::clone::Clone::clone(__self_0)),
}
}
}Clone)]
1886pub enum SourceFileLines {
1887 Lines(Vec<RelativeBytePos>),
1889
1890 Diffs(SourceFileDiffs),
1892}
1893
1894impl SourceFileLines {
1895 pub fn is_lines(&self) -> bool {
1896 #[allow(non_exhaustive_omitted_patterns)] match self {
SourceFileLines::Lines(_) => true,
_ => false,
}matches!(self, SourceFileLines::Lines(_))
1897 }
1898}
1899
1900#[derive(#[automatically_derived]
impl ::core::clone::Clone for SourceFileDiffs {
#[inline]
fn clone(&self) -> SourceFileDiffs {
SourceFileDiffs {
bytes_per_diff: ::core::clone::Clone::clone(&self.bytes_per_diff),
num_diffs: ::core::clone::Clone::clone(&self.num_diffs),
raw_diffs: ::core::clone::Clone::clone(&self.raw_diffs),
}
}
}Clone)]
1908pub struct SourceFileDiffs {
1909 bytes_per_diff: usize,
1913
1914 num_diffs: usize,
1917
1918 raw_diffs: Vec<u8>,
1924}
1925
1926pub struct SourceFile {
1928 pub name: FileName,
1932 pub src: Option<Arc<String>>,
1934 pub src_hash: SourceFileHash,
1936 pub checksum_hash: Option<SourceFileHash>,
1940 pub external_src: FreezeLock<ExternalSource>,
1943 pub start_pos: BytePos,
1945 pub normalized_source_len: RelativeBytePos,
1947 pub unnormalized_source_len: u32,
1949 pub lines: FreezeLock<SourceFileLines>,
1951 pub multibyte_chars: Vec<MultiByteChar>,
1953 pub normalized_pos: Vec<NormalizedPos>,
1955 pub stable_id: StableSourceFileId,
1959 pub cnum: CrateNum,
1961}
1962
1963impl Clone for SourceFile {
1964 fn clone(&self) -> Self {
1965 Self {
1966 name: self.name.clone(),
1967 src: self.src.clone(),
1968 src_hash: self.src_hash,
1969 checksum_hash: self.checksum_hash,
1970 external_src: self.external_src.clone(),
1971 start_pos: self.start_pos,
1972 normalized_source_len: self.normalized_source_len,
1973 unnormalized_source_len: self.unnormalized_source_len,
1974 lines: self.lines.clone(),
1975 multibyte_chars: self.multibyte_chars.clone(),
1976 normalized_pos: self.normalized_pos.clone(),
1977 stable_id: self.stable_id,
1978 cnum: self.cnum,
1979 }
1980 }
1981}
1982
1983impl<S: SpanEncoder> Encodable<S> for SourceFile {
1984 fn encode(&self, s: &mut S) {
1985 self.name.encode(s);
1986 self.src_hash.encode(s);
1987 self.checksum_hash.encode(s);
1988 self.normalized_source_len.encode(s);
1990 self.unnormalized_source_len.encode(s);
1991
1992 if !self.lines.read().is_lines() {
::core::panicking::panic("assertion failed: self.lines.read().is_lines()")
};assert!(self.lines.read().is_lines());
1994 let lines = self.lines();
1995 s.emit_u32(lines.len() as u32);
1997
1998 if lines.len() != 0 {
2000 let max_line_length = if lines.len() == 1 {
2001 0
2002 } else {
2003 lines
2004 .array_windows()
2005 .map(|&[fst, snd]| snd - fst)
2006 .map(|bp| bp.to_usize())
2007 .max()
2008 .unwrap()
2009 };
2010
2011 let bytes_per_diff: usize = match max_line_length {
2012 0..=0xFF => 1,
2013 0x100..=0xFFFF => 2,
2014 _ => 4,
2015 };
2016
2017 s.emit_u8(bytes_per_diff as u8);
2019
2020 {
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));
2022
2023 let diff_iter = lines.array_windows().map(|&[fst, snd]| snd - fst);
2025 let num_diffs = lines.len() - 1;
2026 let mut raw_diffs;
2027 match bytes_per_diff {
2028 1 => {
2029 raw_diffs = Vec::with_capacity(num_diffs);
2030 for diff in diff_iter {
2031 raw_diffs.push(diff.0 as u8);
2032 }
2033 }
2034 2 => {
2035 raw_diffs = Vec::with_capacity(bytes_per_diff * num_diffs);
2036 for diff in diff_iter {
2037 raw_diffs.extend_from_slice(&(diff.0 as u16).to_le_bytes());
2038 }
2039 }
2040 4 => {
2041 raw_diffs = Vec::with_capacity(bytes_per_diff * num_diffs);
2042 for diff in diff_iter {
2043 raw_diffs.extend_from_slice(&(diff.0).to_le_bytes());
2044 }
2045 }
2046 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
2047 }
2048 s.emit_raw_bytes(&raw_diffs);
2049 }
2050
2051 self.multibyte_chars.encode(s);
2052 self.stable_id.encode(s);
2053 self.normalized_pos.encode(s);
2054 self.cnum.encode(s);
2055 }
2056}
2057
2058impl<D: SpanDecoder> Decodable<D> for SourceFile {
2059 fn decode(d: &mut D) -> SourceFile {
2060 let name: FileName = Decodable::decode(d);
2061 let src_hash: SourceFileHash = Decodable::decode(d);
2062 let checksum_hash: Option<SourceFileHash> = Decodable::decode(d);
2063 let normalized_source_len: RelativeBytePos = Decodable::decode(d);
2064 let unnormalized_source_len = Decodable::decode(d);
2065 let lines = {
2066 let num_lines: u32 = Decodable::decode(d);
2067 if num_lines > 0 {
2068 let bytes_per_diff = d.read_u8() as usize;
2070
2071 let num_diffs = num_lines as usize - 1;
2073 let raw_diffs = d.read_raw_bytes(bytes_per_diff * num_diffs).to_vec();
2074 SourceFileLines::Diffs(SourceFileDiffs { bytes_per_diff, num_diffs, raw_diffs })
2075 } else {
2076 SourceFileLines::Lines(::alloc::vec::Vec::new()vec![])
2077 }
2078 };
2079 let multibyte_chars: Vec<MultiByteChar> = Decodable::decode(d);
2080 let stable_id = Decodable::decode(d);
2081 let normalized_pos: Vec<NormalizedPos> = Decodable::decode(d);
2082 let cnum: CrateNum = Decodable::decode(d);
2083 SourceFile {
2084 name,
2085 start_pos: BytePos::from_u32(0),
2086 normalized_source_len,
2087 unnormalized_source_len,
2088 src: None,
2089 src_hash,
2090 checksum_hash,
2091 external_src: FreezeLock::frozen(ExternalSource::Unneeded),
2094 lines: FreezeLock::new(lines),
2095 multibyte_chars,
2096 normalized_pos,
2097 stable_id,
2098 cnum,
2099 }
2100 }
2101}
2102
2103impl fmt::Debug for SourceFile {
2104 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
2105 fmt.write_fmt(format_args!("SourceFile({0:?})", self.name))write!(fmt, "SourceFile({:?})", self.name)
2106 }
2107}
2108
2109#[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]
impl ::core::clone::Clone for StableSourceFileId {
#[inline]
fn clone(&self) -> StableSourceFileId {
let _: ::core::clone::AssertParamIsClone<Hash128>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for StableSourceFileId { }Copy, #[automatically_derived]
impl ::core::hash::Hash for StableSourceFileId {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}Hash, #[automatically_derived]
impl ::core::cmp::PartialEq for StableSourceFileId {
#[inline]
fn eq(&self, other: &StableSourceFileId) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for StableSourceFileId {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Hash128>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for StableSourceFileId {
#[inline]
fn partial_cmp(&self, other: &StableSourceFileId)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd, #[automatically_derived]
impl ::core::default::Default for StableSourceFileId {
#[inline]
fn default() -> StableSourceFileId {
StableSourceFileId(::core::default::Default::default())
}
}Default, #[automatically_derived]
impl ::core::cmp::Ord for StableSourceFileId {
#[inline]
fn cmp(&self, other: &StableSourceFileId) -> ::core::cmp::Ordering {
::core::cmp::Ord::cmp(&self.0, &other.0)
}
}Ord)]
2131#[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) {
match *self {
StableSourceFileId(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for StableSourceFileId {
fn decode(__decoder: &mut __D) -> Self {
StableSourceFileId(::rustc_serialize::Decodable::decode(__decoder))
}
}
};Decodable)]
2132pub struct StableSourceFileId(Hash128);
2133
2134impl StableSourceFileId {
2135 fn from_filename_in_current_crate(filename: &FileName) -> Self {
2136 Self::from_filename_and_stable_crate_id(filename, None)
2137 }
2138
2139 pub fn from_filename_for_export(
2140 filename: &FileName,
2141 local_crate_stable_crate_id: StableCrateId,
2142 ) -> Self {
2143 Self::from_filename_and_stable_crate_id(filename, Some(local_crate_stable_crate_id))
2144 }
2145
2146 fn from_filename_and_stable_crate_id(
2147 filename: &FileName,
2148 stable_crate_id: Option<StableCrateId>,
2149 ) -> Self {
2150 let mut hasher = StableHasher::new();
2151 filename.hash(&mut hasher);
2152 stable_crate_id.hash(&mut hasher);
2153 StableSourceFileId(hasher.finish())
2154 }
2155}
2156
2157impl SourceFile {
2158 const MAX_FILE_SIZE: u32 = u32::MAX - 1;
2159
2160 pub fn new(
2161 name: FileName,
2162 mut src: String,
2163 hash_kind: SourceFileHashAlgorithm,
2164 checksum_hash_kind: Option<SourceFileHashAlgorithm>,
2165 ) -> Result<Self, OffsetOverflowError> {
2166 let src_hash = SourceFileHash::new_in_memory(hash_kind, src.as_bytes());
2168 let checksum_hash = checksum_hash_kind.map(|checksum_hash_kind| {
2169 if checksum_hash_kind == hash_kind {
2170 src_hash
2171 } else {
2172 SourceFileHash::new_in_memory(checksum_hash_kind, src.as_bytes())
2173 }
2174 });
2175 let unnormalized_source_len = u32::try_from(src.len()).map_err(|_| OffsetOverflowError)?;
2177 if unnormalized_source_len > Self::MAX_FILE_SIZE {
2178 return Err(OffsetOverflowError);
2179 }
2180
2181 let normalized_pos = normalize_src(&mut src);
2182
2183 let stable_id = StableSourceFileId::from_filename_in_current_crate(&name);
2184 let normalized_source_len = u32::try_from(src.len()).map_err(|_| OffsetOverflowError)?;
2185 if normalized_source_len > Self::MAX_FILE_SIZE {
2186 return Err(OffsetOverflowError);
2187 }
2188
2189 let (lines, multibyte_chars) = analyze_source_file::analyze_source_file(&src);
2190
2191 Ok(SourceFile {
2192 name,
2193 src: Some(Arc::new(src)),
2194 src_hash,
2195 checksum_hash,
2196 external_src: FreezeLock::frozen(ExternalSource::Unneeded),
2197 start_pos: BytePos::from_u32(0),
2198 normalized_source_len: RelativeBytePos::from_u32(normalized_source_len),
2199 unnormalized_source_len,
2200 lines: FreezeLock::frozen(SourceFileLines::Lines(lines)),
2201 multibyte_chars,
2202 normalized_pos,
2203 stable_id,
2204 cnum: LOCAL_CRATE,
2205 })
2206 }
2207
2208 fn convert_diffs_to_lines_frozen(&self) {
2211 let mut guard = if let Some(guard) = self.lines.try_write() { guard } else { return };
2212
2213 let SourceFileDiffs { bytes_per_diff, num_diffs, raw_diffs } = match &*guard {
2214 SourceFileLines::Diffs(diffs) => diffs,
2215 SourceFileLines::Lines(..) => {
2216 FreezeWriteGuard::freeze(guard);
2217 return;
2218 }
2219 };
2220
2221 let num_lines = num_diffs + 1;
2223 let mut lines = Vec::with_capacity(num_lines);
2224 let mut line_start = RelativeBytePos(0);
2225 lines.push(line_start);
2226
2227 {
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);
2228 match bytes_per_diff {
2229 1 => {
2230 lines.extend(raw_diffs.into_iter().map(|&diff| {
2231 line_start = line_start + RelativeBytePos(diff as u32);
2232 line_start
2233 }));
2234 }
2235 2 => {
2236 lines.extend((0..*num_diffs).map(|i| {
2237 let pos = bytes_per_diff * i;
2238 let bytes = [raw_diffs[pos], raw_diffs[pos + 1]];
2239 let diff = u16::from_le_bytes(bytes);
2240 line_start = line_start + RelativeBytePos(diff as u32);
2241 line_start
2242 }));
2243 }
2244 4 => {
2245 lines.extend((0..*num_diffs).map(|i| {
2246 let pos = bytes_per_diff * i;
2247 let bytes = [
2248 raw_diffs[pos],
2249 raw_diffs[pos + 1],
2250 raw_diffs[pos + 2],
2251 raw_diffs[pos + 3],
2252 ];
2253 let diff = u32::from_le_bytes(bytes);
2254 line_start = line_start + RelativeBytePos(diff);
2255 line_start
2256 }));
2257 }
2258 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
2259 }
2260
2261 *guard = SourceFileLines::Lines(lines);
2262
2263 FreezeWriteGuard::freeze(guard);
2264 }
2265
2266 pub fn lines(&self) -> &[RelativeBytePos] {
2267 if let Some(SourceFileLines::Lines(lines)) = self.lines.get() {
2268 return &lines[..];
2269 }
2270
2271 outline(|| {
2272 self.convert_diffs_to_lines_frozen();
2273 if let Some(SourceFileLines::Lines(lines)) = self.lines.get() {
2274 return &lines[..];
2275 }
2276 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
2277 })
2278 }
2279
2280 pub fn line_begin_pos(&self, pos: BytePos) -> BytePos {
2282 let pos = self.relative_position(pos);
2283 let line_index = self.lookup_line(pos).unwrap();
2284 let line_start_pos = self.lines()[line_index];
2285 self.absolute_position(line_start_pos)
2286 }
2287
2288 pub fn add_external_src<F>(&self, get_src: F) -> bool
2293 where
2294 F: FnOnce() -> Option<String>,
2295 {
2296 if !self.external_src.is_frozen() {
2297 let src = get_src();
2298 let src = src.and_then(|mut src| {
2299 self.src_hash.matches(&src).then(|| {
2301 normalize_src(&mut src);
2302 src
2303 })
2304 });
2305
2306 self.external_src.try_write().map(|mut external_src| {
2307 if let ExternalSource::Foreign {
2308 kind: src_kind @ ExternalSourceKind::AbsentOk,
2309 ..
2310 } = &mut *external_src
2311 {
2312 *src_kind = if let Some(src) = src {
2313 ExternalSourceKind::Present(Arc::new(src))
2314 } else {
2315 ExternalSourceKind::AbsentErr
2316 };
2317 } else {
2318 {
::core::panicking::panic_fmt(format_args!("unexpected state {0:?}",
*external_src));
}panic!("unexpected state {:?}", *external_src)
2319 }
2320
2321 FreezeWriteGuard::freeze(external_src)
2323 });
2324 }
2325
2326 self.src.is_some() || self.external_src.read().get_source().is_some()
2327 }
2328
2329 pub fn get_line(&self, line_number: usize) -> Option<Cow<'_, str>> {
2332 fn get_until_newline(src: &str, begin: usize) -> &str {
2333 let slice = &src[begin..];
2337 match slice.find('\n') {
2338 Some(e) => &slice[..e],
2339 None => slice,
2340 }
2341 }
2342
2343 let begin = {
2344 let line = self.lines().get(line_number).copied()?;
2345 line.to_usize()
2346 };
2347
2348 if let Some(ref src) = self.src {
2349 Some(Cow::from(get_until_newline(src, begin)))
2350 } else {
2351 self.external_src
2352 .borrow()
2353 .get_source()
2354 .map(|src| Cow::Owned(String::from(get_until_newline(src, begin))))
2355 }
2356 }
2357
2358 pub fn is_real_file(&self) -> bool {
2359 self.name.is_real()
2360 }
2361
2362 #[inline]
2363 pub fn is_imported(&self) -> bool {
2364 self.src.is_none()
2365 }
2366
2367 pub fn count_lines(&self) -> usize {
2368 self.lines().len()
2369 }
2370
2371 #[inline]
2372 pub fn absolute_position(&self, pos: RelativeBytePos) -> BytePos {
2373 BytePos::from_u32(pos.to_u32() + self.start_pos.to_u32())
2374 }
2375
2376 #[inline]
2377 pub fn relative_position(&self, pos: BytePos) -> RelativeBytePos {
2378 RelativeBytePos::from_u32(pos.to_u32() - self.start_pos.to_u32())
2379 }
2380
2381 #[inline]
2382 pub fn end_position(&self) -> BytePos {
2383 self.absolute_position(self.normalized_source_len)
2384 }
2385
2386 pub fn lookup_line(&self, pos: RelativeBytePos) -> Option<usize> {
2391 self.lines().partition_point(|x| x <= &pos).checked_sub(1)
2392 }
2393
2394 pub fn line_bounds(&self, line_index: usize) -> Range<BytePos> {
2395 if self.is_empty() {
2396 return self.start_pos..self.start_pos;
2397 }
2398
2399 let lines = self.lines();
2400 if !(line_index < lines.len()) {
::core::panicking::panic("assertion failed: line_index < lines.len()")
};assert!(line_index < lines.len());
2401 if line_index == (lines.len() - 1) {
2402 self.absolute_position(lines[line_index])..self.end_position()
2403 } else {
2404 self.absolute_position(lines[line_index])..self.absolute_position(lines[line_index + 1])
2405 }
2406 }
2407
2408 #[inline]
2413 pub fn contains(&self, byte_pos: BytePos) -> bool {
2414 byte_pos >= self.start_pos && byte_pos <= self.end_position()
2415 }
2416
2417 #[inline]
2418 pub fn is_empty(&self) -> bool {
2419 self.normalized_source_len.to_u32() == 0
2420 }
2421
2422 pub fn original_relative_byte_pos(&self, pos: BytePos) -> RelativeBytePos {
2425 let pos = self.relative_position(pos);
2426
2427 let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) {
2431 Ok(i) => self.normalized_pos[i].diff,
2432 Err(0) => 0,
2433 Err(i) => self.normalized_pos[i - 1].diff,
2434 };
2435
2436 RelativeBytePos::from_u32(pos.0 + diff)
2437 }
2438
2439 pub fn normalized_byte_pos(&self, offset: u32) -> BytePos {
2449 let diff =
2450 match self.normalized_pos.binary_search_by(|np| (np.pos.0 + np.diff).cmp(&offset)) {
2451 Ok(i) => self.normalized_pos[i].diff,
2452 Err(0) => 0,
2453 Err(i) => self.normalized_pos[i - 1].diff,
2454 };
2455
2456 BytePos::from_u32(self.start_pos.0 + offset - diff)
2457 }
2458
2459 fn bytepos_to_file_charpos(&self, bpos: RelativeBytePos) -> CharPos {
2461 let mut total_extra_bytes = 0;
2463
2464 for mbc in self.multibyte_chars.iter() {
2465 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_span/src/lib.rs:2465",
"rustc_span", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_span/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2465u32),
::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);
2466 if mbc.pos < bpos {
2467 total_extra_bytes += mbc.bytes as u32 - 1;
2470 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);
2473 } else {
2474 break;
2475 }
2476 }
2477
2478 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());
2479 CharPos(bpos.to_usize() - total_extra_bytes as usize)
2480 }
2481
2482 fn lookup_file_pos(&self, pos: RelativeBytePos) -> (usize, CharPos) {
2485 let chpos = self.bytepos_to_file_charpos(pos);
2486 match self.lookup_line(pos) {
2487 Some(a) => {
2488 let line = a + 1; let linebpos = self.lines()[a];
2490 let linechpos = self.bytepos_to_file_charpos(linebpos);
2491 let col = chpos - linechpos;
2492 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_span/src/lib.rs:2492",
"rustc_span", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_span/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2492u32),
::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);
2493 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_span/src/lib.rs:2493",
"rustc_span", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_span/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2493u32),
::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);
2494 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_span/src/lib.rs:2494",
"rustc_span", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_span/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2494u32),
::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);
2495 if !(chpos >= linechpos) {
::core::panicking::panic("assertion failed: chpos >= linechpos")
};assert!(chpos >= linechpos);
2496 (line, col)
2497 }
2498 None => (0, chpos),
2499 }
2500 }
2501
2502 pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) {
2505 let pos = self.relative_position(pos);
2506 let (line, col_or_chpos) = self.lookup_file_pos(pos);
2507 if line > 0 {
2508 let Some(code) = self.get_line(line - 1) else {
2509 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_span/src/lib.rs:2516",
"rustc_span", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_span/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(2516u32),
::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);
2517 return (line, col_or_chpos, col_or_chpos.0);
2518 };
2519 let display_col = code.chars().take(col_or_chpos.0).map(|ch| char_width(ch)).sum();
2520 (line, col_or_chpos, display_col)
2521 } else {
2522 (0, col_or_chpos, col_or_chpos.0)
2524 }
2525 }
2526}
2527
2528pub fn char_width(ch: char) -> usize {
2529 match ch {
2532 '\t' => 4,
2533 '\u{0000}' | '\u{0001}' | '\u{0002}' | '\u{0003}' | '\u{0004}' | '\u{0005}'
2537 | '\u{0006}' | '\u{0007}' | '\u{0008}' | '\u{000B}' | '\u{000C}' | '\u{000D}'
2538 | '\u{000E}' | '\u{000F}' | '\u{0010}' | '\u{0011}' | '\u{0012}' | '\u{0013}'
2539 | '\u{0014}' | '\u{0015}' | '\u{0016}' | '\u{0017}' | '\u{0018}' | '\u{0019}'
2540 | '\u{001A}' | '\u{001B}' | '\u{001C}' | '\u{001D}' | '\u{001E}' | '\u{001F}'
2541 | '\u{007F}' | '\u{202A}' | '\u{202B}' | '\u{202D}' | '\u{202E}' | '\u{2066}'
2542 | '\u{2067}' | '\u{2068}' | '\u{202C}' | '\u{2069}' => 1,
2543 _ => unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1),
2544 }
2545}
2546
2547pub fn str_width(s: &str) -> usize {
2548 s.chars().map(char_width).sum()
2549}
2550
2551fn normalize_src(src: &mut String) -> Vec<NormalizedPos> {
2553 let mut normalized_pos = ::alloc::vec::Vec::new()vec![];
2554 remove_bom(src, &mut normalized_pos);
2555 normalize_newlines(src, &mut normalized_pos);
2556 normalized_pos
2557}
2558
2559fn remove_bom(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
2561 if src.starts_with('\u{feff}') {
2562 src.drain(..3);
2563 normalized_pos.push(NormalizedPos { pos: RelativeBytePos(0), diff: 3 });
2564 }
2565}
2566
2567fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec<NormalizedPos>) {
2571 if !src.as_bytes().contains(&b'\r') {
2572 return;
2573 }
2574
2575 let mut buf = std::mem::take(src).into_bytes();
2581 let mut gap_len = 0;
2582 let mut tail = buf.as_mut_slice();
2583 let mut cursor = 0;
2584 let original_gap = normalized_pos.last().map_or(0, |l| l.diff);
2585 loop {
2586 let idx = match find_crlf(&tail[gap_len..]) {
2587 None => tail.len(),
2588 Some(idx) => idx + gap_len,
2589 };
2590 tail.copy_within(gap_len..idx, 0);
2591 tail = &mut tail[idx - gap_len..];
2592 if tail.len() == gap_len {
2593 break;
2594 }
2595 cursor += idx - gap_len;
2596 gap_len += 1;
2597 normalized_pos.push(NormalizedPos {
2598 pos: RelativeBytePos::from_usize(cursor + 1),
2599 diff: original_gap + gap_len as u32,
2600 });
2601 }
2602
2603 let new_len = buf.len() - gap_len;
2606 unsafe {
2607 buf.set_len(new_len);
2608 *src = String::from_utf8_unchecked(buf);
2609 }
2610
2611 fn find_crlf(src: &[u8]) -> Option<usize> {
2612 let mut search_idx = 0;
2613 while let Some(idx) = find_cr(&src[search_idx..]) {
2614 if src[search_idx..].get(idx + 1) != Some(&b'\n') {
2615 search_idx += idx + 1;
2616 continue;
2617 }
2618 return Some(search_idx + idx);
2619 }
2620 None
2621 }
2622
2623 fn find_cr(src: &[u8]) -> Option<usize> {
2624 src.iter().position(|&b| b == b'\r')
2625 }
2626}
2627
2628pub trait Pos {
2633 fn from_usize(n: usize) -> Self;
2634 fn to_usize(&self) -> usize;
2635 fn from_u32(n: u32) -> Self;
2636 fn to_u32(&self) -> u32;
2637}
2638
2639macro_rules! impl_pos {
2640 (
2641 $(
2642 $(#[$attr:meta])*
2643 $vis:vis struct $ident:ident($inner_vis:vis $inner_ty:ty);
2644 )*
2645 ) => {
2646 $(
2647 $(#[$attr])*
2648 $vis struct $ident($inner_vis $inner_ty);
2649
2650 impl Pos for $ident {
2651 #[inline(always)]
2652 fn from_usize(n: usize) -> $ident {
2653 $ident(n as $inner_ty)
2654 }
2655
2656 #[inline(always)]
2657 fn to_usize(&self) -> usize {
2658 self.0 as usize
2659 }
2660
2661 #[inline(always)]
2662 fn from_u32(n: u32) -> $ident {
2663 $ident(n as $inner_ty)
2664 }
2665
2666 #[inline(always)]
2667 fn to_u32(&self) -> u32 {
2668 self.0 as u32
2669 }
2670 }
2671
2672 impl Add for $ident {
2673 type Output = $ident;
2674
2675 #[inline(always)]
2676 fn add(self, rhs: $ident) -> $ident {
2677 $ident(self.0 + rhs.0)
2678 }
2679 }
2680
2681 impl Sub for $ident {
2682 type Output = $ident;
2683
2684 #[inline(always)]
2685 fn sub(self, rhs: $ident) -> $ident {
2686 $ident(self.0 - rhs.0)
2687 }
2688 }
2689 )*
2690 };
2691}
2692
2693#[doc = r" A character offset."]
#[doc = r""]
#[doc = r" Because of multibyte UTF-8 characters, a byte offset"]
#[doc =
r" is not equivalent to a character offset. The [`SourceMap`] will convert [`BytePos`]"]
#[doc = r" values to `CharPos` values as necessary."]
pub struct CharPos(pub usize);
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for CharPos { }
#[automatically_derived]
impl ::core::clone::Clone for CharPos {
#[inline]
fn clone(&self) -> CharPos {
let _: ::core::clone::AssertParamIsClone<usize>;
*self
}
}
#[automatically_derived]
impl ::core::marker::Copy for CharPos { }
#[automatically_derived]
impl ::core::marker::StructuralPartialEq for CharPos { }
#[automatically_derived]
impl ::core::cmp::PartialEq for CharPos {
#[inline]
fn eq(&self, other: &CharPos) -> bool { self.0 == other.0 }
}
#[automatically_derived]
impl ::core::cmp::Eq for CharPos {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<usize>;
}
}
#[automatically_derived]
impl ::core::cmp::PartialOrd for CharPos {
#[inline]
fn partial_cmp(&self, other: &CharPos)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}
#[automatically_derived]
impl ::core::cmp::Ord for CharPos {
#[inline]
fn cmp(&self, other: &CharPos) -> ::core::cmp::Ordering {
::core::cmp::Ord::cmp(&self.0, &other.0)
}
}
#[automatically_derived]
impl ::core::fmt::Debug for CharPos {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f, "CharPos",
&&self.0)
}
}
impl Pos for CharPos {
#[inline(always)]
fn from_usize(n: usize) -> CharPos { CharPos(n as usize) }
#[inline(always)]
fn to_usize(&self) -> usize { self.0 as usize }
#[inline(always)]
fn from_u32(n: u32) -> CharPos { CharPos(n as usize) }
#[inline(always)]
fn to_u32(&self) -> u32 { self.0 as u32 }
}
impl Add for CharPos {
type Output = CharPos;
#[inline(always)]
fn add(self, rhs: CharPos) -> CharPos { CharPos(self.0 + rhs.0) }
}
impl Sub for CharPos {
type Output = CharPos;
#[inline(always)]
fn sub(self, rhs: CharPos) -> CharPos { CharPos(self.0 - rhs.0) }
}impl_pos! {
2694 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
2698 pub struct BytePos(pub u32);
2699
2700 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, StableHash)]
2702 pub struct RelativeBytePos(pub u32);
2703
2704 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
2710 pub struct CharPos(pub usize);
2711}
2712
2713impl<S: Encoder> Encodable<S> for BytePos {
2714 fn encode(&self, s: &mut S) {
2715 s.emit_u32(self.0);
2716 }
2717}
2718
2719impl<D: Decoder> Decodable<D> for BytePos {
2720 fn decode(d: &mut D) -> BytePos {
2721 BytePos(d.read_u32())
2722 }
2723}
2724
2725impl<S: Encoder> Encodable<S> for RelativeBytePos {
2726 fn encode(&self, s: &mut S) {
2727 s.emit_u32(self.0);
2728 }
2729}
2730
2731impl<D: Decoder> Decodable<D> for RelativeBytePos {
2732 fn decode(d: &mut D) -> RelativeBytePos {
2733 RelativeBytePos(d.read_u32())
2734 }
2735}
2736
2737#[derive(#[automatically_derived]
impl ::core::fmt::Debug for Loc {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f, "Loc", "file",
&self.file, "line", &self.line, "col", &self.col, "col_display",
&&self.col_display)
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for Loc {
#[inline]
fn clone(&self) -> Loc {
Loc {
file: ::core::clone::Clone::clone(&self.file),
line: ::core::clone::Clone::clone(&self.line),
col: ::core::clone::Clone::clone(&self.col),
col_display: ::core::clone::Clone::clone(&self.col_display),
}
}
}Clone)]
2743pub struct Loc {
2744 pub file: Arc<SourceFile>,
2746 pub line: usize,
2748 pub col: CharPos,
2750 pub col_display: usize,
2752}
2753
2754#[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)]
2756pub struct SourceFileAndLine {
2757 pub sf: Arc<SourceFile>,
2758 pub line: usize,
2760}
2761#[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)]
2762pub struct SourceFileAndBytePos {
2763 pub sf: Arc<SourceFile>,
2764 pub pos: BytePos,
2765}
2766
2767#[derive(#[automatically_derived]
impl ::core::marker::Copy for LineInfo { }Copy, #[automatically_derived]
impl ::core::clone::Clone for LineInfo {
#[inline]
fn clone(&self) -> LineInfo {
let _: ::core::clone::AssertParamIsClone<usize>;
let _: ::core::clone::AssertParamIsClone<CharPos>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for LineInfo {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f, "LineInfo",
"line_index", &self.line_index, "start_col", &self.start_col,
"end_col", &&self.end_col)
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for LineInfo {
#[inline]
fn eq(&self, other: &LineInfo) -> bool {
self.line_index == other.line_index &&
self.start_col == other.start_col &&
self.end_col == other.end_col
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for LineInfo {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<usize>;
let _: ::core::cmp::AssertParamIsEq<CharPos>;
}
}Eq)]
2768pub struct LineInfo {
2769 pub line_index: usize,
2771
2772 pub start_col: CharPos,
2774
2775 pub end_col: CharPos,
2777}
2778
2779pub struct FileLines {
2780 pub file: Arc<SourceFile>,
2781 pub lines: Vec<LineInfo>,
2782}
2783
2784pub static SPAN_TRACK: AtomicRef<fn(LocalDefId)> = AtomicRef::new(&((|_| {}) as fn(_)));
2785
2786pub type FileLinesResult = Result<FileLines, SpanLinesError>;
2791
2792#[derive(#[automatically_derived]
impl ::core::clone::Clone for SpanLinesError {
#[inline]
fn clone(&self) -> SpanLinesError {
match self {
SpanLinesError::DistinctSources(__self_0) =>
SpanLinesError::DistinctSources(::core::clone::Clone::clone(__self_0)),
}
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for SpanLinesError {
#[inline]
fn eq(&self, other: &SpanLinesError) -> bool {
match (self, other) {
(SpanLinesError::DistinctSources(__self_0),
SpanLinesError::DistinctSources(__arg1_0)) =>
__self_0 == __arg1_0,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for SpanLinesError {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Box<DistinctSources>>;
}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for SpanLinesError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
SpanLinesError::DistinctSources(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"DistinctSources", &__self_0),
}
}
}Debug)]
2793pub enum SpanLinesError {
2794 DistinctSources(Box<DistinctSources>),
2795}
2796
2797#[derive(#[automatically_derived]
impl ::core::clone::Clone for SpanSnippetError {
#[inline]
fn clone(&self) -> SpanSnippetError {
match self {
SpanSnippetError::IllFormedSpan(__self_0) =>
SpanSnippetError::IllFormedSpan(::core::clone::Clone::clone(__self_0)),
SpanSnippetError::DistinctSources(__self_0) =>
SpanSnippetError::DistinctSources(::core::clone::Clone::clone(__self_0)),
SpanSnippetError::MalformedForSourcemap(__self_0) =>
SpanSnippetError::MalformedForSourcemap(::core::clone::Clone::clone(__self_0)),
SpanSnippetError::SourceNotAvailable { filename: __self_0 } =>
SpanSnippetError::SourceNotAvailable {
filename: ::core::clone::Clone::clone(__self_0),
},
}
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for SpanSnippetError {
#[inline]
fn eq(&self, other: &SpanSnippetError) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(SpanSnippetError::IllFormedSpan(__self_0),
SpanSnippetError::IllFormedSpan(__arg1_0)) =>
__self_0 == __arg1_0,
(SpanSnippetError::DistinctSources(__self_0),
SpanSnippetError::DistinctSources(__arg1_0)) =>
__self_0 == __arg1_0,
(SpanSnippetError::MalformedForSourcemap(__self_0),
SpanSnippetError::MalformedForSourcemap(__arg1_0)) =>
__self_0 == __arg1_0,
(SpanSnippetError::SourceNotAvailable { filename: __self_0 },
SpanSnippetError::SourceNotAvailable { filename: __arg1_0 })
=> __self_0 == __arg1_0,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for SpanSnippetError {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<Span>;
let _: ::core::cmp::AssertParamIsEq<Box<DistinctSources>>;
let _: ::core::cmp::AssertParamIsEq<MalformedSourceMapPositions>;
let _: ::core::cmp::AssertParamIsEq<FileName>;
}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for SpanSnippetError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
SpanSnippetError::IllFormedSpan(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"IllFormedSpan", &__self_0),
SpanSnippetError::DistinctSources(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"DistinctSources", &__self_0),
SpanSnippetError::MalformedForSourcemap(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"MalformedForSourcemap", &__self_0),
SpanSnippetError::SourceNotAvailable { filename: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f,
"SourceNotAvailable", "filename", &__self_0),
}
}
}Debug)]
2798pub enum SpanSnippetError {
2799 IllFormedSpan(Span),
2800 DistinctSources(Box<DistinctSources>),
2801 MalformedForSourcemap(MalformedSourceMapPositions),
2802 SourceNotAvailable { filename: FileName },
2803}
2804
2805#[derive(#[automatically_derived]
impl ::core::clone::Clone for DistinctSources {
#[inline]
fn clone(&self) -> DistinctSources {
DistinctSources {
begin: ::core::clone::Clone::clone(&self.begin),
end: ::core::clone::Clone::clone(&self.end),
}
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for DistinctSources {
#[inline]
fn eq(&self, other: &DistinctSources) -> bool {
self.begin == other.begin && self.end == other.end
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for DistinctSources {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<(FileName, BytePos)>;
let _: ::core::cmp::AssertParamIsEq<(FileName, BytePos)>;
}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for DistinctSources {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"DistinctSources", "begin", &self.begin, "end", &&self.end)
}
}Debug)]
2806pub struct DistinctSources {
2807 pub begin: (FileName, BytePos),
2808 pub end: (FileName, BytePos),
2809}
2810
2811#[derive(#[automatically_derived]
impl ::core::clone::Clone for MalformedSourceMapPositions {
#[inline]
fn clone(&self) -> MalformedSourceMapPositions {
MalformedSourceMapPositions {
name: ::core::clone::Clone::clone(&self.name),
source_len: ::core::clone::Clone::clone(&self.source_len),
begin_pos: ::core::clone::Clone::clone(&self.begin_pos),
end_pos: ::core::clone::Clone::clone(&self.end_pos),
}
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for MalformedSourceMapPositions {
#[inline]
fn eq(&self, other: &MalformedSourceMapPositions) -> bool {
self.name == other.name && self.source_len == other.source_len &&
self.begin_pos == other.begin_pos &&
self.end_pos == other.end_pos
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for MalformedSourceMapPositions {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<FileName>;
let _: ::core::cmp::AssertParamIsEq<usize>;
let _: ::core::cmp::AssertParamIsEq<BytePos>;
}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for MalformedSourceMapPositions {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f,
"MalformedSourceMapPositions", "name", &self.name, "source_len",
&self.source_len, "begin_pos", &self.begin_pos, "end_pos",
&&self.end_pos)
}
}Debug)]
2812pub struct MalformedSourceMapPositions {
2813 pub name: FileName,
2814 pub source_len: usize,
2815 pub begin_pos: BytePos,
2816 pub end_pos: BytePos,
2817}
2818
2819#[derive(#[automatically_derived]
impl ::core::marker::Copy for InnerSpan { }Copy, #[automatically_derived]
impl ::core::clone::Clone for InnerSpan {
#[inline]
fn clone(&self) -> InnerSpan {
let _: ::core::clone::AssertParamIsClone<usize>;
*self
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for InnerSpan {
#[inline]
fn eq(&self, other: &InnerSpan) -> bool {
self.start == other.start && self.end == other.end
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for InnerSpan {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<usize>;
}
}Eq, #[automatically_derived]
impl ::core::fmt::Debug for InnerSpan {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "InnerSpan",
"start", &self.start, "end", &&self.end)
}
}Debug)]
2821pub struct InnerSpan {
2822 pub start: usize,
2823 pub end: usize,
2824}
2825
2826impl InnerSpan {
2827 pub fn new(start: usize, end: usize) -> InnerSpan {
2828 InnerSpan { start, end }
2829 }
2830}
2831
2832impl StableHash for Span {
2833 fn stable_hash<Hcx: StableHashCtxt>(&self, hcx: &mut Hcx, hasher: &mut StableHasher) {
2834 hcx.stable_hash_span(self.to_raw_span(), hasher)
2836 }
2837}
2838
2839#[derive(#[automatically_derived]
impl ::core::clone::Clone for ErrorGuaranteed {
#[inline]
fn clone(&self) -> ErrorGuaranteed {
let _: ::core::clone::AssertParamIsClone<()>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for ErrorGuaranteed { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for ErrorGuaranteed {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ErrorGuaranteed", &&self.0)
}
}Debug, #[automatically_derived]
impl ::core::hash::Hash for ErrorGuaranteed {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}Hash, #[automatically_derived]
impl ::core::cmp::PartialEq for ErrorGuaranteed {
#[inline]
fn eq(&self, other: &ErrorGuaranteed) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ErrorGuaranteed {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<()>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for ErrorGuaranteed {
#[inline]
fn partial_cmp(&self, other: &ErrorGuaranteed)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
}
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for ErrorGuaranteed {
#[inline]
fn cmp(&self, other: &ErrorGuaranteed) -> ::core::cmp::Ordering {
::core::cmp::Ord::cmp(&self.0, &other.0)
}
}Ord)]
2845#[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)]
2846pub struct ErrorGuaranteed(());
2847
2848impl ErrorGuaranteed {
2849 #[deprecated = "should only be used in `DiagCtxtInner::emit_diagnostic`"]
2851 pub fn unchecked_error_guaranteed() -> Self {
2852 ErrorGuaranteed(())
2853 }
2854
2855 pub fn raise_fatal(self) -> ! {
2856 FatalError.raise()
2857 }
2858}
2859
2860impl<E: rustc_serialize::Encoder> Encodable<E> for ErrorGuaranteed {
2861 #[inline]
2862 fn encode(&self, _e: &mut E) {
2863 {
::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!(
2864 "should never serialize an `ErrorGuaranteed`, as we do not write metadata or \
2865 incremental caches in case errors occurred"
2866 )
2867 }
2868}
2869impl<D: rustc_serialize::Decoder> Decodable<D> for ErrorGuaranteed {
2870 #[inline]
2871 fn decode(_d: &mut D) -> ErrorGuaranteed {
2872 {
::core::panicking::panic_fmt(format_args!("`ErrorGuaranteed` should never have been serialized to metadata or incremental caches"));
}panic!(
2873 "`ErrorGuaranteed` should never have been serialized to metadata or incremental caches"
2874 )
2875 }
2876}