Skip to main content

rustc_metadata/rmeta/
decoder.rs

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