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