Skip to main content

rustc_span/
span_encoding.rs

1use std::cmp::Ordering;
2use std::hash::Hash;
3
4use 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;
9
10use crate::def_id::{DefIndex, LocalDefId};
11use crate::hygiene::SyntaxContext;
12use crate::{BytePos, SPAN_TRACK, SpanData};
13
14/// 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);
95
96// `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 !PartialOrd for Span {}
100impl !Ord for Span {}
101
102/// 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.
107    shift: u32,
108    /// The field's width, in bits.
109    width: u32,
110}
111
112impl SpanField {
113    /// Specifies the top field, i.e. the highest bits. Chained with `below`.
114    #[inline]
115    const fn top(width: u32) -> Self {
116        SpanField { shift: 64 - width, width }
117    }
118
119    /// Specifies a field that comes below the field in `self`. Chainable.
120    #[inline]
121    const fn below(self, width: u32) -> Self {
122        SpanField { shift: self.shift - width, width }
123    }
124
125    /// The mask for the (downshifted to 0..n) field.
126    #[inline]
127    const fn mask(self) -> u64 {
128        (1 << self.width) - 1
129    }
130
131    /// Gets the field from a span-as-`u64` as a `u32`.
132    #[inline]
133    const fn get(self, u: u64) -> u32 {
134        ((u >> self.shift) & self.mask()) as u32
135    }
136
137    /// Sets the field to `v` in an otherwise-zero span-as-`u64`.
138    #[inline]
139    const fn set(self, v: u32) -> u64 {
140        if 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        (v as u64) << self.shift
142    }
143
144    /// Returns non-zero if `v` is too big to fit in the field.
145    #[inline]
146    const fn too_big(self, v: u32) -> u32 {
147        v & !(self.mask() as u32)
148    }
149
150    /// Asserts that a field uses the bottom-most bits.
151    #[inline]
152    const fn assert_is_bottom(self) {
153        if !(self.shift == 0) {
    ::core::panicking::panic("assertion failed: self.shift == 0")
};assert!(self.shift == 0);
154    }
155}
156
157// 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 {
161    pub(crate) lo: u32,
162    pub(crate) len: u32,
163    pub(crate) ctxt: u32,
164}
165
166#[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}
172
173#[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}
180
181#[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}
186
187impl InlineCtxt {
188    const PREFIX_VALUE: u32 = 0b0;
189    const PREFIX: SpanField = SpanField::top(1);
190    const LEN: SpanField = Self::PREFIX.below(15);
191    const CTXT: SpanField = Self::LEN.below(16);
192    const LO: SpanField = Self::CTXT.below(32);
193
194    #[inline]
195    pub(crate) const fn try_new_span(lo: u32, len: u32, ctxt: u32) -> Option<Span> {
196        if Self::LEN.too_big(len) | Self::CTXT.too_big(ctxt) == 0 {
197            Some(Span(
198                Self::PREFIX.set(Self::PREFIX_VALUE)
199                    | Self::LEN.set(len)
200                    | Self::CTXT.set(ctxt)
201                    | Self::LO.set(lo),
202            ))
203        } else {
204            None
205        }
206    }
207
208    #[inline]
209    fn data(self) -> SpanData {
210        SpanData {
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    }
217
218    #[inline]
219    fn from_span(span: Span) -> InlineCtxt {
220        let u = span.0;
221        Self { lo: Self::LO.get(u), len: Self::LEN.get(u), ctxt: Self::CTXT.get(u) }
222    }
223
224    #[inline]
225    pub(crate) fn try_from_span(span: Span) -> Option<InlineCtxt> {
226        if Self::PREFIX.get(span.0) == Self::PREFIX_VALUE {
227            Some(Self::from_span(span))
228        } else {
229            None
230        }
231    }
232}
233const _: () = InlineCtxt::LO.assert_is_bottom();
234
235impl InlineParent {
236    const PREFIX_VALUE: u32 = 0b110;
237    const PREFIX: SpanField = SpanField::top(3);
238    const LEN: SpanField = Self::PREFIX.below(14);
239    const PARENT: SpanField = Self::LEN.below(15);
240    const LO: SpanField = Self::PARENT.below(32);
241
242    #[inline]
243    fn try_new_span(lo: u32, len: u32, ctxt: u32, parent: u32) -> Option<Span> {
244        if Self::LEN.too_big(len) | ctxt | Self::PARENT.too_big(parent) == 0 {
245            Some(Span(
246                Self::PREFIX.set(Self::PREFIX_VALUE)
247                    | Self::LEN.set(len)
248                    | Self::PARENT.set(parent)
249                    | Self::LO.set(lo),
250            ))
251        } else {
252            None
253        }
254    }
255
256    #[inline]
257    fn data(self) -> SpanData {
258        SpanData {
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    }
265
266    #[inline]
267    fn from_span(span: Span) -> InlineParent {
268        let u = span.0;
269        Self { lo: Self::LO.get(u), len: Self::LEN.get(u), parent: Self::PARENT.get(u) }
270    }
271}
272const _: () = InlineParent::LO.assert_is_bottom();
273
274impl InlinePair {
275    const PREFIX_VALUE: u32 = 0b10;
276    const PREFIX: SpanField = SpanField::top(2);
277    const LEN: SpanField = Self::PREFIX.below(7);
278    const CTXT: SpanField = Self::LEN.below(15);
279    const PARENT: SpanField = Self::CTXT.below(16);
280    const LO: SpanField = Self::PARENT.below(24);
281
282    #[inline]
283    fn try_new_span(lo: u32, len: u32, ctxt: u32, parent: u32) -> Option<Span> {
284        if 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        {
290            Some(Span(
291                Self::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 {
298            None
299        }
300    }
301
302    #[inline]
303    fn data(self) -> SpanData {
304        SpanData {
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    }
311
312    #[inline]
313    fn from_span(span: Span) -> InlinePair {
314        let u = span.0;
315        Self {
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();
324
325impl Interned {
326    const PREFIX_VALUE: u32 = 0b111;
327    const PREFIX: SpanField = SpanField::top(3);
328    const CTXT: SpanField = Self::PREFIX.below(29);
329    const INDEX: SpanField = Self::CTXT.below(32);
330
331    #[inline]
332    fn new_span(ctxt: u32, index: u32) -> Span {
333        Span(Self::PREFIX.set(Self::PREFIX_VALUE) | Self::CTXT.set(ctxt) | Self::INDEX.set(index))
334    }
335
336    #[inline]
337    fn data(self) -> SpanData {
338        #[cold]
339        #[inline(never)]
340        fn interned(index: u32) -> SpanDataNoCtxt {
341            with_span_interner(|interner| interner.spans[index as usize])
342        }
343
344        let SpanDataNoCtxt { lo, hi, parent } = interned(self.index);
345        SpanData { lo, hi, ctxt: SyntaxContext::from_u32(self.ctxt), parent }
346    }
347
348    #[inline]
349    fn from_span(span: Span) -> Interned {
350        let u = span.0;
351        Self { ctxt: Self::CTXT.get(u), index: Self::INDEX.get(u) }
352    }
353}
354const _: () = Interned::INDEX.assert_is_bottom();
355
356/// 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}
364
365/// 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();
367
368impl 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]
373    pub fn new(
374        mut lo: BytePos,
375        mut hi: BytePos,
376        ctxt: SyntaxContext,
377        parent: Option<LocalDefId>,
378    ) -> Self {
379        if lo > hi {
380            std::mem::swap(&mut lo, &mut hi);
381        }
382        Span::new_ordered(lo, hi, ctxt, parent)
383    }
384
385    /// Create a new `Span`.
386    ///
387    /// This requires that `lo <= hi`.
388    #[inline]
389    pub fn new_ordered(
390        lo: BytePos,
391        hi: BytePos,
392        ctxt: SyntaxContext,
393        parent: Option<LocalDefId>,
394    ) -> Self {
395        #[cold]
396        #[inline(never)]
397        fn 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
400            let index =
401                with_span_interner(|interner| interner.intern(&SpanDataNoCtxt { lo, hi, parent }));
402            Interned::new_span(ctxt, index)
403        }
404
405        if true {
    if !(lo <= hi) { ::core::panicking::panic("assertion failed: lo <= hi") };
};debug_assert!(lo <= hi);
406
407        let lo32 = lo.0;
408        let (len, ctxt32) = (hi.0 - lo32, ctxt.as_u32());
409        if let Some(parent) = parent {
410            if let Some(span) = Span::try_new_span_with_parent(lo32, len, ctxt32, parent) {
411                // InlineParent or InlinePair.
412                return span;
413            }
414        } else if let Some(span) = InlineCtxt::try_new_span(lo32, len, ctxt32) {
415            // InlineCtxt.
416            return span;
417        }
418
419        interned(lo, hi, ctxt32, parent)
420    }
421
422    /// Tries to create an `InlineParent` or `InlinePair` format span. Returns `None` if the fields
423    /// won't fit.
424    #[inline]
425    fn try_new_span_with_parent(lo: u32, len: u32, ctxt: u32, parent: LocalDefId) -> Option<Self> {
426        let parent = parent.local_def_index.as_u32();
427        InlineParent::try_new_span(lo, len, ctxt, parent)
428            .or_else(|| InlinePair::try_new_span(lo, len, ctxt, parent))
429    }
430
431    #[inline]
432    fn kind(self) -> SpanKind {
433        let span64 = self.0;
434        if 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    }
444
445    #[inline]
446    pub fn data(self) -> SpanData {
447        let data = self.data_untracked();
448        if let Some(parent) = data.parent {
449            (*SPAN_TRACK)(parent);
450        }
451        data
452    }
453
454    /// 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]
457    pub fn data_untracked(self) -> SpanData {
458        match 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    }
465
466    /// Returns `true` if this span comes from any kind of macro, desugaring or inlining.
467    #[inline]
468    pub fn from_expansion(self) -> bool {
469        !self.ctxt().is_root()
470    }
471
472    /// 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]
475    pub fn is_dummy(self) -> bool {
476        match 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    }
483
484    #[inline]
485    pub fn map_ctxt(self, map: impl FnOnce(SyntaxContext) -> SyntaxContext) -> Span {
486        let 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()`.
490                let new_ctxt = map(SyntaxContext::from_u32(span.ctxt));
491                let new_ctxt32 = new_ctxt.as_u32();
492                return if let Some(span) = InlineCtxt::try_new_span(span.lo, span.len, new_ctxt32) {
493                    span
494                } else {
495                    span.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        };
502
503        data.with_ctxt(map(data.ctxt))
504    }
505
506    /// 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]
509    pub fn ctxt(self) -> SyntaxContext {
510        SyntaxContext::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    }
517
518    #[inline]
519    pub fn with_parent(self, parent: Option<LocalDefId>) -> Span {
520        let 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()`.
524                match parent {
525                    None => return self,
526                    Some(parent)
527                        if let Some(span) = Span::try_new_span_with_parent(
528                            span.lo, span.len, span.ctxt, parent,
529                        ) =>
530                    {
531                        return 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        };
540
541        if let Some(old_parent) = data.parent {
542            (*SPAN_TRACK)(old_parent);
543        }
544        data.with_parent(parent)
545    }
546
547    #[inline]
548    pub fn parent(self) -> Option<LocalDefId> {
549        let to_parent = |parent| Some(LocalDefId { local_def_index: DefIndex::from_u32(parent) });
550        match 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    }
557
558    #[inline]
559    pub(crate) fn to_raw_span(self) -> RawSpan {
560        RawSpan(self.0)
561    }
562
563    #[inline]
564    pub fn from_raw_span(RawSpan(a): RawSpan) -> Span {
565        Span(a)
566    }
567}
568
569/// 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);
574
575impl PartialEq for OrdSpan {
576    fn eq(&self, rhs: &Self) -> bool {
577        // Ignores `ctxt` and `parent` because they are unorderable.
578        self.0.lo_hi() == rhs.0.lo_hi()
579    }
580}
581
582impl Eq for OrdSpan {}
583
584impl PartialOrd for OrdSpan {
585    fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
586        Some(self.cmp(rhs))
587    }
588}
589
590impl Ord for OrdSpan {
591    fn cmp(&self, rhs: &Self) -> Ordering {
592        // Ignores `ctxt` and `parent` because they are unorderable.
593        self.0.lo_hi().cmp(&rhs.0.lo_hi())
594    }
595}
596
597// `OrdSpan` is typically stored in types that rely on ordering, such as `BTreeMap` or `SortedMap`.
598// Hashing shouldn't be necessary.
599impl !Hash for OrdSpan {}
600
601/// `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}
609
610#[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}
614
615impl SpanInterner {
616    fn intern(&mut self, span_data_no_ctxt: &SpanDataNoCtxt) -> u32 {
617        let (index, _) = self.spans.insert_full(*span_data_no_ctxt);
618        index as u32
619    }
620}
621
622// 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 {
625    crate::with_session_globals(|session_globals| f(&mut session_globals.span_interner.lock()))
626}