Skip to main content

rustc_metadata/rmeta/
decoder.rs

1// Decoding metadata from a single crate's metadata
2
3use std::iter::TrustedLen;
4use std::ops::{Deref, DerefMut};
5use std::path::{Path, PathBuf};
6use std::sync::{Arc, OnceLock};
7use std::{io, mem};
8
9pub(super) use cstore_impl::provide;
10use rustc_ast as ast;
11use rustc_data_structures::fingerprint::Fingerprint;
12use rustc_data_structures::fx::FxIndexMap;
13use rustc_data_structures::owned_slice::OwnedSlice;
14use rustc_data_structures::sync::Lock;
15use rustc_data_structures::unhash::UnhashMap;
16use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind};
17use rustc_expand::proc_macro::{AttrProcMacro, BangProcMacro, DeriveProcMacro};
18use rustc_hir::Safety;
19use rustc_hir::def::Res;
20use rustc_hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE};
21use rustc_hir::definitions::{DefPath, DefPathData};
22use rustc_hir::diagnostic_items::DiagnosticItems;
23use rustc_index::Idx;
24use rustc_middle::middle::lib_features::LibFeatures;
25use rustc_middle::mir::interpret::{AllocDecodingSession, AllocDecodingState};
26use rustc_middle::ty::Visibility;
27use rustc_middle::ty::codec::TyDecoder;
28use rustc_middle::{bug, implement_ty_decoder};
29use rustc_proc_macro::bridge::client::ProcMacro;
30use rustc_serialize::opaque::MemDecoder;
31use rustc_serialize::{Decodable, Decoder};
32use rustc_session::config::TargetModifier;
33use rustc_session::config::mitigation_coverage::DeniedPartialMitigation;
34use rustc_session::cstore::{CrateSource, ExternCrate};
35use rustc_span::hygiene::HygieneDecodeContext;
36use rustc_span::{
37    BlobDecoder, BytePos, ByteSymbol, DUMMY_SP, Pos, RemapPathScopeComponents, SpanData,
38    SpanDecoder, Symbol, SyntaxContext, kw,
39};
40use tracing::debug;
41
42use crate::creader::CStore;
43use crate::eii::EiiMapEncodedKeyValue;
44use crate::rmeta::table::IsDefault;
45use crate::rmeta::*;
46
47mod cstore_impl;
48
49/// A reference to the raw binary version of crate metadata.
50/// This struct applies [`MemDecoder`]'s validation when constructed
51/// so that later constructions are guaranteed to succeed.
52pub(crate) struct MetadataBlob(OwnedSlice);
53
54impl std::ops::Deref for MetadataBlob {
55    type Target = [u8];
56
57    #[inline]
58    fn deref(&self) -> &[u8] {
59        &self.0[..]
60    }
61}
62
63impl MetadataBlob {
64    /// Runs the [`MemDecoder`] validation and if it passes, constructs a new [`MetadataBlob`].
65    pub(crate) fn new(slice: OwnedSlice) -> Result<Self, ()> {
66        if MemDecoder::new(&slice, 0).is_ok() { Ok(Self(slice)) } else { Err(()) }
67    }
68
69    /// Since this has passed the validation of [`MetadataBlob::new`], this returns bytes which are
70    /// known to pass the [`MemDecoder`] validation.
71    pub(crate) fn bytes(&self) -> &OwnedSlice {
72        &self.0
73    }
74}
75
76/// A map from external crate numbers (as decoded from some crate file) to
77/// local crate numbers (as generated during this session). Each external
78/// crate may refer to types in other external crates, and each has their
79/// own crate numbers.
80pub(crate) type CrateNumMap = IndexVec<CrateNum, CrateNum>;
81
82/// Target modifiers - abi or exploit mitigations options that may cause unsoundness when mixed or
83/// partially enabled.
84pub(crate) type TargetModifiers = Vec<TargetModifier>;
85
86/// The set of mitigations that cannot be partially enabled (see
87/// [RFC 3855](https://github.com/rust-lang/rfcs/pull/3855)), but are currently enabled for this
88/// crate.
89pub(crate) type DeniedPartialMitigations = Vec<DeniedPartialMitigation>;
90
91pub(crate) struct CrateMetadata {
92    /// The primary crate data - binary metadata blob.
93    blob: MetadataBlob,
94
95    // --- Some data pre-decoded from the metadata blob, usually for performance ---
96    /// Data about the top-level items in a crate, as well as various crate-level metadata.
97    root: CrateRoot,
98    /// Trait impl data.
99    /// FIXME: Used only from queries and can use query cache,
100    /// so pre-decoding can probably be avoided.
101    trait_impls: FxIndexMap<(u32, DefIndex), LazyArray<(DefIndex, Option<SimplifiedType>)>>,
102    /// Inherent impls which do not follow the normal coherence rules.
103    ///
104    /// These can be introduced using either `#![rustc_coherence_is_core]`
105    /// or `#[rustc_allow_incoherent_impl]`.
106    incoherent_impls: FxIndexMap<SimplifiedType, LazyArray<DefIndex>>,
107    /// Proc macro descriptions for this crate, if it's a proc macro crate.
108    raw_proc_macros: Option<&'static [ProcMacro]>,
109    /// Source maps for code from the crate.
110    source_map_import_info: Lock<Vec<Option<ImportedSourceFile>>>,
111    /// For every definition in this crate, maps its `DefPathHash` to its `DefIndex`.
112    def_path_hash_map: DefPathHashMapRef<'static>,
113    /// Likewise for ExpnHash.
114    expn_hash_map: OnceLock<UnhashMap<ExpnHash, ExpnIndex>>,
115    /// Used for decoding interpret::AllocIds in a cached & thread-safe manner.
116    alloc_decoding_state: AllocDecodingState,
117    /// Caches decoded `DefKey`s.
118    def_key_cache: Lock<FxHashMap<DefIndex, DefKey>>,
119
120    // --- Other significant crate properties ---
121    /// ID of this crate, from the current compilation session's point of view.
122    cnum: CrateNum,
123    /// Maps crate IDs as they are were seen from this crate's compilation sessions into
124    /// IDs as they are seen from the current compilation session.
125    cnum_map: CrateNumMap,
126    /// How to link (or not link) this crate to the currently compiled crate.
127    dep_kind: CrateDepKind,
128    /// Filesystem location of this crate.
129    source: Arc<CrateSource>,
130    /// Whether or not this crate should be consider a private dependency.
131    /// Used by the 'exported_private_dependencies' lint, and for determining
132    /// whether to emit suggestions that reference this crate.
133    private_dep: bool,
134    /// The hash for the host proc macro. Used to support `-Z dual-proc-macro`.
135    host_hash: Option<Svh>,
136    /// The crate was used non-speculatively.
137    used: bool,
138
139    /// Additional data used for decoding `HygieneData` (e.g. `SyntaxContext`
140    /// and `ExpnId`).
141    /// Note that we store a `HygieneDecodeContext` for each `CrateMetadata`. This is
142    /// because `SyntaxContext` ids are not globally unique, so we need
143    /// to track which ids we've decoded on a per-crate basis.
144    hygiene_context: HygieneDecodeContext,
145
146    // --- Data used only for improving diagnostics ---
147    /// Information about the `extern crate` item or path that caused this crate to be loaded.
148    /// If this is `None`, then the crate was injected (e.g., by the allocator).
149    extern_crate: Option<ExternCrate>,
150}
151
152/// Holds information about a rustc_span::SourceFile imported from another crate.
153/// See `imported_source_file()` for more information.
154#[derive(#[automatically_derived]
impl ::core::clone::Clone for ImportedSourceFile {
    #[inline]
    fn clone(&self) -> ImportedSourceFile {
        ImportedSourceFile {
            original_start_pos: ::core::clone::Clone::clone(&self.original_start_pos),
            original_end_pos: ::core::clone::Clone::clone(&self.original_end_pos),
            translated_source_file: ::core::clone::Clone::clone(&self.translated_source_file),
        }
    }
}Clone)]
155struct ImportedSourceFile {
156    /// This SourceFile's byte-offset within the source_map of its original crate
157    original_start_pos: rustc_span::BytePos,
158    /// The end of this SourceFile within the source_map of its original crate
159    original_end_pos: rustc_span::BytePos,
160    /// The imported SourceFile's representation within the local source_map
161    translated_source_file: Arc<rustc_span::SourceFile>,
162}
163
164/// Decode context used when we just have a blob of metadata from which we have to decode a header
165/// and [`CrateRoot`]. After that, [`MetadataDecodeContext`] can be used.
166/// Most notably, [`BlobDecodeContext]` doesn't implement [`SpanDecoder`]
167pub(super) struct BlobDecodeContext<'a> {
168    opaque: MemDecoder<'a>,
169    blob: &'a MetadataBlob,
170    lazy_state: LazyState,
171}
172
173/// This trait abstracts over decoders that can decode lazy values using [`LazyState`]:
174///
175/// - [`LazyValue`]
176/// - [`LazyArray`]
177/// - [`LazyTable`]
178pub(super) trait LazyDecoder: BlobDecoder {
179    fn set_lazy_state(&mut self, state: LazyState);
180    fn get_lazy_state(&self) -> LazyState;
181
182    fn read_lazy<T>(&mut self) -> LazyValue<T> {
183        self.read_lazy_offset_then(|pos| LazyValue::from_position(pos))
184    }
185
186    fn read_lazy_array<T>(&mut self, len: usize) -> LazyArray<T> {
187        self.read_lazy_offset_then(|pos| LazyArray::from_position_and_num_elems(pos, len))
188    }
189
190    fn read_lazy_table<I, T>(&mut self, width: usize, len: usize) -> LazyTable<I, T> {
191        self.read_lazy_offset_then(|pos| LazyTable::from_position_and_encoded_size(pos, width, len))
192    }
193
194    #[inline]
195    fn read_lazy_offset_then<T>(&mut self, f: impl Fn(NonZero<usize>) -> T) -> T {
196        let distance = self.read_usize();
197        let position = match self.get_lazy_state() {
198            LazyState::NoNode => ::rustc_middle::util::bug::bug_fmt(format_args!("read_lazy_with_meta: outside of a metadata node"))bug!("read_lazy_with_meta: outside of a metadata node"),
199            LazyState::NodeStart(start) => {
200                let start = start.get();
201                if !(distance <= start) {
    ::core::panicking::panic("assertion failed: distance <= start")
};assert!(distance <= start);
202                start - distance
203            }
204            LazyState::Previous(last_pos) => last_pos.get() + distance,
205        };
206        let position = NonZero::new(position).unwrap();
207        self.set_lazy_state(LazyState::Previous(position));
208        f(position)
209    }
210}
211
212impl<'a> LazyDecoder for BlobDecodeContext<'a> {
213    fn set_lazy_state(&mut self, state: LazyState) {
214        self.lazy_state = state;
215    }
216
217    fn get_lazy_state(&self) -> LazyState {
218        self.lazy_state
219    }
220}
221
222/// This is the decode context used when crate metadata was already read.
223/// Decoding of some types, like `Span` require some information to already been read.
224/// Can be constructed from a [`TyCtxt`] and [`CrateMetadata`] (see impls of the [`MetaDecoder`]
225/// trait).
226pub(super) struct MetadataDecodeContext<'a, 'tcx> {
227    blob_decoder: BlobDecodeContext<'a>,
228    cdata: &'a CrateMetadata,
229    tcx: TyCtxt<'tcx>,
230
231    // Used for decoding interpret::AllocIds in a cached & thread-safe manner.
232    alloc_decoding_session: AllocDecodingSession<'a>,
233}
234
235impl<'a, 'tcx> LazyDecoder for MetadataDecodeContext<'a, 'tcx> {
236    fn set_lazy_state(&mut self, state: LazyState) {
237        self.lazy_state = state;
238    }
239
240    fn get_lazy_state(&self) -> LazyState {
241        self.lazy_state
242    }
243}
244
245impl<'a, 'tcx> DerefMut for MetadataDecodeContext<'a, 'tcx> {
246    fn deref_mut(&mut self) -> &mut Self::Target {
247        &mut self.blob_decoder
248    }
249}
250
251impl<'a, 'tcx> Deref for MetadataDecodeContext<'a, 'tcx> {
252    type Target = BlobDecodeContext<'a>;
253
254    fn deref(&self) -> &Self::Target {
255        &self.blob_decoder
256    }
257}
258
259pub(super) trait MetaBlob<'a>: Copy {
260    fn blob(&self) -> &'a MetadataBlob;
261}
262
263pub(super) trait MetaDecoder: Copy {
264    type Context: BlobDecoder + LazyDecoder;
265
266    fn decoder(self, pos: usize) -> Self::Context;
267}
268
269impl<'a> MetaBlob<'a> for &'a MetadataBlob {
270    fn blob(&self) -> &'a MetadataBlob {
271        self
272    }
273}
274
275impl<'a> MetaDecoder for &'a MetadataBlob {
276    type Context = BlobDecodeContext<'a>;
277
278    fn decoder(self, pos: usize) -> Self::Context {
279        BlobDecodeContext {
280            // FIXME: This unwrap should never panic because we check that it won't when creating
281            // `MetadataBlob`. Ideally we'd just have a `MetadataDecoder` and hand out subslices of
282            // it as we do elsewhere in the compiler using `MetadataDecoder::split_at`. But we own
283            // the data for the decoder so holding onto the `MemDecoder` too would make us a
284            // self-referential struct which is downright goofy because `MetadataBlob` is already
285            // self-referential. Probably `MemDecoder` should contain an `OwnedSlice`, but that
286            // demands a significant refactoring due to our crate graph.
287            opaque: MemDecoder::new(self, pos).unwrap(),
288            lazy_state: LazyState::NoNode,
289            blob: self.blob(),
290        }
291    }
292}
293
294impl<'a> MetaBlob<'a> for &'a CrateMetadata {
295    fn blob(&self) -> &'a MetadataBlob {
296        &self.blob
297    }
298}
299
300impl<'a, 'tcx> MetaDecoder for (&'a CrateMetadata, TyCtxt<'tcx>) {
301    type Context = MetadataDecodeContext<'a, 'tcx>;
302
303    fn decoder(self, pos: usize) -> MetadataDecodeContext<'a, 'tcx> {
304        MetadataDecodeContext {
305            blob_decoder: self.0.blob().decoder(pos),
306            cdata: self.0,
307            tcx: self.1,
308            alloc_decoding_session: self.0.alloc_decoding_state.new_decoding_session(),
309        }
310    }
311}
312
313impl<T: ParameterizedOverTcx> LazyValue<T> {
314    #[inline]
315    fn decode<'tcx, M: MetaDecoder>(self, metadata: M) -> T::Value<'tcx>
316    where
317        T::Value<'tcx>: Decodable<M::Context>,
318    {
319        let mut dcx = metadata.decoder(self.position.get());
320        dcx.set_lazy_state(LazyState::NodeStart(self.position));
321        T::Value::decode(&mut dcx)
322    }
323}
324
325struct DecodeIterator<T, D> {
326    elem_counter: std::ops::Range<usize>,
327    dcx: D,
328    _phantom: PhantomData<fn() -> T>,
329}
330
331impl<D: Decoder, T: Decodable<D>> Iterator for DecodeIterator<T, D> {
332    type Item = T;
333
334    #[inline(always)]
335    fn next(&mut self) -> Option<Self::Item> {
336        self.elem_counter.next().map(|_| T::decode(&mut self.dcx))
337    }
338
339    #[inline(always)]
340    fn size_hint(&self) -> (usize, Option<usize>) {
341        self.elem_counter.size_hint()
342    }
343}
344
345impl<D: Decoder, T: Decodable<D>> ExactSizeIterator for DecodeIterator<T, D> {
346    fn len(&self) -> usize {
347        self.elem_counter.len()
348    }
349}
350
351unsafe impl<D: Decoder, T: Decodable<D>> TrustedLen for DecodeIterator<T, D> {}
352
353impl<T: ParameterizedOverTcx> LazyArray<T> {
354    #[inline]
355    fn decode<'tcx, M: MetaDecoder>(self, metadata: M) -> DecodeIterator<T::Value<'tcx>, M::Context>
356    where
357        T::Value<'tcx>: Decodable<M::Context>,
358    {
359        let mut dcx = metadata.decoder(self.position.get());
360        dcx.set_lazy_state(LazyState::NodeStart(self.position));
361        DecodeIterator { elem_counter: (0..self.num_elems), dcx, _phantom: PhantomData }
362    }
363}
364
365impl<'a, 'tcx> MetadataDecodeContext<'a, 'tcx> {
366    #[inline]
367    fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
368        self.cdata.map_encoded_cnum_to_current(cnum)
369    }
370}
371
372impl<'a> BlobDecodeContext<'a> {
373    #[inline]
374    pub(crate) fn blob(&self) -> &'a MetadataBlob {
375        self.blob
376    }
377
378    fn decode_symbol_or_byte_symbol<S>(
379        &mut self,
380        new_from_index: impl Fn(u32) -> S,
381        read_and_intern_str_or_byte_str_this: impl Fn(&mut Self) -> S,
382        read_and_intern_str_or_byte_str_opaque: impl Fn(&mut MemDecoder<'a>) -> S,
383    ) -> S {
384        let tag = self.read_u8();
385
386        match tag {
387            SYMBOL_STR => read_and_intern_str_or_byte_str_this(self),
388            SYMBOL_OFFSET => {
389                // read str offset
390                let pos = self.read_usize();
391
392                // move to str offset and read
393                self.opaque.with_position(pos, |d| read_and_intern_str_or_byte_str_opaque(d))
394            }
395            SYMBOL_PREDEFINED => new_from_index(self.read_u32()),
396            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
397        }
398    }
399}
400
401impl<'a, 'tcx> TyDecoder<'tcx> for MetadataDecodeContext<'a, 'tcx> {
402    const CLEAR_CROSS_CRATE: bool = true;
403
404    #[inline]
405    fn interner(&self) -> TyCtxt<'tcx> {
406        self.tcx
407    }
408
409    fn cached_ty_for_shorthand<F>(&mut self, shorthand: usize, or_insert_with: F) -> Ty<'tcx>
410    where
411        F: FnOnce(&mut Self) -> Ty<'tcx>,
412    {
413        let tcx = self.tcx;
414
415        let key = ty::CReaderCacheKey { cnum: Some(self.cdata.cnum), pos: shorthand };
416
417        if let Some(&ty) = tcx.ty_rcache.borrow().get(&key) {
418            return ty;
419        }
420
421        let ty = or_insert_with(self);
422        tcx.ty_rcache.borrow_mut().insert(key, ty);
423        ty
424    }
425
426    fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
427    where
428        F: FnOnce(&mut Self) -> R,
429    {
430        let new_opaque = self.blob_decoder.opaque.split_at(pos);
431        let old_opaque = mem::replace(&mut self.blob_decoder.opaque, new_opaque);
432        let old_state = mem::replace(&mut self.blob_decoder.lazy_state, LazyState::NoNode);
433        let r = f(self);
434        self.blob_decoder.opaque = old_opaque;
435        self.blob_decoder.lazy_state = old_state;
436        r
437    }
438
439    fn decode_alloc_id(&mut self) -> rustc_middle::mir::interpret::AllocId {
440        let ads = self.alloc_decoding_session;
441        ads.decode_alloc_id(self)
442    }
443}
444
445impl<'a, 'tcx> Decodable<MetadataDecodeContext<'a, 'tcx>> for ExpnIndex {
446    #[inline]
447    fn decode(d: &mut MetadataDecodeContext<'a, 'tcx>) -> ExpnIndex {
448        ExpnIndex::from_u32(d.read_u32())
449    }
450}
451
452impl<'a, 'tcx> SpanDecoder for MetadataDecodeContext<'a, 'tcx> {
453    fn decode_attr_id(&mut self) -> rustc_span::AttrId {
454        self.tcx.sess.psess.attr_id_generator.mk_attr_id()
455    }
456
457    fn decode_crate_num(&mut self) -> CrateNum {
458        let cnum = CrateNum::from_u32(self.read_u32());
459        self.map_encoded_cnum_to_current(cnum)
460    }
461
462    fn decode_def_id(&mut self) -> DefId {
463        DefId { krate: Decodable::decode(self), index: Decodable::decode(self) }
464    }
465
466    fn decode_syntax_context(&mut self) -> SyntaxContext {
467        let cdata = self.cdata;
468        let tcx = self.tcx;
469
470        let cname = cdata.root.name();
471        rustc_span::hygiene::decode_syntax_context(self, &cdata.hygiene_context, |_, id| {
472            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/rmeta/decoder.rs:472",
                        "rustc_metadata::rmeta::decoder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/decoder.rs"),
                        ::tracing_core::__macro_support::Option::Some(472u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::decoder"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("SpecializedDecoder<SyntaxContext>: decoding {0}",
                                                    id) as &dyn Value))])
            });
    } else { ; }
};debug!("SpecializedDecoder<SyntaxContext>: decoding {}", id);
473            cdata
474                .root
475                .syntax_contexts
476                .get(cdata, id)
477                .unwrap_or_else(|| {
    ::core::panicking::panic_fmt(format_args!("Missing SyntaxContext {0:?} for crate {1:?}",
            id, cname));
}panic!("Missing SyntaxContext {id:?} for crate {cname:?}"))
478                .decode((cdata, tcx))
479        })
480    }
481
482    fn decode_expn_id(&mut self) -> ExpnId {
483        let tcx = self.tcx;
484        let cnum = CrateNum::decode(self);
485        let index = u32::decode(self);
486
487        let expn_id = rustc_span::hygiene::decode_expn_id(cnum, index, |expn_id| {
488            let ExpnId { krate: cnum, local_id: index } = expn_id;
489            // Lookup local `ExpnData`s in our own crate data. Foreign `ExpnData`s
490            // are stored in the owning crate, to avoid duplication.
491            if true {
    match (&cnum, &LOCAL_CRATE) {
        (left_val, right_val) => {
            if *left_val == *right_val {
                let kind = ::core::panicking::AssertKind::Ne;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    };
};debug_assert_ne!(cnum, LOCAL_CRATE);
492            let cstore;
493            let cdata = if cnum == self.cdata.cnum {
494                self.cdata
495            } else {
496                cstore = CStore::from_tcx(tcx);
497                cstore.get_crate_data(cnum)
498            };
499            let expn_data = cdata.root.expn_data.get(cdata, index).unwrap().decode((cdata, tcx));
500            let expn_hash = cdata.root.expn_hashes.get(cdata, index).unwrap().decode((cdata, tcx));
501            (expn_data, expn_hash)
502        });
503        expn_id
504    }
505
506    fn decode_span(&mut self) -> Span {
507        let start = self.position();
508        let tag = SpanTag(self.peek_byte());
509        let data = if tag.kind() == SpanKind::Indirect {
510            // Skip past the tag we just peek'd.
511            self.read_u8();
512            // indirect tag lengths are safe to access, since they're (0, 8)
513            let bytes_needed = tag.length().unwrap().0 as usize;
514            let mut total = [0u8; usize::BITS as usize / 8];
515            total[..bytes_needed].copy_from_slice(self.read_raw_bytes(bytes_needed));
516            let offset_or_position = usize::from_le_bytes(total);
517            let position = if tag.is_relative_offset() {
518                start - offset_or_position
519            } else {
520                offset_or_position
521            };
522            self.with_position(position, SpanData::decode)
523        } else {
524            SpanData::decode(self)
525        };
526        data.span()
527    }
528}
529
530impl<'a, 'tcx> BlobDecoder for MetadataDecodeContext<'a, 'tcx> {
531    fn decode_def_index(&mut self) -> DefIndex {
532        self.blob_decoder.decode_def_index()
533    }
534    fn decode_symbol(&mut self) -> Symbol {
535        self.blob_decoder.decode_symbol()
536    }
537
538    fn decode_byte_symbol(&mut self) -> ByteSymbol {
539        self.blob_decoder.decode_byte_symbol()
540    }
541}
542
543impl<'a> BlobDecoder for BlobDecodeContext<'a> {
544    fn decode_def_index(&mut self) -> DefIndex {
545        DefIndex::from_u32(self.read_u32())
546    }
547    fn decode_symbol(&mut self) -> Symbol {
548        self.decode_symbol_or_byte_symbol(
549            Symbol::new,
550            |this| Symbol::intern(this.read_str()),
551            |opaque| Symbol::intern(opaque.read_str()),
552        )
553    }
554
555    fn decode_byte_symbol(&mut self) -> ByteSymbol {
556        self.decode_symbol_or_byte_symbol(
557            ByteSymbol::new,
558            |this| ByteSymbol::intern(this.read_byte_str()),
559            |opaque| ByteSymbol::intern(opaque.read_byte_str()),
560        )
561    }
562}
563
564impl<'a, 'tcx> Decodable<MetadataDecodeContext<'a, 'tcx>> for SpanData {
565    fn decode(decoder: &mut MetadataDecodeContext<'a, 'tcx>) -> SpanData {
566        let tag = SpanTag::decode(decoder);
567        let ctxt = tag.context().unwrap_or_else(|| SyntaxContext::decode(decoder));
568
569        if tag.kind() == SpanKind::Partial {
570            return DUMMY_SP.with_ctxt(ctxt).data();
571        }
572
573        if true {
    if !(tag.kind() == SpanKind::Local || tag.kind() == SpanKind::Foreign) {
        ::core::panicking::panic("assertion failed: tag.kind() == SpanKind::Local || tag.kind() == SpanKind::Foreign")
    };
};debug_assert!(tag.kind() == SpanKind::Local || tag.kind() == SpanKind::Foreign);
574
575        let lo = BytePos::decode(decoder);
576        let len = tag.length().unwrap_or_else(|| BytePos::decode(decoder));
577        let hi = lo + len;
578
579        let tcx = decoder.tcx;
580
581        // Index of the file in the corresponding crate's list of encoded files.
582        let metadata_index = u32::decode(decoder);
583
584        // There are two possibilities here:
585        // 1. This is a 'local span', which is located inside a `SourceFile`
586        // that came from this crate. In this case, we use the source map data
587        // encoded in this crate. This branch should be taken nearly all of the time.
588        // 2. This is a 'foreign span', which is located inside a `SourceFile`
589        // that came from a *different* crate (some crate upstream of the one
590        // whose metadata we're looking at). For example, consider this dependency graph:
591        //
592        // A -> B -> C
593        //
594        // Suppose that we're currently compiling crate A, and start deserializing
595        // metadata from crate B. When we deserialize a Span from crate B's metadata,
596        // there are two possibilities:
597        //
598        // 1. The span references a file from crate B. This makes it a 'local' span,
599        // which means that we can use crate B's serialized source map information.
600        // 2. The span references a file from crate C. This makes it a 'foreign' span,
601        // which means we need to use Crate *C* (not crate B) to determine the source
602        // map information. We only record source map information for a file in the
603        // crate that 'owns' it, so deserializing a Span may require us to look at
604        // a transitive dependency.
605        //
606        // When we encode a foreign span, we adjust its 'lo' and 'high' values
607        // to be based on the *foreign* crate (e.g. crate C), not the crate
608        // we are writing metadata for (e.g. crate B). This allows us to
609        // treat the 'local' and 'foreign' cases almost identically during deserialization:
610        // we can call `imported_source_file` for the proper crate, and binary search
611        // through the returned slice using our span.
612        let source_file = if tag.kind() == SpanKind::Local {
613            decoder.cdata.imported_source_file(tcx, metadata_index)
614        } else {
615            // When we encode a proc-macro crate, all `Span`s should be encoded
616            // with `TAG_VALID_SPAN_LOCAL`
617            if decoder.cdata.root.is_proc_macro_crate() {
618                // Decode `CrateNum` as u32 - using `CrateNum::decode` will ICE
619                // since we don't have `cnum_map` populated.
620                let cnum = u32::decode(decoder);
621                {
    ::core::panicking::panic_fmt(format_args!("Decoding of crate {0:?} tried to access proc-macro dep {1:?}",
            decoder.cdata.root.header.name, cnum));
};panic!(
622                    "Decoding of crate {:?} tried to access proc-macro dep {:?}",
623                    decoder.cdata.root.header.name, cnum
624                );
625            }
626            // tag is TAG_VALID_SPAN_FOREIGN, checked by `debug_assert` above
627            let cnum = CrateNum::decode(decoder);
628            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/rmeta/decoder.rs:628",
                        "rustc_metadata::rmeta::decoder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/decoder.rs"),
                        ::tracing_core::__macro_support::Option::Some(628u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::decoder"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("SpecializedDecoder<Span>::specialized_decode: loading source files from cnum {0:?}",
                                                    cnum) as &dyn Value))])
            });
    } else { ; }
};debug!(
629                "SpecializedDecoder<Span>::specialized_decode: loading source files from cnum {:?}",
630                cnum
631            );
632
633            let cstore = CStore::from_tcx(tcx);
634            let foreign_cdata = cstore.get_crate_data(cnum);
635            foreign_cdata.imported_source_file(tcx, metadata_index)
636        };
637
638        // Make sure our span is well-formed.
639        if true {
    if !(lo + source_file.original_start_pos <= source_file.original_end_pos)
        {
        {
            ::core::panicking::panic_fmt(format_args!("Malformed encoded span: lo={0:?} source_file.original_start_pos={1:?} source_file.original_end_pos={2:?}",
                    lo, source_file.original_start_pos,
                    source_file.original_end_pos));
        }
    };
};debug_assert!(
640            lo + source_file.original_start_pos <= source_file.original_end_pos,
641            "Malformed encoded span: lo={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}",
642            lo,
643            source_file.original_start_pos,
644            source_file.original_end_pos
645        );
646
647        // Make sure we correctly filtered out invalid spans during encoding.
648        if true {
    if !(hi + source_file.original_start_pos <= source_file.original_end_pos)
        {
        {
            ::core::panicking::panic_fmt(format_args!("Malformed encoded span: hi={0:?} source_file.original_start_pos={1:?} source_file.original_end_pos={2:?}",
                    hi, source_file.original_start_pos,
                    source_file.original_end_pos));
        }
    };
};debug_assert!(
649            hi + source_file.original_start_pos <= source_file.original_end_pos,
650            "Malformed encoded span: hi={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}",
651            hi,
652            source_file.original_start_pos,
653            source_file.original_end_pos
654        );
655
656        let lo = lo + source_file.translated_source_file.start_pos;
657        let hi = hi + source_file.translated_source_file.start_pos;
658
659        // Do not try to decode parent for foreign spans (it wasn't encoded in the first place).
660        SpanData { lo, hi, ctxt, parent: None }
661    }
662}
663
664impl<'a, 'tcx> Decodable<MetadataDecodeContext<'a, 'tcx>> for &'tcx [(ty::Clause<'tcx>, Span)] {
665    fn decode(d: &mut MetadataDecodeContext<'a, 'tcx>) -> Self {
666        ty::codec::RefDecodable::decode(d)
667    }
668}
669
670impl<D: LazyDecoder, T> Decodable<D> for LazyValue<T> {
671    fn decode(decoder: &mut D) -> Self {
672        decoder.read_lazy()
673    }
674}
675
676impl<D: LazyDecoder, T> Decodable<D> for LazyArray<T> {
677    #[inline]
678    fn decode(decoder: &mut D) -> Self {
679        let len = decoder.read_usize();
680        if len == 0 { LazyArray::default() } else { decoder.read_lazy_array(len) }
681    }
682}
683
684impl<I: Idx, D: LazyDecoder, T> Decodable<D> for LazyTable<I, T> {
685    fn decode(decoder: &mut D) -> Self {
686        let width = decoder.read_usize();
687        let len = decoder.read_usize();
688        decoder.read_lazy_table(width, len)
689    }
690}
691
692mod meta {
693    use super::*;
694    mod __ty_decoder_impl {
    use rustc_serialize::Decoder;
    use super::MetadataDecodeContext;
    impl<'a, 'tcx> Decoder for MetadataDecodeContext<'a, 'tcx> {
        #[inline]
        fn read_usize(&mut self) -> usize { self.opaque.read_usize() }
        #[inline]
        fn read_u128(&mut self) -> u128 { self.opaque.read_u128() }
        #[inline]
        fn read_u64(&mut self) -> u64 { self.opaque.read_u64() }
        #[inline]
        fn read_u32(&mut self) -> u32 { self.opaque.read_u32() }
        #[inline]
        fn read_u16(&mut self) -> u16 { self.opaque.read_u16() }
        #[inline]
        fn read_u8(&mut self) -> u8 { self.opaque.read_u8() }
        #[inline]
        fn read_isize(&mut self) -> isize { self.opaque.read_isize() }
        #[inline]
        fn read_i128(&mut self) -> i128 { self.opaque.read_i128() }
        #[inline]
        fn read_i64(&mut self) -> i64 { self.opaque.read_i64() }
        #[inline]
        fn read_i32(&mut self) -> i32 { self.opaque.read_i32() }
        #[inline]
        fn read_i16(&mut self) -> i16 { self.opaque.read_i16() }
        #[inline]
        fn read_raw_bytes(&mut self, len: usize) -> &[u8] {
            self.opaque.read_raw_bytes(len)
        }
        #[inline]
        fn peek_byte(&self) -> u8 { self.opaque.peek_byte() }
        #[inline]
        fn position(&self) -> usize { self.opaque.position() }
    }
}implement_ty_decoder!(MetadataDecodeContext<'a, 'tcx>);
695}
696mod blob {
697    use super::*;
698    mod __ty_decoder_impl {
    use rustc_serialize::Decoder;
    use super::BlobDecodeContext;
    impl<'a> Decoder for BlobDecodeContext<'a> {
        #[inline]
        fn read_usize(&mut self) -> usize { self.opaque.read_usize() }
        #[inline]
        fn read_u128(&mut self) -> u128 { self.opaque.read_u128() }
        #[inline]
        fn read_u64(&mut self) -> u64 { self.opaque.read_u64() }
        #[inline]
        fn read_u32(&mut self) -> u32 { self.opaque.read_u32() }
        #[inline]
        fn read_u16(&mut self) -> u16 { self.opaque.read_u16() }
        #[inline]
        fn read_u8(&mut self) -> u8 { self.opaque.read_u8() }
        #[inline]
        fn read_isize(&mut self) -> isize { self.opaque.read_isize() }
        #[inline]
        fn read_i128(&mut self) -> i128 { self.opaque.read_i128() }
        #[inline]
        fn read_i64(&mut self) -> i64 { self.opaque.read_i64() }
        #[inline]
        fn read_i32(&mut self) -> i32 { self.opaque.read_i32() }
        #[inline]
        fn read_i16(&mut self) -> i16 { self.opaque.read_i16() }
        #[inline]
        fn read_raw_bytes(&mut self, len: usize) -> &[u8] {
            self.opaque.read_raw_bytes(len)
        }
        #[inline]
        fn peek_byte(&self) -> u8 { self.opaque.peek_byte() }
        #[inline]
        fn position(&self) -> usize { self.opaque.position() }
    }
}implement_ty_decoder!(BlobDecodeContext<'a>);
699}
700
701impl MetadataBlob {
702    pub(crate) fn check_compatibility(
703        &self,
704        cfg_version: &'static str,
705    ) -> Result<(), Option<String>> {
706        if !self.starts_with(METADATA_HEADER) {
707            if self.starts_with(b"rust") {
708                return Err(Some("<unknown rustc version>".to_owned()));
709            }
710            return Err(None);
711        }
712
713        let found_version =
714            LazyValue::<String>::from_position(NonZero::new(METADATA_HEADER.len() + 8).unwrap())
715                .decode(self);
716        if rustc_version(cfg_version) != found_version {
717            return Err(Some(found_version));
718        }
719
720        Ok(())
721    }
722
723    fn root_pos(&self) -> NonZero<usize> {
724        let offset = METADATA_HEADER.len();
725        let pos_bytes = self[offset..][..8].try_into().unwrap();
726        let pos = u64::from_le_bytes(pos_bytes);
727        NonZero::new(pos as usize).unwrap()
728    }
729
730    pub(crate) fn get_header(&self) -> CrateHeader {
731        let pos = self.root_pos();
732        LazyValue::<CrateHeader>::from_position(pos).decode(self)
733    }
734
735    pub(crate) fn get_root(&self) -> CrateRoot {
736        let pos = self.root_pos();
737        LazyValue::<CrateRoot>::from_position(pos).decode(self)
738    }
739
740    pub(crate) fn list_crate_metadata(
741        &self,
742        out: &mut dyn io::Write,
743        ls_kinds: &[String],
744    ) -> io::Result<()> {
745        let root = self.get_root();
746
747        let all_ls_kinds = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        ["root".to_owned(), "lang_items".to_owned(), "features".to_owned(),
                "items".to_owned()]))vec![
748            "root".to_owned(),
749            "lang_items".to_owned(),
750            "features".to_owned(),
751            "items".to_owned(),
752        ];
753        let ls_kinds = if ls_kinds.contains(&"all".to_owned()) { &all_ls_kinds } else { ls_kinds };
754
755        for kind in ls_kinds {
756            match &**kind {
757                "root" => {
758                    out.write_fmt(format_args!("Crate info:\n"))writeln!(out, "Crate info:")?;
759                    out.write_fmt(format_args!("name {0}{1}\n", root.name(), root.extra_filename))writeln!(out, "name {}{}", root.name(), root.extra_filename)?;
760                    out.write_fmt(format_args!("hash {0} stable_crate_id {1:?}\n", root.hash(),
        root.stable_crate_id))writeln!(
761                        out,
762                        "hash {} stable_crate_id {:?}",
763                        root.hash(),
764                        root.stable_crate_id
765                    )?;
766                    out.write_fmt(format_args!("proc_macro {0:?}\n",
        root.proc_macro_data.is_some()))writeln!(out, "proc_macro {:?}", root.proc_macro_data.is_some())?;
767                    out.write_fmt(format_args!("triple {0}\n", root.header.triple.tuple()))writeln!(out, "triple {}", root.header.triple.tuple())?;
768                    out.write_fmt(format_args!("edition {0}\n", root.edition))writeln!(out, "edition {}", root.edition)?;
769                    out.write_fmt(format_args!("symbol_mangling_version {0:?}\n",
        root.symbol_mangling_version))writeln!(out, "symbol_mangling_version {:?}", root.symbol_mangling_version)?;
770                    out.write_fmt(format_args!("required_panic_strategy {0:?} panic_in_drop_strategy {1:?}\n",
        root.required_panic_strategy, root.panic_in_drop_strategy))writeln!(
771                        out,
772                        "required_panic_strategy {:?} panic_in_drop_strategy {:?}",
773                        root.required_panic_strategy, root.panic_in_drop_strategy
774                    )?;
775                    out.write_fmt(format_args!("has_global_allocator {0} has_alloc_error_handler {1} has_panic_handler {2} has_default_lib_allocator {3}\n",
        root.has_global_allocator, root.has_alloc_error_handler,
        root.has_panic_handler, root.has_default_lib_allocator))writeln!(
776                        out,
777                        "has_global_allocator {} has_alloc_error_handler {} has_panic_handler {} has_default_lib_allocator {}",
778                        root.has_global_allocator,
779                        root.has_alloc_error_handler,
780                        root.has_panic_handler,
781                        root.has_default_lib_allocator
782                    )?;
783                    out.write_fmt(format_args!("compiler_builtins {0} needs_allocator {1} needs_panic_runtime {2} no_builtins {3} panic_runtime {4} profiler_runtime {5}\n",
        root.compiler_builtins, root.needs_allocator,
        root.needs_panic_runtime, root.no_builtins, root.panic_runtime,
        root.profiler_runtime))writeln!(
784                        out,
785                        "compiler_builtins {} needs_allocator {} needs_panic_runtime {} no_builtins {} panic_runtime {} profiler_runtime {}",
786                        root.compiler_builtins,
787                        root.needs_allocator,
788                        root.needs_panic_runtime,
789                        root.no_builtins,
790                        root.panic_runtime,
791                        root.profiler_runtime
792                    )?;
793
794                    out.write_fmt(format_args!("=External Dependencies=\n"))writeln!(out, "=External Dependencies=")?;
795                    let dylib_dependency_formats =
796                        root.dylib_dependency_formats.decode(self).collect::<Vec<_>>();
797                    for (i, dep) in root.crate_deps.decode(self).enumerate() {
798                        let CrateDep { name, extra_filename, hash, host_hash, kind, is_private } =
799                            dep;
800                        let number = i + 1;
801
802                        out.write_fmt(format_args!("{2} {3}{4} hash {5} host_hash {6:?} kind {7:?} {0}{1}\n",
        if is_private { "private" } else { "public" },
        if dylib_dependency_formats.is_empty() {
            String::new()
        } else {
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!(" linkage {0:?}",
                            dylib_dependency_formats[i]))
                })
        }, number, name, extra_filename, hash, host_hash, kind))writeln!(
803                            out,
804                            "{number} {name}{extra_filename} hash {hash} host_hash {host_hash:?} kind {kind:?} {privacy}{linkage}",
805                            privacy = if is_private { "private" } else { "public" },
806                            linkage = if dylib_dependency_formats.is_empty() {
807                                String::new()
808                            } else {
809                                format!(" linkage {:?}", dylib_dependency_formats[i])
810                            }
811                        )?;
812                    }
813                    out.write_fmt(format_args!("\n"))write!(out, "\n")?;
814                }
815
816                "lang_items" => {
817                    out.write_fmt(format_args!("=Lang items=\n"))writeln!(out, "=Lang items=")?;
818                    for (id, lang_item) in root.lang_items.decode(self) {
819                        out.write_fmt(format_args!("{0} = crate{1}\n", lang_item.name(),
        DefPath::make(LOCAL_CRATE, id,
                |parent|
                    root.tables.def_keys.get(self,
                                parent).unwrap().decode(self)).to_string_no_crate_verbose()))writeln!(
820                            out,
821                            "{} = crate{}",
822                            lang_item.name(),
823                            DefPath::make(LOCAL_CRATE, id, |parent| root
824                                .tables
825                                .def_keys
826                                .get(self, parent)
827                                .unwrap()
828                                .decode(self))
829                            .to_string_no_crate_verbose()
830                        )?;
831                    }
832                    for lang_item in root.lang_items_missing.decode(self) {
833                        out.write_fmt(format_args!("{0} = <missing>\n", lang_item.name()))writeln!(out, "{} = <missing>", lang_item.name())?;
834                    }
835                    out.write_fmt(format_args!("\n"))write!(out, "\n")?;
836                }
837
838                "features" => {
839                    out.write_fmt(format_args!("=Lib features=\n"))writeln!(out, "=Lib features=")?;
840                    for (feature, since) in root.lib_features.decode(self) {
841                        out.write_fmt(format_args!("{0}{1}\n", feature,
        if let FeatureStability::AcceptedSince(since) = since {
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!(" since {0}", since))
                })
        } else { String::new() }))writeln!(
842                            out,
843                            "{}{}",
844                            feature,
845                            if let FeatureStability::AcceptedSince(since) = since {
846                                format!(" since {since}")
847                            } else {
848                                String::new()
849                            }
850                        )?;
851                    }
852                    out.write_fmt(format_args!("\n"))write!(out, "\n")?;
853                }
854
855                "items" => {
856                    out.write_fmt(format_args!("=Items=\n"))writeln!(out, "=Items=")?;
857
858                    fn print_item(
859                        blob: &MetadataBlob,
860                        out: &mut dyn io::Write,
861                        item: DefIndex,
862                        indent: usize,
863                    ) -> io::Result<()> {
864                        let root = blob.get_root();
865
866                        let def_kind = root.tables.def_kind.get(blob, item).unwrap();
867                        let def_key = root.tables.def_keys.get(blob, item).unwrap().decode(blob);
868                        #[allow(rustc::symbol_intern_string_literal)]
869                        let def_name = if item == CRATE_DEF_INDEX {
870                            kw::Crate
871                        } else {
872                            def_key
873                                .disambiguated_data
874                                .data
875                                .get_opt_name()
876                                .unwrap_or_else(|| Symbol::intern("???"))
877                        };
878                        let visibility =
879                            root.tables.visibility.get(blob, item).unwrap().decode(blob).map_id(
880                                |index| {
881                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("crate{0}",
                DefPath::make(LOCAL_CRATE, index,
                        |parent|
                            root.tables.def_keys.get(blob,
                                        parent).unwrap().decode(blob)).to_string_no_crate_verbose()))
    })format!(
882                                        "crate{}",
883                                        DefPath::make(LOCAL_CRATE, index, |parent| root
884                                            .tables
885                                            .def_keys
886                                            .get(blob, parent)
887                                            .unwrap()
888                                            .decode(blob))
889                                        .to_string_no_crate_verbose()
890                                    )
891                                },
892                            );
893                        out.write_fmt(format_args!("{3: <4$}{0:?} {1:?} {2} {{", visibility, def_kind,
        def_name, "", indent))write!(
894                            out,
895                            "{nil: <indent$}{:?} {:?} {} {{",
896                            visibility,
897                            def_kind,
898                            def_name,
899                            nil = "",
900                        )?;
901
902                        if let Some(children) =
903                            root.tables.module_children_non_reexports.get(blob, item)
904                        {
905                            out.write_fmt(format_args!("\n"))write!(out, "\n")?;
906                            for child in children.decode(blob) {
907                                print_item(blob, out, child, indent + 4)?;
908                            }
909                            out.write_fmt(format_args!("{0: <1$}}}\n", "", indent))writeln!(out, "{nil: <indent$}}}", nil = "")?;
910                        } else {
911                            out.write_fmt(format_args!("}}\n"))writeln!(out, "}}")?;
912                        }
913
914                        Ok(())
915                    }
916
917                    print_item(self, out, CRATE_DEF_INDEX, 0)?;
918
919                    out.write_fmt(format_args!("\n"))write!(out, "\n")?;
920                }
921
922                _ => {
923                    out.write_fmt(format_args!("unknown -Zls kind. allowed values are: all, root, lang_items, features, items\n"))writeln!(
924                        out,
925                        "unknown -Zls kind. allowed values are: all, root, lang_items, features, items"
926                    )?;
927                }
928            }
929        }
930
931        Ok(())
932    }
933}
934
935impl CrateRoot {
936    pub(crate) fn is_proc_macro_crate(&self) -> bool {
937        self.proc_macro_data.is_some()
938    }
939
940    pub(crate) fn name(&self) -> Symbol {
941        self.header.name
942    }
943
944    pub(crate) fn hash(&self) -> Svh {
945        self.header.hash
946    }
947
948    pub(crate) fn stable_crate_id(&self) -> StableCrateId {
949        self.stable_crate_id
950    }
951
952    pub(crate) fn decode_crate_deps<'a>(
953        &self,
954        metadata: &'a MetadataBlob,
955    ) -> impl ExactSizeIterator<Item = CrateDep> {
956        self.crate_deps.decode(metadata)
957    }
958
959    pub(crate) fn decode_target_modifiers<'a>(
960        &self,
961        metadata: &'a MetadataBlob,
962    ) -> impl ExactSizeIterator<Item = TargetModifier> {
963        self.target_modifiers.decode(metadata)
964    }
965
966    pub(crate) fn decode_denied_partial_mitigations<'a>(
967        &self,
968        metadata: &'a MetadataBlob,
969    ) -> impl ExactSizeIterator<Item = DeniedPartialMitigation> {
970        self.denied_partial_mitigations.decode(metadata)
971    }
972}
973
974impl CrateMetadata {
975    fn missing(&self, descr: &str, id: DefIndex) -> ! {
976        ::rustc_middle::util::bug::bug_fmt(format_args!("missing `{1}` for {0:?}",
        self.local_def_id(id), descr))bug!("missing `{descr}` for {:?}", self.local_def_id(id))
977    }
978
979    fn raw_proc_macro(&self, tcx: TyCtxt<'_>, id: DefIndex) -> &ProcMacro {
980        // DefIndex's in root.proc_macro_data have a one-to-one correspondence
981        // with items in 'raw_proc_macros'.
982        let pos = self
983            .root
984            .proc_macro_data
985            .as_ref()
986            .unwrap()
987            .macros
988            .decode((self, tcx))
989            .position(|i| i == id)
990            .unwrap();
991        &self.raw_proc_macros.unwrap()[pos]
992    }
993
994    fn opt_item_name(&self, item_index: DefIndex) -> Option<Symbol> {
995        let def_key = self.def_key(item_index);
996        def_key.disambiguated_data.data.get_opt_name().or_else(|| {
997            if def_key.disambiguated_data.data == DefPathData::Ctor {
998                let parent_index = def_key.parent.expect("no parent for a constructor");
999                self.def_key(parent_index).disambiguated_data.data.get_opt_name()
1000            } else {
1001                None
1002            }
1003        })
1004    }
1005
1006    fn item_name(&self, item_index: DefIndex) -> Symbol {
1007        self.opt_item_name(item_index).expect("no encoded ident for item")
1008    }
1009
1010    fn opt_item_ident(&self, tcx: TyCtxt<'_>, item_index: DefIndex) -> Option<Ident> {
1011        let name = self.opt_item_name(item_index)?;
1012        let span = self
1013            .root
1014            .tables
1015            .def_ident_span
1016            .get(self, item_index)
1017            .unwrap_or_else(|| self.missing("def_ident_span", item_index))
1018            .decode((self, tcx));
1019        Some(Ident::new(name, span))
1020    }
1021
1022    fn item_ident(&self, tcx: TyCtxt<'_>, item_index: DefIndex) -> Ident {
1023        self.opt_item_ident(tcx, item_index).expect("no encoded ident for item")
1024    }
1025
1026    #[inline]
1027    pub(super) fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
1028        if cnum == LOCAL_CRATE { self.cnum } else { self.cnum_map[cnum] }
1029    }
1030
1031    fn def_kind(&self, item_id: DefIndex) -> DefKind {
1032        self.root
1033            .tables
1034            .def_kind
1035            .get(self, item_id)
1036            .unwrap_or_else(|| self.missing("def_kind", item_id))
1037    }
1038
1039    fn get_span(&self, tcx: TyCtxt<'_>, index: DefIndex) -> Span {
1040        self.root
1041            .tables
1042            .def_span
1043            .get(self, index)
1044            .unwrap_or_else(|| self.missing("def_span", index))
1045            .decode((self, tcx))
1046    }
1047
1048    fn load_proc_macro<'tcx>(&self, tcx: TyCtxt<'tcx>, id: DefIndex) -> SyntaxExtension {
1049        let (name, kind, helper_attrs) = match *self.raw_proc_macro(tcx, id) {
1050            ProcMacro::CustomDerive { trait_name, attributes, client } => {
1051                let helper_attrs =
1052                    attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
1053                (
1054                    trait_name,
1055                    SyntaxExtensionKind::Derive(Arc::new(DeriveProcMacro { client })),
1056                    helper_attrs,
1057                )
1058            }
1059            ProcMacro::Attr { name, client } => {
1060                (name, SyntaxExtensionKind::Attr(Arc::new(AttrProcMacro { client })), Vec::new())
1061            }
1062            ProcMacro::Bang { name, client } => {
1063                (name, SyntaxExtensionKind::Bang(Arc::new(BangProcMacro { client })), Vec::new())
1064            }
1065        };
1066
1067        let sess = tcx.sess;
1068        let attrs: Vec<_> = self.get_item_attrs(tcx, id).collect();
1069        SyntaxExtension::new(
1070            sess,
1071            kind,
1072            self.get_span(tcx, id),
1073            helper_attrs,
1074            self.root.edition,
1075            Symbol::intern(name),
1076            &attrs,
1077            false,
1078        )
1079    }
1080
1081    fn get_variant(
1082        &self,
1083        tcx: TyCtxt<'_>,
1084        kind: DefKind,
1085        index: DefIndex,
1086        parent_did: DefId,
1087    ) -> (VariantIdx, ty::VariantDef) {
1088        let adt_kind = match kind {
1089            DefKind::Variant => ty::AdtKind::Enum,
1090            DefKind::Struct => ty::AdtKind::Struct,
1091            DefKind::Union => ty::AdtKind::Union,
1092            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
1093        };
1094
1095        let data = self.root.tables.variant_data.get(self, index).unwrap().decode((self, tcx));
1096
1097        let variant_did =
1098            if adt_kind == ty::AdtKind::Enum { Some(self.local_def_id(index)) } else { None };
1099        let ctor = data.ctor.map(|(kind, index)| (kind, self.local_def_id(index)));
1100
1101        (
1102            data.idx,
1103            ty::VariantDef::new(
1104                self.item_name(index),
1105                variant_did,
1106                ctor,
1107                data.discr,
1108                self.get_associated_item_or_field_def_ids(tcx, index)
1109                    .map(|did| ty::FieldDef {
1110                        did,
1111                        name: self.item_name(did.index),
1112                        vis: self.get_visibility(tcx, did.index),
1113                        safety: self.get_safety(did.index),
1114                        value: self.get_default_field(tcx, did.index),
1115                    })
1116                    .collect(),
1117                parent_did,
1118                None,
1119                data.is_non_exhaustive,
1120            ),
1121        )
1122    }
1123
1124    fn get_adt_def<'tcx>(&self, tcx: TyCtxt<'tcx>, item_id: DefIndex) -> ty::AdtDef<'tcx> {
1125        let kind = self.def_kind(item_id);
1126        let did = self.local_def_id(item_id);
1127
1128        let adt_kind = match kind {
1129            DefKind::Enum => ty::AdtKind::Enum,
1130            DefKind::Struct => ty::AdtKind::Struct,
1131            DefKind::Union => ty::AdtKind::Union,
1132            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("get_adt_def called on a non-ADT {0:?}",
        did))bug!("get_adt_def called on a non-ADT {:?}", did),
1133        };
1134        let repr = self.root.tables.repr_options.get(self, item_id).unwrap().decode((self, tcx));
1135
1136        let mut variants: Vec<_> = if let ty::AdtKind::Enum = adt_kind {
1137            self.root
1138                .tables
1139                .module_children_non_reexports
1140                .get(self, item_id)
1141                .expect("variants are not encoded for an enum")
1142                .decode((self, tcx))
1143                .filter_map(|index| {
1144                    let kind = self.def_kind(index);
1145                    match kind {
1146                        DefKind::Ctor(..) => None,
1147                        _ => Some(self.get_variant(tcx, kind, index, did)),
1148                    }
1149                })
1150                .collect()
1151        } else {
1152            std::iter::once(self.get_variant(tcx, kind, item_id, did)).collect()
1153        };
1154
1155        variants.sort_by_key(|(idx, _)| *idx);
1156
1157        tcx.mk_adt_def(
1158            did,
1159            adt_kind,
1160            variants.into_iter().map(|(_, variant)| variant).collect(),
1161            repr,
1162        )
1163    }
1164
1165    fn get_visibility(&self, tcx: TyCtxt<'_>, id: DefIndex) -> Visibility<DefId> {
1166        self.root
1167            .tables
1168            .visibility
1169            .get(self, id)
1170            .unwrap_or_else(|| self.missing("visibility", id))
1171            .decode((self, tcx))
1172            .map_id(|index| self.local_def_id(index))
1173    }
1174
1175    fn get_safety(&self, id: DefIndex) -> Safety {
1176        self.root.tables.safety.get(self, id)
1177    }
1178
1179    fn get_default_field(&self, tcx: TyCtxt<'_>, id: DefIndex) -> Option<DefId> {
1180        self.root.tables.default_fields.get(self, id).map(|d| d.decode((self, tcx)))
1181    }
1182
1183    fn get_expn_that_defined(&self, tcx: TyCtxt<'_>, id: DefIndex) -> ExpnId {
1184        self.root
1185            .tables
1186            .expn_that_defined
1187            .get(self, id)
1188            .unwrap_or_else(|| self.missing("expn_that_defined", id))
1189            .decode((self, tcx))
1190    }
1191
1192    fn get_debugger_visualizers(&self, tcx: TyCtxt<'_>) -> Vec<DebuggerVisualizerFile> {
1193        self.root.debugger_visualizers.decode((self, tcx)).collect::<Vec<_>>()
1194    }
1195
1196    /// Iterates over all the stability attributes in the given crate.
1197    fn get_lib_features(&self, tcx: TyCtxt<'_>) -> LibFeatures {
1198        LibFeatures {
1199            stability: self
1200                .root
1201                .lib_features
1202                .decode((self, tcx))
1203                .map(|(sym, stab)| (sym, (stab, DUMMY_SP)))
1204                .collect(),
1205        }
1206    }
1207
1208    /// Iterates over the stability implications in the given crate (when a `#[unstable]` attribute
1209    /// has an `implied_by` meta item, then the mapping from the implied feature to the actual
1210    /// feature is a stability implication).
1211    fn get_stability_implications<'tcx>(&self, tcx: TyCtxt<'tcx>) -> &'tcx [(Symbol, Symbol)] {
1212        tcx.arena.alloc_from_iter(self.root.stability_implications.decode((self, tcx)))
1213    }
1214
1215    /// Iterates over the lang items in the given crate.
1216    fn get_lang_items<'tcx>(&self, tcx: TyCtxt<'tcx>) -> &'tcx [(DefId, LangItem)] {
1217        tcx.arena.alloc_from_iter(
1218            self.root
1219                .lang_items
1220                .decode((self, tcx))
1221                .map(move |(def_index, index)| (self.local_def_id(def_index), index)),
1222        )
1223    }
1224
1225    fn get_stripped_cfg_items<'tcx>(
1226        &self,
1227        tcx: TyCtxt<'tcx>,
1228        cnum: CrateNum,
1229    ) -> &'tcx [StrippedCfgItem] {
1230        let item_names = self
1231            .root
1232            .stripped_cfg_items
1233            .decode((self, tcx))
1234            .map(|item| item.map_scope_id(|index| DefId { krate: cnum, index }));
1235        tcx.arena.alloc_from_iter(item_names)
1236    }
1237
1238    /// Iterates over the diagnostic items in the given crate.
1239    fn get_diagnostic_items(&self, tcx: TyCtxt<'_>) -> DiagnosticItems {
1240        let mut id_to_name = DefIdMap::default();
1241        let name_to_id = self
1242            .root
1243            .diagnostic_items
1244            .decode((self, tcx))
1245            .map(|(name, def_index)| {
1246                let id = self.local_def_id(def_index);
1247                id_to_name.insert(id, name);
1248                (name, id)
1249            })
1250            .collect();
1251        DiagnosticItems { id_to_name, name_to_id }
1252    }
1253
1254    fn get_mod_child(&self, tcx: TyCtxt<'_>, id: DefIndex) -> ModChild {
1255        let ident = self.item_ident(tcx, id);
1256        let res = Res::Def(self.def_kind(id), self.local_def_id(id));
1257        let vis = self.get_visibility(tcx, id);
1258
1259        ModChild { ident, res, vis, reexport_chain: Default::default() }
1260    }
1261
1262    /// Iterates over all named children of the given module,
1263    /// including both proper items and reexports.
1264    /// Module here is understood in name resolution sense - it can be a `mod` item,
1265    /// or a crate root, or an enum, or a trait.
1266    fn get_module_children(&self, tcx: TyCtxt<'_>, id: DefIndex) -> impl Iterator<Item = ModChild> {
1267        gen move {
1268            if let Some(data) = &self.root.proc_macro_data {
1269                // If we are loading as a proc macro, we want to return
1270                // the view of this crate as a proc macro crate.
1271                if id == CRATE_DEF_INDEX {
1272                    for child_index in data.macros.decode((self, tcx)) {
1273                        yield self.get_mod_child(tcx, child_index);
1274                    }
1275                }
1276            } else {
1277                // Iterate over all children.
1278                let non_reexports = self.root.tables.module_children_non_reexports.get(self, id);
1279                for child_index in non_reexports.unwrap().decode((self, tcx)) {
1280                    yield self.get_mod_child(tcx, child_index);
1281                }
1282
1283                let reexports = self.root.tables.module_children_reexports.get(self, id);
1284                if !reexports.is_default() {
1285                    for reexport in reexports.decode((self, tcx)) {
1286                        yield reexport;
1287                    }
1288                }
1289            }
1290        }
1291    }
1292
1293    fn get_ambig_module_children(
1294        &self,
1295        tcx: TyCtxt<'_>,
1296        id: DefIndex,
1297    ) -> impl Iterator<Item = AmbigModChild> {
1298        gen move {
1299            let children = self.root.tables.ambig_module_children.get(self, id);
1300            if !children.is_default() {
1301                for child in children.decode((self, tcx)) {
1302                    yield child;
1303                }
1304            }
1305        }
1306    }
1307
1308    fn is_item_mir_available(&self, id: DefIndex) -> bool {
1309        self.root.tables.optimized_mir.get(self, id).is_some()
1310    }
1311
1312    fn get_fn_has_self_parameter(&self, tcx: TyCtxt<'_>, id: DefIndex) -> bool {
1313        self.root
1314            .tables
1315            .fn_arg_idents
1316            .get(self, id)
1317            .expect("argument names not encoded for a function")
1318            .decode((self, tcx))
1319            .nth(0)
1320            .is_some_and(|ident| #[allow(non_exhaustive_omitted_patterns)] match ident {
    Some(Ident { name: kw::SelfLower, .. }) => true,
    _ => false,
}matches!(ident, Some(Ident { name: kw::SelfLower, .. })))
1321    }
1322
1323    fn get_associated_item_or_field_def_ids(
1324        &self,
1325        tcx: TyCtxt<'_>,
1326        id: DefIndex,
1327    ) -> impl Iterator<Item = DefId> {
1328        self.root
1329            .tables
1330            .associated_item_or_field_def_ids
1331            .get(self, id)
1332            .unwrap_or_else(|| self.missing("associated_item_or_field_def_ids", id))
1333            .decode((self, tcx))
1334            .map(move |child_index| self.local_def_id(child_index))
1335    }
1336
1337    fn get_associated_item(&self, tcx: TyCtxt<'_>, id: DefIndex) -> ty::AssocItem {
1338        let kind = match self.def_kind(id) {
1339            DefKind::AssocConst { is_type_const } => {
1340                ty::AssocKind::Const { name: self.item_name(id), is_type_const }
1341            }
1342            DefKind::AssocFn => ty::AssocKind::Fn {
1343                name: self.item_name(id),
1344                has_self: self.get_fn_has_self_parameter(tcx, id),
1345            },
1346            DefKind::AssocTy => {
1347                let data = if let Some(rpitit_info) = self.root.tables.opt_rpitit_info.get(self, id)
1348                {
1349                    ty::AssocTypeData::Rpitit(rpitit_info.decode((self, tcx)))
1350                } else {
1351                    ty::AssocTypeData::Normal(self.item_name(id))
1352                };
1353                ty::AssocKind::Type { data }
1354            }
1355            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("cannot get associated-item of `{0:?}`",
        self.def_key(id)))bug!("cannot get associated-item of `{:?}`", self.def_key(id)),
1356        };
1357        let container = self.root.tables.assoc_container.get(self, id).unwrap().decode((self, tcx));
1358
1359        ty::AssocItem { kind, def_id: self.local_def_id(id), container }
1360    }
1361
1362    fn get_ctor(&self, tcx: TyCtxt<'_>, node_id: DefIndex) -> Option<(CtorKind, DefId)> {
1363        match self.def_kind(node_id) {
1364            DefKind::Struct | DefKind::Variant => {
1365                let vdata =
1366                    self.root.tables.variant_data.get(self, node_id).unwrap().decode((self, tcx));
1367                vdata.ctor.map(|(kind, index)| (kind, self.local_def_id(index)))
1368            }
1369            _ => None,
1370        }
1371    }
1372
1373    fn get_item_attrs(
1374        &self,
1375        tcx: TyCtxt<'_>,
1376        id: DefIndex,
1377    ) -> impl Iterator<Item = hir::Attribute> {
1378        self.root
1379            .tables
1380            .attributes
1381            .get(self, id)
1382            .unwrap_or_else(|| {
1383                // Structure and variant constructors don't have any attributes encoded for them,
1384                // but we assume that someone passing a constructor ID actually wants to look at
1385                // the attributes on the corresponding struct or variant.
1386                let def_key = self.def_key(id);
1387                match (&def_key.disambiguated_data.data, &DefPathData::Ctor) {
    (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!(def_key.disambiguated_data.data, DefPathData::Ctor);
1388                let parent_id = def_key.parent.expect("no parent for a constructor");
1389                self.root
1390                    .tables
1391                    .attributes
1392                    .get(self, parent_id)
1393                    .expect("no encoded attributes for a structure or variant")
1394            })
1395            .decode((self, tcx))
1396    }
1397
1398    fn get_inherent_implementations_for_type<'tcx>(
1399        &self,
1400        tcx: TyCtxt<'tcx>,
1401        id: DefIndex,
1402    ) -> &'tcx [DefId] {
1403        tcx.arena.alloc_from_iter(
1404            self.root
1405                .tables
1406                .inherent_impls
1407                .get(self, id)
1408                .decode((self, tcx))
1409                .map(|index| self.local_def_id(index)),
1410        )
1411    }
1412
1413    /// Decodes all traits in the crate (for rustdoc and rustc diagnostics).
1414    fn get_traits(&self, tcx: TyCtxt<'_>) -> impl Iterator<Item = DefId> {
1415        self.root.traits.decode((self, tcx)).map(move |index| self.local_def_id(index))
1416    }
1417
1418    /// Decodes all trait impls in the crate (for rustdoc).
1419    fn get_trait_impls(&self, tcx: TyCtxt<'_>) -> impl Iterator<Item = DefId> {
1420        self.trait_impls.values().flat_map(move |impls| {
1421            impls.decode((self, tcx)).map(move |(impl_index, _)| self.local_def_id(impl_index))
1422        })
1423    }
1424
1425    fn get_incoherent_impls<'tcx>(&self, tcx: TyCtxt<'tcx>, simp: SimplifiedType) -> &'tcx [DefId] {
1426        if let Some(impls) = self.incoherent_impls.get(&simp) {
1427            tcx.arena.alloc_from_iter(impls.decode((self, tcx)).map(|idx| self.local_def_id(idx)))
1428        } else {
1429            &[]
1430        }
1431    }
1432
1433    fn get_implementations_of_trait<'tcx>(
1434        &self,
1435        tcx: TyCtxt<'tcx>,
1436        trait_def_id: DefId,
1437    ) -> &'tcx [(DefId, Option<SimplifiedType>)] {
1438        if self.trait_impls.is_empty() {
1439            return &[];
1440        }
1441
1442        // Do a reverse lookup beforehand to avoid touching the crate_num
1443        // hash map in the loop below.
1444        let key = match self.reverse_translate_def_id(trait_def_id) {
1445            Some(def_id) => (def_id.krate.as_u32(), def_id.index),
1446            None => return &[],
1447        };
1448
1449        if let Some(impls) = self.trait_impls.get(&key) {
1450            tcx.arena.alloc_from_iter(
1451                impls
1452                    .decode((self, tcx))
1453                    .map(|(idx, simplified_self_ty)| (self.local_def_id(idx), simplified_self_ty)),
1454            )
1455        } else {
1456            &[]
1457        }
1458    }
1459
1460    fn get_native_libraries(&self, tcx: TyCtxt<'_>) -> impl Iterator<Item = NativeLib> {
1461        self.root.native_libraries.decode((self, tcx))
1462    }
1463
1464    fn get_proc_macro_quoted_span(&self, tcx: TyCtxt<'_>, index: usize) -> Span {
1465        self.root
1466            .tables
1467            .proc_macro_quoted_spans
1468            .get(self, index)
1469            .unwrap_or_else(|| {
    ::core::panicking::panic_fmt(format_args!("Missing proc macro quoted span: {0:?}",
            index));
}panic!("Missing proc macro quoted span: {index:?}"))
1470            .decode((self, tcx))
1471    }
1472
1473    fn get_foreign_modules(&self, tcx: TyCtxt<'_>) -> impl Iterator<Item = ForeignModule> {
1474        self.root.foreign_modules.decode((self, tcx))
1475    }
1476
1477    fn get_dylib_dependency_formats<'tcx>(
1478        &self,
1479        tcx: TyCtxt<'tcx>,
1480    ) -> &'tcx [(CrateNum, LinkagePreference)] {
1481        tcx.arena.alloc_from_iter(
1482            self.root.dylib_dependency_formats.decode((self, tcx)).enumerate().flat_map(
1483                |(i, link)| {
1484                    let cnum = CrateNum::new(i + 1); // We skipped LOCAL_CRATE when encoding
1485                    link.map(|link| (self.cnum_map[cnum], link))
1486                },
1487            ),
1488        )
1489    }
1490
1491    fn get_externally_implementable_items(
1492        &self,
1493        tcx: TyCtxt<'_>,
1494    ) -> impl Iterator<Item = EiiMapEncodedKeyValue> {
1495        self.root.externally_implementable_items.decode((self, tcx))
1496    }
1497
1498    fn get_missing_lang_items<'tcx>(&self, tcx: TyCtxt<'tcx>) -> &'tcx [LangItem] {
1499        tcx.arena.alloc_from_iter(self.root.lang_items_missing.decode((self, tcx)))
1500    }
1501
1502    fn get_exportable_items(&self, tcx: TyCtxt<'_>) -> impl Iterator<Item = DefId> {
1503        self.root.exportable_items.decode((self, tcx)).map(move |index| self.local_def_id(index))
1504    }
1505
1506    fn get_stable_order_of_exportable_impls(
1507        &self,
1508        tcx: TyCtxt<'_>,
1509    ) -> impl Iterator<Item = (DefId, usize)> {
1510        self.root
1511            .stable_order_of_exportable_impls
1512            .decode((self, tcx))
1513            .map(move |v| (self.local_def_id(v.0), v.1))
1514    }
1515
1516    fn exported_non_generic_symbols<'tcx>(
1517        &self,
1518        tcx: TyCtxt<'tcx>,
1519    ) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
1520        tcx.arena.alloc_from_iter(self.root.exported_non_generic_symbols.decode((self, tcx)))
1521    }
1522
1523    fn exported_generic_symbols<'tcx>(
1524        &self,
1525        tcx: TyCtxt<'tcx>,
1526    ) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
1527        tcx.arena.alloc_from_iter(self.root.exported_generic_symbols.decode((self, tcx)))
1528    }
1529
1530    fn get_macro(&self, tcx: TyCtxt<'_>, id: DefIndex) -> ast::MacroDef {
1531        match self.def_kind(id) {
1532            DefKind::Macro(_) => {
1533                let macro_rules = self.root.tables.is_macro_rules.get(self, id);
1534                let body =
1535                    self.root.tables.macro_definition.get(self, id).unwrap().decode((self, tcx));
1536                ast::MacroDef { macro_rules, body: Box::new(body), eii_declaration: None }
1537            }
1538            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
1539        }
1540    }
1541
1542    #[inline]
1543    fn def_key(&self, index: DefIndex) -> DefKey {
1544        *self.def_key_cache.lock().entry(index).or_insert_with(|| {
1545            self.root.tables.def_keys.get(&self.blob, index).unwrap().decode(&self.blob)
1546        })
1547    }
1548
1549    // Returns the path leading to the thing with this `id`.
1550    fn def_path(&self, id: DefIndex) -> DefPath {
1551        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/rmeta/decoder.rs:1551",
                        "rustc_metadata::rmeta::decoder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/decoder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1551u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::decoder"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("def_path(cnum={0:?}, id={1:?})",
                                                    self.cnum, id) as &dyn Value))])
            });
    } else { ; }
};debug!("def_path(cnum={:?}, id={:?})", self.cnum, id);
1552        DefPath::make(self.cnum, id, |parent| self.def_key(parent))
1553    }
1554
1555    #[inline]
1556    fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
1557        // This is a hack to workaround the fact that we can't easily encode/decode a Hash64
1558        // into the FixedSizeEncoding, as Hash64 lacks a Default impl. A future refactor to
1559        // relax the Default restriction will likely fix this.
1560        let fingerprint = Fingerprint::new(
1561            self.root.stable_crate_id.as_u64(),
1562            self.root.tables.def_path_hashes.get(&self.blob, index),
1563        );
1564        DefPathHash::new(self.root.stable_crate_id, fingerprint.split().1)
1565    }
1566
1567    #[inline]
1568    fn def_path_hash_to_def_index(&self, hash: DefPathHash) -> Option<DefIndex> {
1569        self.def_path_hash_map.def_path_hash_to_def_index(&hash)
1570    }
1571
1572    fn expn_hash_to_expn_id(&self, tcx: TyCtxt<'_>, index_guess: u32, hash: ExpnHash) -> ExpnId {
1573        let index_guess = ExpnIndex::from_u32(index_guess);
1574        let old_hash =
1575            self.root.expn_hashes.get(self, index_guess).map(|lazy| lazy.decode((self, tcx)));
1576
1577        let index = if old_hash == Some(hash) {
1578            // Fast path: the expn and its index is unchanged from the
1579            // previous compilation session. There is no need to decode anything
1580            // else.
1581            index_guess
1582        } else {
1583            // Slow path: We need to find out the new `DefIndex` of the provided
1584            // `DefPathHash`, if its still exists. This requires decoding every `DefPathHash`
1585            // stored in this crate.
1586            let map = self.expn_hash_map.get_or_init(|| {
1587                let end_id = self.root.expn_hashes.size() as u32;
1588                let mut map =
1589                    UnhashMap::with_capacity_and_hasher(end_id as usize, Default::default());
1590                for i in 0..end_id {
1591                    let i = ExpnIndex::from_u32(i);
1592                    if let Some(hash) = self.root.expn_hashes.get(self, i) {
1593                        map.insert(hash.decode((self, tcx)), i);
1594                    }
1595                }
1596                map
1597            });
1598            map[&hash]
1599        };
1600
1601        let data = self.root.expn_data.get(self, index).unwrap().decode((self, tcx));
1602        rustc_span::hygiene::register_expn_id(self.cnum, index, data, hash)
1603    }
1604
1605    /// Imports the source_map from an external crate into the source_map of the crate
1606    /// currently being compiled (the "local crate").
1607    ///
1608    /// The import algorithm works analogous to how AST items are inlined from an
1609    /// external crate's metadata:
1610    /// For every SourceFile in the external source_map an 'inline' copy is created in the
1611    /// local source_map. The correspondence relation between external and local
1612    /// SourceFiles is recorded in the `ImportedSourceFile` objects returned from this
1613    /// function. When an item from an external crate is later inlined into this
1614    /// crate, this correspondence information is used to translate the span
1615    /// information of the inlined item so that it refers the correct positions in
1616    /// the local source_map (see `<decoder::DecodeContext as SpecializedDecoder<Span>>`).
1617    ///
1618    /// The import algorithm in the function below will reuse SourceFiles already
1619    /// existing in the local source_map. For example, even if the SourceFile of some
1620    /// source file of libstd gets imported many times, there will only ever be
1621    /// one SourceFile object for the corresponding file in the local source_map.
1622    ///
1623    /// Note that imported SourceFiles do not actually contain the source code of the
1624    /// file they represent, just information about length, line breaks, and
1625    /// multibyte characters. This information is enough to generate valid debuginfo
1626    /// for items inlined from other crates.
1627    ///
1628    /// Proc macro crates don't currently export spans, so this function does not have
1629    /// to work for them.
1630    fn imported_source_file(&self, tcx: TyCtxt<'_>, source_file_index: u32) -> ImportedSourceFile {
1631        fn filter<'a>(
1632            tcx: TyCtxt<'_>,
1633            real_source_base_dir: &Option<PathBuf>,
1634            path: Option<&'a Path>,
1635        ) -> Option<&'a Path> {
1636            path.filter(|_| {
1637                // Only spend time on further checks if we have what to translate *to*.
1638                real_source_base_dir.is_some()
1639                // Some tests need the translation to be always skipped.
1640                && tcx.sess.opts.unstable_opts.translate_remapped_path_to_local_path
1641            })
1642            .filter(|virtual_dir| {
1643                // Don't translate away `/rustc/$hash` if we're still remapping to it,
1644                // since that means we're still building `std`/`rustc` that need it,
1645                // and we don't want the real path to leak into codegen/debuginfo.
1646                !tcx.sess.opts.remap_path_prefix.iter().any(|(_from, to)| to == virtual_dir)
1647            })
1648        }
1649
1650        let try_to_translate_virtual_to_real =
1651            |virtual_source_base_dir: Option<&str>,
1652             real_source_base_dir: &Option<PathBuf>,
1653             name: &mut rustc_span::FileName| {
1654                let virtual_source_base_dir = [
1655                    filter(tcx, real_source_base_dir, virtual_source_base_dir.map(Path::new)),
1656                    filter(
1657                        tcx,
1658                        real_source_base_dir,
1659                        tcx.sess.opts.unstable_opts.simulate_remapped_rust_src_base.as_deref(),
1660                    ),
1661                ];
1662
1663                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/rmeta/decoder.rs:1663",
                        "rustc_metadata::rmeta::decoder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/decoder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1663u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::decoder"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("try_to_translate_virtual_to_real(name={0:?}): virtual_source_base_dir={1:?}, real_source_base_dir={2:?}",
                                                    name, virtual_source_base_dir, real_source_base_dir) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(
1664                    "try_to_translate_virtual_to_real(name={:?}): \
1665                     virtual_source_base_dir={:?}, real_source_base_dir={:?}",
1666                    name, virtual_source_base_dir, real_source_base_dir,
1667                );
1668
1669                for virtual_dir in virtual_source_base_dir.iter().flatten() {
1670                    if let Some(real_dir) = &real_source_base_dir
1671                        && let rustc_span::FileName::Real(old_name) = name
1672                        && let virtual_path = old_name.path(RemapPathScopeComponents::MACRO)
1673                        && let Ok(rest) = virtual_path.strip_prefix(virtual_dir)
1674                    {
1675                        let new_path = real_dir.join(rest);
1676
1677                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/rmeta/decoder.rs:1677",
                        "rustc_metadata::rmeta::decoder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/decoder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1677u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::decoder"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("try_to_translate_virtual_to_real: `{0}` -> `{1}`",
                                                    virtual_path.display(), new_path.display()) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(
1678                            "try_to_translate_virtual_to_real: `{}` -> `{}`",
1679                            virtual_path.display(),
1680                            new_path.display(),
1681                        );
1682
1683                        // Check if the translated real path is affected by any user-requested
1684                        // remaps via --remap-path-prefix. Apply them if so.
1685                        // Note that this is a special case for imported rust-src paths specified by
1686                        // https://rust-lang.github.io/rfcs/3127-trim-paths.html#handling-sysroot-paths.
1687                        // Other imported paths are not currently remapped (see #66251).
1688                        *name = rustc_span::FileName::Real(
1689                            tcx.sess
1690                                .source_map()
1691                                .path_mapping()
1692                                .to_real_filename(&rustc_span::RealFileName::empty(), new_path),
1693                        );
1694                    }
1695                }
1696            };
1697
1698        let try_to_translate_real_to_virtual =
1699            |virtual_source_base_dir: Option<&str>,
1700             real_source_base_dir: &Option<PathBuf>,
1701             subdir: &str,
1702             name: &mut rustc_span::FileName| {
1703                if let Some(virtual_dir) =
1704                    &tcx.sess.opts.unstable_opts.simulate_remapped_rust_src_base
1705                    && let Some(real_dir) = real_source_base_dir
1706                    && let rustc_span::FileName::Real(old_name) = name
1707                {
1708                    let (_working_dir, embeddable_path) =
1709                        old_name.embeddable_name(RemapPathScopeComponents::MACRO);
1710                    let relative_path = embeddable_path.strip_prefix(real_dir).ok().or_else(|| {
1711                        virtual_source_base_dir
1712                            .and_then(|virtual_dir| embeddable_path.strip_prefix(virtual_dir).ok())
1713                    });
1714                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/rmeta/decoder.rs:1714",
                        "rustc_metadata::rmeta::decoder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/decoder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1714u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::decoder"),
                        ::tracing_core::field::FieldSet::new(&["message",
                                        "relative_path", "virtual_dir", "subdir"],
                            ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("simulate_remapped_rust_src_base")
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&relative_path)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&virtual_dir)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&subdir) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(
1715                        ?relative_path,
1716                        ?virtual_dir,
1717                        ?subdir,
1718                        "simulate_remapped_rust_src_base"
1719                    );
1720                    if let Some(rest) = relative_path.and_then(|p| p.strip_prefix(subdir).ok()) {
1721                        *name =
1722                            rustc_span::FileName::Real(rustc_span::RealFileName::from_virtual_path(
1723                                &virtual_dir.join(subdir).join(rest),
1724                            ))
1725                    }
1726                }
1727            };
1728
1729        let mut import_info = self.source_map_import_info.lock();
1730        for _ in import_info.len()..=(source_file_index as usize) {
1731            import_info.push(None);
1732        }
1733        import_info[source_file_index as usize]
1734            .get_or_insert_with(|| {
1735                let source_file_to_import = self
1736                    .root
1737                    .source_map
1738                    .get(self, source_file_index)
1739                    .expect("missing source file")
1740                    .decode((self, tcx));
1741
1742                // We can't reuse an existing SourceFile, so allocate a new one
1743                // containing the information we need.
1744                let original_end_pos = source_file_to_import.end_position();
1745                let rustc_span::SourceFile {
1746                    mut name,
1747                    src_hash,
1748                    checksum_hash,
1749                    start_pos: original_start_pos,
1750                    normalized_source_len,
1751                    unnormalized_source_len,
1752                    lines,
1753                    multibyte_chars,
1754                    normalized_pos,
1755                    stable_id,
1756                    ..
1757                } = source_file_to_import;
1758
1759                // If this file is under $sysroot/lib/rustlib/src/
1760                // and the user wish to simulate remapping with -Z simulate-remapped-rust-src-base,
1761                // then we change `name` to a similar state as if the rust was bootstrapped
1762                // with `remap-debuginfo = true`.
1763                // This is useful for testing so that tests about the effects of
1764                // `try_to_translate_virtual_to_real` don't have to worry about how the
1765                // compiler is bootstrapped.
1766                try_to_translate_real_to_virtual(
1767                    ::core::option::Option::Some("/rustc/20de910db49d3476ccf49ea79a4b22e2b5dface0")option_env!("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR"),
1768                    &tcx.sess.opts.real_rust_source_base_dir,
1769                    "library",
1770                    &mut name,
1771                );
1772
1773                // If this file is under $sysroot/lib/rustlib/rustc-src/
1774                // and the user wish to simulate remapping with -Z simulate-remapped-rust-src-base,
1775                // then we change `name` to a similar state as if the rust was bootstrapped
1776                // with `remap-debuginfo = true`.
1777                try_to_translate_real_to_virtual(
1778                    ::core::option::Option::Some("/rustc-dev/20de910db49d3476ccf49ea79a4b22e2b5dface0")option_env!("CFG_VIRTUAL_RUSTC_DEV_SOURCE_BASE_DIR"),
1779                    &tcx.sess.opts.real_rustc_dev_source_base_dir,
1780                    "compiler",
1781                    &mut name,
1782                );
1783
1784                // If this file's path has been remapped to `/rustc/$hash`,
1785                // we might be able to reverse that.
1786                //
1787                // NOTE: if you update this, you might need to also update bootstrap's code for generating
1788                // the `rust-src` component in `Src::run` in `src/bootstrap/dist.rs`.
1789                try_to_translate_virtual_to_real(
1790                    ::core::option::Option::Some("/rustc/20de910db49d3476ccf49ea79a4b22e2b5dface0")option_env!("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR"),
1791                    &tcx.sess.opts.real_rust_source_base_dir,
1792                    &mut name,
1793                );
1794
1795                // If this file's path has been remapped to `/rustc-dev/$hash`,
1796                // we might be able to reverse that.
1797                //
1798                // NOTE: if you update this, you might need to also update bootstrap's code for generating
1799                // the `rustc-dev` component in `Src::run` in `src/bootstrap/dist.rs`.
1800                try_to_translate_virtual_to_real(
1801                    ::core::option::Option::Some("/rustc-dev/20de910db49d3476ccf49ea79a4b22e2b5dface0")option_env!("CFG_VIRTUAL_RUSTC_DEV_SOURCE_BASE_DIR"),
1802                    &tcx.sess.opts.real_rustc_dev_source_base_dir,
1803                    &mut name,
1804                );
1805
1806                let local_version = tcx.sess.source_map().new_imported_source_file(
1807                    name,
1808                    src_hash,
1809                    checksum_hash,
1810                    stable_id,
1811                    normalized_source_len.to_u32(),
1812                    unnormalized_source_len,
1813                    self.cnum,
1814                    lines,
1815                    multibyte_chars,
1816                    normalized_pos,
1817                    source_file_index,
1818                );
1819                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/rmeta/decoder.rs:1819",
                        "rustc_metadata::rmeta::decoder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/decoder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1819u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::decoder"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("CrateMetaData::imported_source_files alloc source_file {0:?} original (start_pos {1:?} source_len {2:?}) translated (start_pos {3:?} source_len {4:?})",
                                                    local_version.name, original_start_pos,
                                                    normalized_source_len, local_version.start_pos,
                                                    local_version.normalized_source_len) as &dyn Value))])
            });
    } else { ; }
};debug!(
1820                    "CrateMetaData::imported_source_files alloc \
1821                         source_file {:?} original (start_pos {:?} source_len {:?}) \
1822                         translated (start_pos {:?} source_len {:?})",
1823                    local_version.name,
1824                    original_start_pos,
1825                    normalized_source_len,
1826                    local_version.start_pos,
1827                    local_version.normalized_source_len
1828                );
1829
1830                ImportedSourceFile {
1831                    original_start_pos,
1832                    original_end_pos,
1833                    translated_source_file: local_version,
1834                }
1835            })
1836            .clone()
1837    }
1838
1839    fn get_attr_flags(&self, index: DefIndex) -> AttrFlags {
1840        self.root.tables.attr_flags.get(self, index)
1841    }
1842
1843    fn get_intrinsic(&self, tcx: TyCtxt<'_>, index: DefIndex) -> Option<ty::IntrinsicDef> {
1844        self.root.tables.intrinsic.get(self, index).map(|d| d.decode((self, tcx)))
1845    }
1846
1847    fn get_doc_link_resolutions(&self, tcx: TyCtxt<'_>, index: DefIndex) -> DocLinkResMap {
1848        self.root
1849            .tables
1850            .doc_link_resolutions
1851            .get(self, index)
1852            .expect("no resolutions for a doc link")
1853            .decode((self, tcx))
1854    }
1855
1856    fn get_doc_link_traits_in_scope(
1857        &self,
1858        tcx: TyCtxt<'_>,
1859        index: DefIndex,
1860    ) -> impl Iterator<Item = DefId> {
1861        self.root
1862            .tables
1863            .doc_link_traits_in_scope
1864            .get(self, index)
1865            .expect("no traits in scope for a doc link")
1866            .decode((self, tcx))
1867    }
1868}
1869
1870impl CrateMetadata {
1871    pub(crate) fn new(
1872        tcx: TyCtxt<'_>,
1873        blob: MetadataBlob,
1874        root: CrateRoot,
1875        raw_proc_macros: Option<&'static [ProcMacro]>,
1876        cnum: CrateNum,
1877        cnum_map: CrateNumMap,
1878        dep_kind: CrateDepKind,
1879        source: CrateSource,
1880        private_dep: bool,
1881        host_hash: Option<Svh>,
1882    ) -> CrateMetadata {
1883        let trait_impls = root
1884            .impls
1885            .decode(&blob)
1886            .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
1887            .collect();
1888        let alloc_decoding_state =
1889            AllocDecodingState::new(root.interpret_alloc_index.decode(&blob).collect());
1890
1891        // Pre-decode the DefPathHash->DefIndex table. This is a cheap operation
1892        // that does not copy any data. It just does some data verification.
1893        let def_path_hash_map = root.def_path_hash_map.decode(&blob);
1894
1895        let mut cdata = CrateMetadata {
1896            blob,
1897            root,
1898            trait_impls,
1899            incoherent_impls: Default::default(),
1900            raw_proc_macros,
1901            source_map_import_info: Lock::new(Vec::new()),
1902            def_path_hash_map,
1903            expn_hash_map: Default::default(),
1904            alloc_decoding_state,
1905            cnum,
1906            cnum_map,
1907            dep_kind,
1908            source: Arc::new(source),
1909            private_dep,
1910            host_hash,
1911            used: false,
1912            extern_crate: None,
1913            hygiene_context: Default::default(),
1914            def_key_cache: Default::default(),
1915        };
1916
1917        cdata.incoherent_impls = cdata
1918            .root
1919            .incoherent_impls
1920            .decode((&cdata, tcx))
1921            .map(|incoherent_impls| {
1922                (incoherent_impls.self_ty.decode((&cdata, tcx)), incoherent_impls.impls)
1923            })
1924            .collect();
1925
1926        cdata
1927    }
1928
1929    pub(crate) fn dependencies(&self) -> impl Iterator<Item = CrateNum> {
1930        self.cnum_map.iter().copied()
1931    }
1932
1933    pub(crate) fn target_modifiers(&self) -> TargetModifiers {
1934        self.root.decode_target_modifiers(&self.blob).collect()
1935    }
1936
1937    pub(crate) fn enabled_denied_partial_mitigations(&self) -> DeniedPartialMitigations {
1938        self.root.decode_denied_partial_mitigations(&self.blob).collect()
1939    }
1940
1941    /// Keep `new_extern_crate` if it looks better in diagnostics
1942    pub(crate) fn update_extern_crate_diagnostics(
1943        &mut self,
1944        new_extern_crate: ExternCrate,
1945    ) -> bool {
1946        let update =
1947            self.extern_crate.as_ref().is_none_or(|old| old.rank() < new_extern_crate.rank());
1948        if update {
1949            self.extern_crate = Some(new_extern_crate);
1950        }
1951        update
1952    }
1953
1954    pub(crate) fn source(&self) -> &CrateSource {
1955        &*self.source
1956    }
1957
1958    pub(crate) fn dep_kind(&self) -> CrateDepKind {
1959        self.dep_kind
1960    }
1961
1962    pub(crate) fn set_dep_kind(&mut self, dep_kind: CrateDepKind) {
1963        self.dep_kind = dep_kind;
1964    }
1965
1966    pub(crate) fn update_and_private_dep(&mut self, private_dep: bool) {
1967        self.private_dep &= private_dep;
1968    }
1969
1970    pub(crate) fn used(&self) -> bool {
1971        self.used
1972    }
1973
1974    pub(crate) fn required_panic_strategy(&self) -> Option<PanicStrategy> {
1975        self.root.required_panic_strategy
1976    }
1977
1978    pub(crate) fn needs_panic_runtime(&self) -> bool {
1979        self.root.needs_panic_runtime
1980    }
1981
1982    pub(crate) fn is_private_dep(&self) -> bool {
1983        self.private_dep
1984    }
1985
1986    pub(crate) fn is_panic_runtime(&self) -> bool {
1987        self.root.panic_runtime
1988    }
1989
1990    pub(crate) fn is_profiler_runtime(&self) -> bool {
1991        self.root.profiler_runtime
1992    }
1993
1994    pub(crate) fn is_compiler_builtins(&self) -> bool {
1995        self.root.compiler_builtins
1996    }
1997
1998    pub(crate) fn needs_allocator(&self) -> bool {
1999        self.root.needs_allocator
2000    }
2001
2002    pub(crate) fn has_global_allocator(&self) -> bool {
2003        self.root.has_global_allocator
2004    }
2005
2006    pub(crate) fn has_alloc_error_handler(&self) -> bool {
2007        self.root.has_alloc_error_handler
2008    }
2009
2010    pub(crate) fn has_default_lib_allocator(&self) -> bool {
2011        self.root.has_default_lib_allocator
2012    }
2013
2014    pub(crate) fn is_proc_macro_crate(&self) -> bool {
2015        self.root.is_proc_macro_crate()
2016    }
2017
2018    pub(crate) fn proc_macros_for_crate(
2019        &self,
2020        tcx: TyCtxt<'_>,
2021        krate: CrateNum,
2022    ) -> impl Iterator<Item = DefId> {
2023        gen move {
2024            for def_id in self.root.proc_macro_data.as_ref().into_iter().flat_map(move |data| {
2025                data.macros.decode((self, tcx)).map(move |index| DefId { index, krate })
2026            }) {
2027                yield def_id;
2028            }
2029        }
2030    }
2031
2032    pub(crate) fn name(&self) -> Symbol {
2033        self.root.header.name
2034    }
2035
2036    pub(crate) fn hash(&self) -> Svh {
2037        self.root.header.hash
2038    }
2039
2040    pub(crate) fn has_async_drops(&self) -> bool {
2041        self.root.tables.adt_async_destructor.len > 0
2042    }
2043
2044    fn num_def_ids(&self) -> usize {
2045        self.root.tables.def_keys.size()
2046    }
2047
2048    fn local_def_id(&self, index: DefIndex) -> DefId {
2049        DefId { krate: self.cnum, index }
2050    }
2051
2052    // Translate a DefId from the current compilation environment to a DefId
2053    // for an external crate.
2054    fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
2055        for (local, &global) in self.cnum_map.iter_enumerated() {
2056            if global == did.krate {
2057                return Some(DefId { krate: local, index: did.index });
2058            }
2059        }
2060
2061        None
2062    }
2063}