1use std::cmp::Ordering;
2use std::hash::Hash;
34use rustc_data_structures::fx::FxIndexSet;
5use rustc_data_structures::stable_hash::RawSpan;
6// This code is very hot and uses lots of arithmetic, avoid overflow checks for performance.
7// See https://github.com/rust-lang/rust/pull/119440#issuecomment-1874255727
8use rustc_serialize::int_overflow::DebugStrictAdd;
910use crate::def_id::{DefIndex, LocalDefId};
11use crate::hygiene::SyntaxContext;
12use crate::{BytePos, SPAN_TRACK, SpanData};
1314/// A compressed span.
15///
16/// [`SpanData`] is 16 bytes, which is too big to stick everywhere. `Span` is
17/// only 8 bytes. A large majority of `SpanData` instances can be made to fit
18/// within those 8 bytes. Any `SpanData` whose fields don't fit into a `Span`
19/// are stored in a separate interner table, and the `Span` will index into
20/// that table.
21///
22/// An earlier version of this code used only 4 bytes for `Span`, but that was
23/// slower because many fewer spans could be stored inline and the interner was
24/// used a lot more. That version of the code also predated the storage of
25/// parents.
26///
27/// Experiments with uncompressed spans yielded worse performance in most cases
28/// because memory usage and cache miss rates are significantly higher without
29/// compression.
30///
31/// There are four different span formats and each packs data into the 8 bytes
32/// in a different way. A variable-length prefix in the high bits identifies
33/// which format is being used. It is an invariant that we always use the first
34/// listed format whose requirements are satisfied. `len` is `hi - lo`.
35///
36/// - Inline-context format (requires 15-bit length, 16-bit context, and no parent):
37///
38/// `[ prefix=0 | len:15 | ctxt:16 | lo:32 ]`
39///
40/// - Inline-parent format (requires 14-bit length, root context, and 15-bit parent):
41///
42/// `[ prefix=110 | len:14 | parent:15 | lo:32 ]`
43///
44/// - Inline-pair format (requires 24-bit lo, 7-bit length, 15-bit context, 16-bit parent):
45///
46/// `[ prefix=10 | len:7 | ctxt:15 | parent:16 | lo:24 ]`
47///
48/// - Interned format (all cases not covered above):
49///
50/// `[ prefix=111 | ctxt:29 | index:32 ]`
51///
52/// Notes about this design.
53///
54/// - This configuration was the best one found after many measurements of
55/// real-world crates, and replaced an earlier 8-byte design.
56///
57/// - The size of `lo` depends on the size of the crate and its dependencies.
58/// Crates whose `lo` size exceeds 24-bits are extremely rare.
59///
60/// - The most common numbers of bits needed for `len` are from 0 to 7,
61/// with a peak usually at 3 or 4, and then it drops off quickly from 8
62/// onwards. Lengths larger than 14 bits are rare, but many crates will have
63/// a small number of such lengths (sometimes 20+ bits).
64///
65/// - The number of bits needed for `ctxt` and `parent` values depend partly on
66/// the crate size and partly on the form of the code. For both fields,
67/// values needing more than 15 bits are very rare, and most crates won't hit
68/// these limits.
69///
70/// - The ctxt is stored inline in every format (Every ctxt must fit in
71/// 29 bits; if we ever hit that we'd have many gigabytes of contexts, and
72/// certainly would have OOM'd anyway.) This means reading the ctxt never
73/// requires checking the interner. This is good because the ctxt is often
74/// consulted by itself. It also means we don't need to store the ctxt in the
75/// interner table, which we achieve by using `SpanDataNoCtxt`, which
76/// minimizes the number of unique values that need to be interned.
77///
78/// - The interned format is typically used for < 1% of all spans in
79/// incremental builds and < 0.1% of all spans in non-incremental builds.
80/// The difference is because only incremental builds use the parent field.
81///
82/// - The use of `repr(packed(4))` means `Span` has an alignment of 4 bytes,
83/// which keeps many types that contain spans (e.g. AST nodes) smaller.
84/// `repr(packed(1))` isn't worth it; it only shrinks a few types and
85/// performance is a tiny bit worse.
86///
87/// In order to reliably use parented spans in incremental compilation,
88/// accesses to `lo` and `hi` must introduce a dependency to the parent definition's span.
89/// This is performed using the callback `SPAN_TRACK` to access the query engine.
90#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for Span {
}
#[automatically_derived]impl ::core::clone::Clone for Span {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<u64>;
*self
}
}Clone, #[automatically_derived]impl ::core::marker::Copy for Span { }Copy, #[automatically_derived]impl ::core::cmp::Eq for Span {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<u64>;
}
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for Span { }
#[automatically_derived]impl ::core::cmp::PartialEq for Span {
#[inline]
fn eq(&self, other: &Self) -> bool { ({ self.0 }) == ({ other.0 }) }
}PartialEq, #[automatically_derived]impl ::core::hash::Hash for Span {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&{ self.0 }, state)
}
}Hash)]
91#[cfg_attr(bootstrap, rustc_pass_by_value)]
92#[cfg_attr(not(bootstrap), lint::pass_by_value)]
93#[repr(packed(4))]
94pub struct Span(u64);
9596// `SyntaxContext` (`SpanData::ctxt`) and `LocalDefId` (within `SpanData::parent`) aren't orderable.
97// If you want to order spans just on `lo`/`hi`, use explicit comparisons involving `Span::lo_hi`.
98// Or you can wrap your span within `OrdSpan` which impls `PartialOrd`/`Ord` via `Span::lo_hi`.
99impl !PartialOrdfor Span {}
100impl !Ordfor Span {}
101102/// Specifies a field within one of the span formats. Provides const operations that (a) let a span
103/// format be fully specified, and (b) check/read/write the field for/from/to a span.
104#[derive(#[automatically_derived]impl ::core::marker::Copy for SpanField { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for SpanField {
}
#[automatically_derived]impl ::core::clone::Clone for SpanField {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<u32>;
*self
}
}Clone)]
105struct SpanField {
106/// The field's bit position, where zero means it's in the lowest bits.
107shift: u32,
108/// The field's width, in bits.
109width: u32,
110}
111112impl SpanField {
113/// Specifies the top field, i.e. the highest bits. Chained with `below`.
114#[inline]
115const fn top(width: u32) -> Self {
116SpanField { shift: 64 - width, width }
117 }
118119/// Specifies a field that comes below the field in `self`. Chainable.
120#[inline]
121const fn below(self, width: u32) -> Self {
122SpanField { shift: self.shift - width, width }
123 }
124125/// The mask for the (downshifted to 0..n) field.
126#[inline]
127const fn mask(self) -> u64 {
128 (1 << self.width) - 1
129}
130131/// Gets the field from a span-as-`u64` as a `u32`.
132#[inline]
133const fn get(self, u: u64) -> u32 {
134 ((u >> self.shift) & self.mask()) as u32135 }
136137/// Sets the field to `v` in an otherwise-zero span-as-`u64`.
138#[inline]
139const fn set(self, v: u32) -> u64 {
140if true {
if !(v <= self.mask() as u32) {
::core::panicking::panic("assertion failed: v <= self.mask() as u32")
};
};debug_assert!(v <= self.mask() as u32);
141 (vas u64) << self.shift
142 }
143144/// Returns non-zero if `v` is too big to fit in the field.
145#[inline]
146const fn too_big(self, v: u32) -> u32 {
147v & !(self.mask() as u32)
148 }
149150/// Asserts that a field uses the bottom-most bits.
151#[inline]
152const fn assert_is_bottom(self) {
153if !(self.shift == 0) {
::core::panicking::panic("assertion failed: self.shift == 0")
};assert!(self.shift == 0);
154 }
155}
156157// Convenience structures for all span formats.
158// InlineCtxt is public to allow inline-only fast paths.
159#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for InlineCtxt {
}
#[automatically_derived]impl ::core::clone::Clone for InlineCtxt {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<u32>;
*self
}
}Clone, #[automatically_derived]impl ::core::marker::Copy for InlineCtxt { }Copy)]
160pub(crate) struct InlineCtxt {
161pub(crate) lo: u32,
162pub(crate) len: u32,
163pub(crate) ctxt: u32,
164}
165166#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for InlineParent {
}
#[automatically_derived]impl ::core::clone::Clone for InlineParent {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<u32>;
*self
}
}Clone, #[automatically_derived]impl ::core::marker::Copy for InlineParent { }Copy)]
167struct InlineParent {
168 lo: u32,
169 len: u32,
170 parent: u32,
171}
172173#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for InlinePair {
}
#[automatically_derived]impl ::core::clone::Clone for InlinePair {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<u32>;
*self
}
}Clone, #[automatically_derived]impl ::core::marker::Copy for InlinePair { }Copy)]
174struct InlinePair {
175 lo: u32,
176 len: u32,
177 ctxt: u32,
178 parent: u32,
179}
180181#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for Interned {
}
#[automatically_derived]impl ::core::clone::Clone for Interned {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<u32>;
*self
}
}Clone, #[automatically_derived]impl ::core::marker::Copy for Interned { }Copy)]
182struct Interned {
183 ctxt: u32,
184 index: u32,
185}
186187impl InlineCtxt {
188const PREFIX_VALUE: u32 = 0b0;
189const PREFIX: SpanField = SpanField::top(1);
190const LEN: SpanField = Self::PREFIX.below(15);
191const CTXT: SpanField = Self::LEN.below(16);
192const LO: SpanField = Self::CTXT.below(32);
193194#[inline]
195pub(crate) const fn try_new_span(lo: u32, len: u32, ctxt: u32) -> Option<Span> {
196if Self::LEN.too_big(len) | Self::CTXT.too_big(ctxt) == 0 {
197Some(Span(
198Self::PREFIX.set(Self::PREFIX_VALUE)
199 | Self::LEN.set(len)
200 | Self::CTXT.set(ctxt)
201 | Self::LO.set(lo),
202 ))
203 } else {
204None205 }
206 }
207208#[inline]
209fn data(self) -> SpanData {
210SpanData {
211 lo: BytePos(self.lo),
212 hi: BytePos(self.lo.debug_strict_add(self.len)),
213 ctxt: SyntaxContext::from_u32(self.ctxt),
214 parent: None,
215 }
216 }
217218#[inline]
219fn from_span(span: Span) -> InlineCtxt {
220let u = span.0;
221Self { lo: Self::LO.get(u), len: Self::LEN.get(u), ctxt: Self::CTXT.get(u) }
222 }
223224#[inline]
225pub(crate) fn try_from_span(span: Span) -> Option<InlineCtxt> {
226if Self::PREFIX.get(span.0) == Self::PREFIX_VALUE {
227Some(Self::from_span(span))
228 } else {
229None230 }
231 }
232}
233const _: () = InlineCtxt::LO.assert_is_bottom();
234235impl InlineParent {
236const PREFIX_VALUE: u32 = 0b110;
237const PREFIX: SpanField = SpanField::top(3);
238const LEN: SpanField = Self::PREFIX.below(14);
239const PARENT: SpanField = Self::LEN.below(15);
240const LO: SpanField = Self::PARENT.below(32);
241242#[inline]
243fn try_new_span(lo: u32, len: u32, ctxt: u32, parent: u32) -> Option<Span> {
244if Self::LEN.too_big(len) | ctxt | Self::PARENT.too_big(parent) == 0 {
245Some(Span(
246Self::PREFIX.set(Self::PREFIX_VALUE)
247 | Self::LEN.set(len)
248 | Self::PARENT.set(parent)
249 | Self::LO.set(lo),
250 ))
251 } else {
252None253 }
254 }
255256#[inline]
257fn data(self) -> SpanData {
258SpanData {
259 lo: BytePos(self.lo),
260 hi: BytePos(self.lo.debug_strict_add(self.len)),
261 ctxt: SyntaxContext::root(),
262 parent: Some(LocalDefId { local_def_index: DefIndex::from_u32(self.parent) }),
263 }
264 }
265266#[inline]
267fn from_span(span: Span) -> InlineParent {
268let u = span.0;
269Self { lo: Self::LO.get(u), len: Self::LEN.get(u), parent: Self::PARENT.get(u) }
270 }
271}
272const _: () = InlineParent::LO.assert_is_bottom();
273274impl InlinePair {
275const PREFIX_VALUE: u32 = 0b10;
276const PREFIX: SpanField = SpanField::top(2);
277const LEN: SpanField = Self::PREFIX.below(7);
278const CTXT: SpanField = Self::LEN.below(15);
279const PARENT: SpanField = Self::CTXT.below(16);
280const LO: SpanField = Self::PARENT.below(24);
281282#[inline]
283fn try_new_span(lo: u32, len: u32, ctxt: u32, parent: u32) -> Option<Span> {
284if Self::LO.too_big(lo)
285 | Self::LEN.too_big(len)
286 | Self::CTXT.too_big(ctxt)
287 | Self::PARENT.too_big(parent)
288 == 0
289{
290Some(Span(
291Self::PREFIX.set(Self::PREFIX_VALUE)
292 | Self::LEN.set(len)
293 | Self::CTXT.set(ctxt)
294 | Self::PARENT.set(parent)
295 | Self::LO.set(lo),
296 ))
297 } else {
298None299 }
300 }
301302#[inline]
303fn data(self) -> SpanData {
304SpanData {
305 lo: BytePos(self.lo),
306 hi: BytePos(self.lo.debug_strict_add(self.len)),
307 ctxt: SyntaxContext::from_u32(self.ctxt),
308 parent: Some(LocalDefId { local_def_index: DefIndex::from_u32(self.parent) }),
309 }
310 }
311312#[inline]
313fn from_span(span: Span) -> InlinePair {
314let u = span.0;
315Self {
316 lo: Self::LO.get(u),
317 len: Self::LEN.get(u),
318 ctxt: Self::CTXT.get(u),
319 parent: Self::PARENT.get(u),
320 }
321 }
322}
323const _: () = InlinePair::LO.assert_is_bottom();
324325impl Interned {
326const PREFIX_VALUE: u32 = 0b111;
327const PREFIX: SpanField = SpanField::top(3);
328const CTXT: SpanField = Self::PREFIX.below(29);
329const INDEX: SpanField = Self::CTXT.below(32);
330331#[inline]
332fn new_span(ctxt: u32, index: u32) -> Span {
333Span(Self::PREFIX.set(Self::PREFIX_VALUE) | Self::CTXT.set(ctxt) | Self::INDEX.set(index))
334 }
335336#[inline]
337fn data(self) -> SpanData {
338#[cold]
339 #[inline(never)]
340fn interned(index: u32) -> SpanDataNoCtxt {
341with_span_interner(|interner| interner.spans[indexas usize])
342 }
343344let SpanDataNoCtxt { lo, hi, parent } = interned(self.index);
345SpanData { lo, hi, ctxt: SyntaxContext::from_u32(self.ctxt), parent }
346 }
347348#[inline]
349fn from_span(span: Span) -> Interned {
350let u = span.0;
351Self { ctxt: Self::CTXT.get(u), index: Self::INDEX.get(u) }
352 }
353}
354const _: () = Interned::INDEX.assert_is_bottom();
355356/// Values of this type should never actually be materialized, because they are just temporaries
357/// and `Span::kind` is inlined.
358enum SpanKind {
359 InlineCtxt(InlineCtxt),
360 InlineParent(InlineParent),
361 InlinePair(InlinePair),
362 Interned(Interned),
363}
364365/// The dummy span has zero position, length, and context, and no parent.
366pub const DUMMY_SP: Span = InlineCtxt::try_new_span(0, 0, 0).unwrap();
367368impl Span {
369/// Create a new `Span`, handling the invalid case where `lo > hi` by swapping.
370 ///
371 /// If possible, ensure that `lo <= hi`, and call `Span::new_ordered` instead.
372#[inline]
373pub fn new(
374mut lo: BytePos,
375mut hi: BytePos,
376 ctxt: SyntaxContext,
377 parent: Option<LocalDefId>,
378 ) -> Self {
379if lo > hi {
380 std::mem::swap(&mut lo, &mut hi);
381 }
382Span::new_ordered(lo, hi, ctxt, parent)
383 }
384385/// Create a new `Span`.
386 ///
387 /// This requires that `lo <= hi`.
388#[inline]
389pub fn new_ordered(
390 lo: BytePos,
391 hi: BytePos,
392 ctxt: SyntaxContext,
393 parent: Option<LocalDefId>,
394 ) -> Self {
395#[cold]
396 #[inline(never)]
397fn interned(lo: BytePos, hi: BytePos, ctxt: u32, parent: Option<LocalDefId>) -> Span {
398// Interned.
399{
match (&Interned::CTXT.too_big(ctxt), &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!(Interned::CTXT.too_big(ctxt), 0); // this is a hard limit, with no fallback
400let index =
401with_span_interner(|interner| interner.intern(&SpanDataNoCtxt { lo, hi, parent }));
402Interned::new_span(ctxt, index)
403 }
404405if true {
if !(lo <= hi) { ::core::panicking::panic("assertion failed: lo <= hi") };
};debug_assert!(lo <= hi);
406407let lo32 = lo.0;
408let (len, ctxt32) = (hi.0 - lo32, ctxt.as_u32());
409if let Some(parent) = parent {
410if let Some(span) = Span::try_new_span_with_parent(lo32, len, ctxt32, parent) {
411// InlineParent or InlinePair.
412return span;
413 }
414 } else if let Some(span) = InlineCtxt::try_new_span(lo32, len, ctxt32) {
415// InlineCtxt.
416return span;
417 }
418419interned(lo, hi, ctxt32, parent)
420 }
421422/// Tries to create an `InlineParent` or `InlinePair` format span. Returns `None` if the fields
423 /// won't fit.
424#[inline]
425fn try_new_span_with_parent(lo: u32, len: u32, ctxt: u32, parent: LocalDefId) -> Option<Self> {
426let parent = parent.local_def_index.as_u32();
427InlineParent::try_new_span(lo, len, ctxt, parent)
428 .or_else(|| InlinePair::try_new_span(lo, len, ctxt, parent))
429 }
430431#[inline]
432fn kind(self) -> SpanKind {
433let span64 = self.0;
434if InlineCtxt::PREFIX.get(span64) == InlineCtxt::PREFIX_VALUE {
435 SpanKind::InlineCtxt(InlineCtxt::from_span(self))
436 } else if InlineParent::PREFIX.get(span64) == InlineParent::PREFIX_VALUE {
437 SpanKind::InlineParent(InlineParent::from_span(self))
438 } else if InlinePair::PREFIX.get(span64) == InlinePair::PREFIX_VALUE {
439 SpanKind::InlinePair(InlinePair::from_span(self))
440 } else {
441 SpanKind::Interned(Interned::from_span(self))
442 }
443 }
444445#[inline]
446pub fn data(self) -> SpanData {
447let data = self.data_untracked();
448if let Some(parent) = data.parent {
449 (*SPAN_TRACK)(parent);
450 }
451data452 }
453454/// Internal function to translate between an encoded span and the expanded representation.
455 /// This function must not be used outside the incremental engine.
456#[inline]
457pub fn data_untracked(self) -> SpanData {
458match self.kind() {
459 SpanKind::InlineCtxt(span) => span.data(),
460 SpanKind::InlineParent(span) => span.data(),
461 SpanKind::InlinePair(span) => span.data(),
462 SpanKind::Interned(span) => span.data(),
463 }
464 }
465466/// Returns `true` if this span comes from any kind of macro, desugaring or inlining.
467#[inline]
468pub fn from_expansion(self) -> bool {
469 !self.ctxt().is_root()
470 }
471472/// Returns `true` if this is a dummy span with lo=0, hi=0. Any context value is allowed, which
473 /// means it's not the same as an equality comparison with `DUMMY_SP`.
474#[inline]
475pub fn is_dummy(self) -> bool {
476match self.kind() {
477 SpanKind::InlineCtxt(span) => span.lo == 0 && span.len == 0,
478 SpanKind::InlineParent(span) => span.lo == 0 && span.len == 0,
479 SpanKind::InlinePair(span) => span.lo == 0 && span.len == 0,
480 SpanKind::Interned(span) => span.data().is_dummy(),
481 }
482 }
483484#[inline]
485pub fn map_ctxt(self, map: impl FnOnce(SyntaxContext) -> SyntaxContext) -> Span {
486let data = match self.kind() {
487 SpanKind::InlineCtxt(span) => {
488// This format occurs 1-2 orders of magnitude more often than others (#125017),
489 // so it makes sense to micro-optimize it to avoid `span.data()` and `Span::new()`.
490let new_ctxt = map(SyntaxContext::from_u32(span.ctxt));
491let new_ctxt32 = new_ctxt.as_u32();
492return if let Some(span) = InlineCtxt::try_new_span(span.lo, span.len, new_ctxt32) {
493span494 } else {
495span.data().with_ctxt(new_ctxt)
496 };
497 }
498 SpanKind::InlineParent(span) => span.data(),
499 SpanKind::InlinePair(span) => span.data(),
500 SpanKind::Interned(span) => span.data(),
501 };
502503data.with_ctxt(map(data.ctxt))
504 }
505506/// This function is used as a fast path when decoding the full `SpanData` is not necessary.
507 /// It's a cut-down version of `data_untracked` and doesn't require taking the interner lock.
508#[inline]
509pub fn ctxt(self) -> SyntaxContext {
510SyntaxContext::from_u32(match self.kind() {
511 SpanKind::InlineCtxt(span) => span.ctxt,
512 SpanKind::InlineParent(_span) => return SyntaxContext::root(),
513 SpanKind::InlinePair(span) => span.ctxt,
514 SpanKind::Interned(span) => span.ctxt,
515 })
516 }
517518#[inline]
519pub fn with_parent(self, parent: Option<LocalDefId>) -> Span {
520let data = match self.kind() {
521 SpanKind::InlineCtxt(span) => {
522// This format occurs 1-2 orders of magnitude more often than others (#126544),
523 // so it makes sense to micro-optimize it to avoid `span.data()`.
524match parent {
525None => return self,
526Some(parent)
527if let Some(span) = Span::try_new_span_with_parent(
528span.lo, span.len, span.ctxt, parent,
529 ) =>
530 {
531return span;
532 }
533_ => span.data(),
534 }
535 }
536 SpanKind::InlineParent(span) => span.data(),
537 SpanKind::InlinePair(span) => span.data(),
538 SpanKind::Interned(span) => span.data(),
539 };
540541if let Some(old_parent) = data.parent {
542 (*SPAN_TRACK)(old_parent);
543 }
544data.with_parent(parent)
545 }
546547#[inline]
548pub fn parent(self) -> Option<LocalDefId> {
549let to_parent = |parent| Some(LocalDefId { local_def_index: DefIndex::from_u32(parent) });
550match self.kind() {
551 SpanKind::InlineCtxt(_span) => None,
552 SpanKind::InlineParent(span) => to_parent(span.parent),
553 SpanKind::InlinePair(span) => to_parent(span.parent),
554 SpanKind::Interned(span) => span.data().parent,
555 }
556 }
557558#[inline]
559pub(crate) fn to_raw_span(self) -> RawSpan {
560RawSpan(self.0)
561 }
562563#[inline]
564pub fn from_raw_span(RawSpan(a): RawSpan) -> Span {
565Span(a)
566 }
567}
568569/// Span wrapper that provides equality and ordering based only on the `lo`/`hi` fields. Exists
570/// because `Span` doesn't impl `PartialOrd`/`Ord` due to the `ctxt` and `parent` fields being
571/// unorderable. Useful when storing things in source code order, e.g. in a `BTreeMap<OrdSpan, T>`.
572#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for OrdSpan {
}
#[automatically_derived]impl ::core::clone::Clone for OrdSpan {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<Span>;
*self
}
}Clone, #[automatically_derived]impl ::core::marker::Copy for OrdSpan { }Copy, #[automatically_derived]impl ::core::fmt::Debug for OrdSpan {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f, "OrdSpan",
&&self.0)
}
}Debug)]
573pub struct OrdSpan(pub Span);
574575impl PartialEqfor OrdSpan {
576fn eq(&self, rhs: &Self) -> bool {
577// Ignores `ctxt` and `parent` because they are unorderable.
578self.0.lo_hi() == rhs.0.lo_hi()
579 }
580}
581582impl Eqfor OrdSpan {}
583584impl PartialOrdfor OrdSpan {
585fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
586Some(self.cmp(rhs))
587 }
588}
589590impl Ordfor OrdSpan {
591fn cmp(&self, rhs: &Self) -> Ordering {
592// Ignores `ctxt` and `parent` because they are unorderable.
593self.0.lo_hi().cmp(&rhs.0.lo_hi())
594 }
595}
596597// `OrdSpan` is typically stored in types that rely on ordering, such as `BTreeMap` or `SortedMap`.
598// Hashing shouldn't be necessary.
599impl !Hashfor OrdSpan {}
600601/// `SpanData` minus the `ctxt` field. This is what we actually intern, because we can always store
602/// ctxt inline in `Span`.
603#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for SpanDataNoCtxt {
}
#[automatically_derived]impl ::core::clone::Clone for SpanDataNoCtxt {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<BytePos>;
let _: ::core::clone::AssertParamIsClone<Option<LocalDefId>>;
*self
}
}Clone, #[automatically_derived]impl ::core::marker::Copy for SpanDataNoCtxt { }Copy, #[automatically_derived]impl ::core::hash::Hash for SpanDataNoCtxt {
#[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.parent, state)
}
}Hash, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
SpanDataNoCtxt {
}
#[automatically_derived]impl ::core::cmp::PartialEq for SpanDataNoCtxt {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.lo == other.lo && self.hi == other.hi &&
self.parent == other.parent
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for SpanDataNoCtxt {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<BytePos>;
let _: ::core::cmp::AssertParamIsEq<Option<LocalDefId>>;
}
}Eq)]
604struct SpanDataNoCtxt {
605 lo: BytePos,
606 hi: BytePos,
607 parent: Option<LocalDefId>,
608}
609610#[derive(#[automatically_derived]impl ::core::default::Default for SpanInterner {
#[inline]
fn default() -> Self {
SpanInterner { spans: ::core::default::Default::default() }
}
}Default)]
611pub(crate) struct SpanInterner {
612 spans: FxIndexSet<SpanDataNoCtxt>,
613}
614615impl SpanInterner {
616fn intern(&mut self, span_data_no_ctxt: &SpanDataNoCtxt) -> u32 {
617let (index, _) = self.spans.insert_full(*span_data_no_ctxt);
618indexas u32619 }
620}
621622// If an interner exists, return it. Otherwise, prepare a fresh one.
623#[inline]
624fn with_span_interner<T, F: FnOnce(&mut SpanInterner) -> T>(f: F) -> T {
625crate::with_session_globals(|session_globals| f(&mut session_globals.span_interner.lock()))
626}