Skip to main content

rustc_metadata/rmeta/
encoder.rs

1use std::borrow::Borrow;
2use std::cell::RefCell;
3use std::collections::hash_map::Entry;
4use std::fs::File;
5use std::io::{Read, Seek, Write};
6use std::path::{Path, PathBuf};
7use std::rc::Rc;
8use std::sync::Arc;
9
10use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
11use rustc_data_structures::memmap::{Mmap, MmapMut};
12use rustc_data_structures::sync::{par_for_each_in, par_join};
13use rustc_data_structures::temp_dir::MaybeTempDir;
14use rustc_data_structures::thousands::usize_with_underscores;
15use rustc_hir as hir;
16use rustc_hir::attrs::{AttributeKind, EncodeCrossCrate};
17use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE, LocalDefId, LocalDefIdSet};
18use rustc_hir::definitions::DefPathData;
19use rustc_hir::find_attr;
20use rustc_hir_pretty::id_to_string;
21use rustc_middle::dep_graph::WorkProductId;
22use rustc_middle::middle::dependency_format::Linkage;
23use rustc_middle::mir::interpret;
24use rustc_middle::query::Providers;
25use rustc_middle::traits::specialization_graph;
26use rustc_middle::ty::AssocContainer;
27use rustc_middle::ty::codec::TyEncoder;
28use rustc_middle::ty::fast_reject::{self, TreatParams};
29use rustc_serialize::{Decodable, Decoder, Encodable, Encoder, opaque};
30use rustc_session::config::mitigation_coverage::DeniedPartialMitigation;
31use rustc_session::config::{OptLevel, TargetModifier};
32use rustc_span::def_id::CRATE_MOD_ID;
33use rustc_span::hygiene::HygieneEncodeContext;
34use rustc_span::{
35    ByteSymbol, ExternalSource, FileName, SourceFile, SpanData, SpanEncoder, StableSourceFileId,
36    Symbol, SyntaxContext, bug, span_bug, sym,
37};
38use rustc_structures::CrateType;
39use tracing::{debug, instrument, trace};
40
41use crate::diagnostics::{FailCreateFileEncoder, FailWriteFile};
42use crate::eii::EiiMapEncodedKeyValue;
43use crate::rmeta::*;
44
45pub(super) struct EncodeContext<'a, 'tcx> {
46    opaque: opaque::FileEncoder<'a>,
47    tcx: TyCtxt<'tcx>,
48    feat: &'tcx rustc_feature::Features,
49    tables: TableBuilders,
50
51    lazy_state: LazyState,
52    span_shorthands: FxHashMap<Span, usize>,
53    type_shorthands: FxHashMap<Ty<'tcx>, usize>,
54    predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
55
56    interpret_allocs: FxIndexSet<interpret::AllocId>,
57
58    // This is used to speed up Span encoding.
59    // The `usize` is an index into the `MonotonicVec`
60    // that stores the `SourceFile`
61    source_file_cache: (Arc<SourceFile>, usize),
62    // The indices (into the `SourceMap`'s `MonotonicVec`)
63    // of all of the `SourceFiles` that we need to serialize.
64    // When we serialize a `Span`, we insert the index of its
65    // `SourceFile` into the `FxIndexSet`.
66    // The order inside the `FxIndexSet` is used as on-disk
67    // order of `SourceFiles`, and encoded inside `Span`s.
68    required_source_files: Option<FxIndexSet<usize>>,
69    is_proc_macro: bool,
70    hygiene_ctxt: Rc<RefCell<HygieneEncodeContext>>,
71    // Used for both `Symbol`s and `ByteSymbol`s.
72    symbol_index_table: FxHashMap<u32, usize>,
73}
74
75/// If the current crate is a proc-macro, returns early with `LazyArray::default()`.
76/// This is useful for skipping the encoding of things that aren't needed
77/// for proc-macro crates.
78macro_rules! empty_proc_macro {
79    ($self:ident) => {
80        if $self.is_proc_macro {
81            return LazyArray::default();
82        }
83    };
84}
85
86macro_rules! encoder_methods {
87    ($($name:ident($ty:ty);)*) => {
88        $(fn $name(&mut self, value: $ty) {
89            self.opaque.$name(value)
90        })*
91    }
92}
93
94impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
95    fn emit_usize(&mut self, value: usize) { self.opaque.emit_usize(value) }
fn emit_u128(&mut self, value: u128) { self.opaque.emit_u128(value) }
fn emit_u64(&mut self, value: u64) { self.opaque.emit_u64(value) }
fn emit_u32(&mut self, value: u32) { self.opaque.emit_u32(value) }
fn emit_u16(&mut self, value: u16) { self.opaque.emit_u16(value) }
fn emit_u8(&mut self, value: u8) { self.opaque.emit_u8(value) }
fn emit_isize(&mut self, value: isize) { self.opaque.emit_isize(value) }
fn emit_i128(&mut self, value: i128) { self.opaque.emit_i128(value) }
fn emit_i64(&mut self, value: i64) { self.opaque.emit_i64(value) }
fn emit_i32(&mut self, value: i32) { self.opaque.emit_i32(value) }
fn emit_i16(&mut self, value: i16) { self.opaque.emit_i16(value) }
fn emit_raw_bytes(&mut self, value: &[u8]) {
    self.opaque.emit_raw_bytes(value)
}encoder_methods! {
96        emit_usize(usize);
97        emit_u128(u128);
98        emit_u64(u64);
99        emit_u32(u32);
100        emit_u16(u16);
101        emit_u8(u8);
102
103        emit_isize(isize);
104        emit_i128(i128);
105        emit_i64(i64);
106        emit_i32(i32);
107        emit_i16(i16);
108
109        emit_raw_bytes(&[u8]);
110    }
111}
112
113impl<'a, 'tcx, T> Encodable<EncodeContext<'a, 'tcx>> for LazyValue<T> {
114    fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
115        e.emit_lazy_distance(self.position);
116    }
117}
118
119impl<'a, 'tcx, T> Encodable<EncodeContext<'a, 'tcx>> for LazyArray<T> {
120    fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
121        e.emit_usize(self.num_elems);
122        if self.num_elems > 0 {
123            e.emit_lazy_distance(self.position)
124        }
125    }
126}
127
128impl<'a, 'tcx, I, T> Encodable<EncodeContext<'a, 'tcx>> for LazyTable<I, T> {
129    fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
130        e.emit_usize(self.width);
131        e.emit_usize(self.len);
132        e.emit_lazy_distance(self.position);
133    }
134}
135
136impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnIndex {
137    fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
138        s.emit_u32(self.as_u32());
139    }
140}
141
142impl<'a, 'tcx> SpanEncoder for EncodeContext<'a, 'tcx> {
143    fn encode_crate_num(&mut self, crate_num: CrateNum) {
144        if crate_num != LOCAL_CRATE && self.is_proc_macro {
145            {
    ::core::panicking::panic_fmt(format_args!("Attempted to encode non-local CrateNum {0:?} for proc-macro crate",
            crate_num));
};panic!("Attempted to encode non-local CrateNum {crate_num:?} for proc-macro crate");
146        }
147        self.emit_u32(crate_num.as_u32());
148    }
149
150    fn encode_def_index(&mut self, def_index: DefIndex) {
151        self.emit_u32(def_index.as_u32());
152    }
153
154    fn encode_def_id(&mut self, def_id: DefId) {
155        def_id.krate.encode(self);
156        def_id.index.encode(self);
157    }
158
159    fn encode_syntax_context(&mut self, syntax_context: SyntaxContext) {
160        let idx = self.hygiene_ctxt.borrow_mut().get_syntax_ctxt_encoding_index(syntax_context);
161        idx.encode(self);
162    }
163
164    fn encode_expn_id(&mut self, expn_id: ExpnId) {
165        if expn_id.krate == LOCAL_CRATE {
166            // We will only write details for local expansions. Non-local expansions will fetch
167            // data from the corresponding crate's metadata.
168            // FIXME(#43047) FIXME(#74731) We may eventually want to avoid relying on external
169            // metadata from proc-macro crates.
170            self.hygiene_ctxt.borrow_mut().schedule_expn_data_for_encoding(expn_id);
171        }
172        expn_id.krate.encode(self);
173        expn_id.local_id.encode(self);
174    }
175
176    fn encode_span(&mut self, span: Span) {
177        match self.span_shorthands.entry(span) {
178            Entry::Occupied(o) => {
179                // If an offset is smaller than the absolute position, we encode with the offset.
180                // This saves space since smaller numbers encode in less bits.
181                let last_location = *o.get();
182                // This cannot underflow. Metadata is written with increasing position(), so any
183                // previously saved offset must be smaller than the current position.
184                let offset = self.opaque.position() - last_location;
185                if offset < last_location {
186                    let needed = bytes_needed(offset);
187                    SpanTag::indirect(true, needed as u8).encode(self);
188                    self.opaque.write_with(|dest| {
189                        *dest = offset.to_le_bytes();
190                        needed
191                    });
192                } else {
193                    let needed = bytes_needed(last_location);
194                    SpanTag::indirect(false, needed as u8).encode(self);
195                    self.opaque.write_with(|dest| {
196                        *dest = last_location.to_le_bytes();
197                        needed
198                    });
199                }
200            }
201            Entry::Vacant(v) => {
202                let position = self.opaque.position();
203                v.insert(position);
204                // Data is encoded with a SpanTag prefix (see below).
205                span.data().encode(self);
206            }
207        }
208    }
209
210    fn encode_symbol(&mut self, sym: Symbol) {
211        self.encode_symbol_or_byte_symbol(sym.as_u32(), |this| this.emit_str(sym.as_str()));
212    }
213
214    fn encode_byte_symbol(&mut self, byte_sym: ByteSymbol) {
215        self.encode_symbol_or_byte_symbol(byte_sym.as_u32(), |this| {
216            this.emit_byte_str(byte_sym.as_byte_str())
217        });
218    }
219}
220
221fn bytes_needed(n: usize) -> usize {
222    (usize::BITS - n.leading_zeros()).div_ceil(u8::BITS) as usize
223}
224
225impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for SpanData {
226    fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
227        // Don't serialize any `SyntaxContext`s from a proc-macro crate,
228        // since we don't load proc-macro dependencies during serialization.
229        // This means that any hygiene information from macros used *within*
230        // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro
231        // definition) will be lost.
232        //
233        // This can show up in two ways:
234        //
235        // 1. Any hygiene information associated with identifier of
236        // a proc macro (e.g. `#[proc_macro] pub fn $name`) will be lost.
237        // Since proc-macros can only be invoked from a different crate,
238        // real code should never need to care about this.
239        //
240        // 2. Using `Span::def_site` or `Span::mixed_site` will not
241        // include any hygiene information associated with the definition
242        // site. This means that a proc-macro cannot emit a `$crate`
243        // identifier which resolves to one of its dependencies,
244        // which also should never come up in practice.
245        //
246        // Additionally, this affects `Span::parent`, and any other
247        // span inspection APIs that would otherwise allow traversing
248        // the `SyntaxContexts` associated with a span.
249        //
250        // None of these user-visible effects should result in any
251        // cross-crate inconsistencies (getting one behavior in the same
252        // crate, and a different behavior in another crate) due to the
253        // limited surface that proc-macros can expose.
254        //
255        // IMPORTANT: If this is ever changed, be sure to update
256        // `rustc_span::hygiene::raw_encode_expn_id` to handle
257        // encoding `ExpnData` for proc-macro crates.
258        let ctxt = if s.is_proc_macro { SyntaxContext::root() } else { self.ctxt };
259
260        if self.is_dummy() {
261            let tag = SpanTag::new(SpanKind::Partial, ctxt, 0);
262            tag.encode(s);
263            if tag.context().is_none() {
264                ctxt.encode(s);
265            }
266            return;
267        }
268
269        // The Span infrastructure should make sure that this invariant holds:
270        if true {
    if !(self.lo <= self.hi) {
        ::core::panicking::panic("assertion failed: self.lo <= self.hi")
    };
};debug_assert!(self.lo <= self.hi);
271
272        if !s.source_file_cache.0.contains(self.lo) {
273            let source_map = s.tcx.sess.source_map();
274            let source_file_index = source_map.lookup_source_file_idx(self.lo);
275            s.source_file_cache =
276                (Arc::clone(&source_map.files()[source_file_index]), source_file_index);
277        }
278        let (ref source_file, source_file_index) = s.source_file_cache;
279        if true {
    if !source_file.contains(self.lo) {
        ::core::panicking::panic("assertion failed: source_file.contains(self.lo)")
    };
};debug_assert!(source_file.contains(self.lo));
280
281        if !source_file.contains(self.hi) {
282            // Unfortunately, macro expansion still sometimes generates Spans
283            // that malformed in this way.
284            let tag = SpanTag::new(SpanKind::Partial, ctxt, 0);
285            tag.encode(s);
286            if tag.context().is_none() {
287                ctxt.encode(s);
288            }
289            return;
290        }
291
292        // There are two possible cases here:
293        // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the
294        // crate we are writing metadata for. When the metadata for *this* crate gets
295        // deserialized, the deserializer will need to know which crate it originally came
296        // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should
297        // be deserialized after the rest of the span data, which tells the deserializer
298        // which crate contains the source map information.
299        // 2. This span comes from our own crate. No special handling is needed - we just
300        // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use
301        // our own source map information.
302        //
303        // If we're a proc-macro crate, we always treat this as a local `Span`.
304        // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata
305        // if we're a proc-macro crate.
306        // This allows us to avoid loading the dependencies of proc-macro crates: all of
307        // the information we need to decode `Span`s is stored in the proc-macro crate.
308        let (kind, metadata_index) = if source_file.is_imported() && !s.is_proc_macro {
309            // To simplify deserialization, we 'rebase' this span onto the crate it originally came
310            // from (the crate that 'owns' the file it references. These rebased 'lo' and 'hi'
311            // values are relative to the source map information for the 'foreign' crate whose
312            // CrateNum we write into the metadata. This allows `imported_source_files` to binary
313            // search through the 'foreign' crate's source map information, using the
314            // deserialized 'lo' and 'hi' values directly.
315            //
316            // All of this logic ensures that the final result of deserialization is a 'normal'
317            // Span that can be used without any additional trouble.
318            let metadata_index = {
319                // Introduce a new scope so that we drop the 'read()' temporary
320                match &*source_file.external_src.read() {
321                    ExternalSource::Foreign { metadata_index, .. } => *metadata_index,
322                    src => {
    ::core::panicking::panic_fmt(format_args!("Unexpected external source {0:?}",
            src));
}panic!("Unexpected external source {src:?}"),
323                }
324            };
325
326            (SpanKind::Foreign, metadata_index)
327        } else {
328            // Record the fact that we need to encode the data for this `SourceFile`
329            let source_files =
330                s.required_source_files.as_mut().expect("Already encoded SourceMap!");
331            let (metadata_index, _) = source_files.insert_full(source_file_index);
332            let metadata_index: u32 =
333                metadata_index.try_into().expect("cannot export more than U32_MAX files");
334
335            (SpanKind::Local, metadata_index)
336        };
337
338        // Encode the start position relative to the file start, so we profit more from the
339        // variable-length integer encoding.
340        let lo = self.lo - source_file.start_pos;
341
342        // Encode length which is usually less than span.hi and profits more
343        // from the variable-length integer encoding that we use.
344        let len = self.hi - self.lo;
345
346        let tag = SpanTag::new(kind, ctxt, len.0 as usize);
347        tag.encode(s);
348        if tag.context().is_none() {
349            ctxt.encode(s);
350        }
351        lo.encode(s);
352        if tag.length().is_none() {
353            len.encode(s);
354        }
355
356        // Encode the index of the `SourceFile` for the span, in order to make decoding faster.
357        metadata_index.encode(s);
358
359        if kind == SpanKind::Foreign {
360            // This needs to be two lines to avoid holding the `s.source_file_cache`
361            // while calling `cnum.encode(s)`
362            let cnum = s.source_file_cache.0.cnum;
363            cnum.encode(s);
364        }
365    }
366}
367
368impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for [u8] {
369    fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
370        Encoder::emit_usize(e, self.len());
371        e.emit_raw_bytes(self);
372    }
373}
374
375impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> {
376    const CLEAR_CROSS_CRATE: bool = true;
377
378    fn position(&self) -> usize {
379        self.opaque.position()
380    }
381
382    fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
383        &mut self.type_shorthands
384    }
385
386    fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
387        &mut self.predicate_shorthands
388    }
389
390    fn encode_alloc_id(&mut self, alloc_id: &rustc_middle::mir::interpret::AllocId) {
391        let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
392
393        index.encode(self);
394    }
395}
396
397// Shorthand for `$self.$tables.$table.set_some($def_id.index, $self.lazy($value))`, which would
398// normally need extra variables to avoid errors about multiple mutable borrows.
399macro_rules! record {
400    ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
401        {
402            let value = $value;
403            let lazy = $self.lazy(value);
404            $self.$tables.$table.set_some($def_id.index, lazy);
405        }
406    }};
407}
408
409// Shorthand for `$self.$tables.$table.set_some($def_id.index, $self.lazy_array($value))`, which would
410// normally need extra variables to avoid errors about multiple mutable borrows.
411macro_rules! record_array {
412    ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
413        {
414            let value = $value;
415            let lazy = $self.lazy_array(value);
416            $self.$tables.$table.set_some($def_id.index, lazy);
417        }
418    }};
419}
420
421macro_rules! record_defaulted_array {
422    ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
423        {
424            let value = $value;
425            let lazy = $self.lazy_array(value);
426            $self.$tables.$table.set($def_id.index, lazy);
427        }
428    }};
429}
430
431impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
432    fn emit_lazy_distance(&mut self, position: NonZero<usize>) {
433        let pos = position.get();
434        let distance = match self.lazy_state {
435            LazyState::NoNode => bug_impl(None, format_args!("emit_lazy_distance: outside of a metadata node"),
    Location::caller())bug!("emit_lazy_distance: outside of a metadata node"),
436            LazyState::NodeStart(start) => {
437                let start = start.get();
438                if !(pos <= start) {
    ::core::panicking::panic("assertion failed: pos <= start")
};assert!(pos <= start);
439                start - pos
440            }
441            LazyState::Previous(last_pos) => {
442                if !(last_pos <= position) {
    {
        ::core::panicking::panic_fmt(format_args!("make sure that the calls to `lazy*` are in the same order as the metadata fields"));
    }
};assert!(
443                    last_pos <= position,
444                    "make sure that the calls to `lazy*` \
445                     are in the same order as the metadata fields",
446                );
447                position.get() - last_pos.get()
448            }
449        };
450        self.lazy_state = LazyState::Previous(NonZero::new(pos).unwrap());
451        self.emit_usize(distance);
452    }
453
454    fn lazy<T: ParameterizedOverTcx, B: Borrow<T::Value<'tcx>>>(&mut self, value: B) -> LazyValue<T>
455    where
456        T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
457    {
458        let pos = NonZero::new(self.position()).unwrap();
459
460        {
    match (&self.lazy_state, &LazyState::NoNode) {
        (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!(self.lazy_state, LazyState::NoNode);
461        self.lazy_state = LazyState::NodeStart(pos);
462        value.borrow().encode(self);
463        self.lazy_state = LazyState::NoNode;
464
465        if !(pos.get() <= self.position()) {
    ::core::panicking::panic("assertion failed: pos.get() <= self.position()")
};assert!(pos.get() <= self.position());
466
467        LazyValue::from_position(pos)
468    }
469
470    fn lazy_array<T: ParameterizedOverTcx, I: IntoIterator<Item = B>, B: Borrow<T::Value<'tcx>>>(
471        &mut self,
472        values: I,
473    ) -> LazyArray<T>
474    where
475        T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
476    {
477        let pos = NonZero::new(self.position()).unwrap();
478
479        {
    match (&self.lazy_state, &LazyState::NoNode) {
        (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!(self.lazy_state, LazyState::NoNode);
480        self.lazy_state = LazyState::NodeStart(pos);
481        let len = values.into_iter().map(|value| value.borrow().encode(self)).count();
482        self.lazy_state = LazyState::NoNode;
483
484        if !(pos.get() <= self.position()) {
    ::core::panicking::panic("assertion failed: pos.get() <= self.position()")
};assert!(pos.get() <= self.position());
485
486        LazyArray::from_position_and_num_elems(pos, len)
487    }
488
489    fn encode_symbol_or_byte_symbol(
490        &mut self,
491        index: u32,
492        emit_str_or_byte_str: impl Fn(&mut Self),
493    ) {
494        // if symbol/byte symbol is predefined, emit tag and symbol index
495        if Symbol::is_predefined(index) {
496            self.opaque.emit_u8(SYMBOL_PREDEFINED);
497            self.opaque.emit_u32(index);
498        } else {
499            // otherwise write it as string or as offset to it
500            match self.symbol_index_table.entry(index) {
501                Entry::Vacant(o) => {
502                    self.opaque.emit_u8(SYMBOL_STR);
503                    let pos = self.opaque.position();
504                    o.insert(pos);
505                    emit_str_or_byte_str(self);
506                }
507                Entry::Occupied(o) => {
508                    let x = *o.get();
509                    self.emit_u8(SYMBOL_OFFSET);
510                    self.emit_usize(x);
511                }
512            }
513        }
514    }
515
516    fn encode_def_path_table(&mut self) {
517        let defs = self.tcx.definitions();
518        if self.is_proc_macro {
519            for def_id in std::iter::once(CRATE_DEF_ID)
520                .chain(self.tcx.resolutions(()).proc_macros.iter().copied())
521            {
522                let def_key = self.lazy(defs.def_key(def_id));
523                let def_path_hash = defs.def_path_hash(def_id);
524                self.tables.def_keys.set_some(def_id.local_def_index, def_key);
525                self.tables
526                    .def_path_hashes
527                    .set(def_id.local_def_index, def_path_hash.local_hash().as_u64());
528            }
529        } else {
530            for (def_index, def_key, def_path_hash) in defs.enumerated_keys_and_path_hashes() {
531                let def_key = self.lazy(def_key);
532                self.tables.def_keys.set_some(def_index, def_key);
533                self.tables.def_path_hashes.set(def_index, def_path_hash.local_hash().as_u64());
534            }
535        }
536    }
537
538    fn encode_def_path_hash_map(&mut self) -> LazyValue<DefPathHashMapRef<'static>> {
539        self.lazy(DefPathHashMapRef::BorrowedFromTcx(self.tcx.def_path_hash_to_def_index_map()))
540    }
541
542    fn encode_source_map(&mut self) -> LazyTable<u32, Option<LazyValue<rustc_span::SourceFile>>> {
543        let source_map = self.tcx.sess.source_map();
544        let all_source_files = source_map.files();
545
546        // By replacing the `Option` with `None`, we ensure that we can't
547        // accidentally serialize any more `Span`s after the source map encoding
548        // is done.
549        let required_source_files = self.required_source_files.take().unwrap();
550
551        let mut adapted = TableBuilder::default();
552
553        let local_crate_stable_id = self.tcx.stable_crate_id(LOCAL_CRATE);
554
555        // Only serialize `SourceFile`s that were used during the encoding of a `Span`.
556        //
557        // The order in which we encode source files is important here: the on-disk format for
558        // `Span` contains the index of the corresponding `SourceFile`.
559        for (on_disk_index, &source_file_index) in required_source_files.iter().enumerate() {
560            let source_file = &all_source_files[source_file_index];
561            // Don't serialize imported `SourceFile`s, unless we're in a proc-macro crate.
562            if !(!source_file.is_imported() || self.is_proc_macro) {
    ::core::panicking::panic("assertion failed: !source_file.is_imported() || self.is_proc_macro")
};assert!(!source_file.is_imported() || self.is_proc_macro);
563
564            // At export time we expand all source file paths to absolute paths because
565            // downstream compilation sessions can have a different compiler working
566            // directory, so relative paths from this or any other upstream crate
567            // won't be valid anymore.
568            //
569            // At this point we also erase the actual on-disk path and only keep
570            // the remapped version -- as is necessary for reproducible builds.
571            let mut adapted_source_file = (**source_file).clone();
572
573            match source_file.name {
574                FileName::Real(ref original_file_name) => {
575                    let mut adapted_file_name = original_file_name.clone();
576                    adapted_file_name.update_for_crate_metadata();
577                    adapted_source_file.name = FileName::Real(adapted_file_name);
578                }
579                _ => {
580                    // expanded code, not from a file
581                }
582            };
583
584            // We're serializing this `SourceFile` into our crate metadata,
585            // so mark it as coming from this crate.
586            // This also ensures that we don't try to deserialize the
587            // `CrateNum` for a proc-macro dependency - since proc macro
588            // dependencies aren't loaded when we deserialize a proc-macro,
589            // trying to remap the `CrateNum` would fail.
590            if self.is_proc_macro {
591                adapted_source_file.cnum = LOCAL_CRATE;
592            }
593
594            // Update the `StableSourceFileId` to make sure it incorporates the
595            // id of the current crate. This way it will be unique within the
596            // crate graph during downstream compilation sessions.
597            adapted_source_file.stable_id = StableSourceFileId::from_filename_for_export(
598                &adapted_source_file.name,
599                local_crate_stable_id,
600            );
601
602            let on_disk_index: u32 =
603                on_disk_index.try_into().expect("cannot export more than U32_MAX files");
604            adapted.set_some(on_disk_index, self.lazy(adapted_source_file));
605        }
606
607        adapted.encode(&mut self.opaque)
608    }
609
610    fn encode_crate_root(&mut self) -> LazyValue<CrateRoot> {
611        let tcx = self.tcx;
612        let mut stats: Vec<(&'static str, usize)> = Vec::with_capacity(32);
613
614        macro_rules! stat {
615            ($label:literal, $f:expr) => {{
616                let orig_pos = self.position();
617                let res = $f();
618                stats.push(($label, self.position() - orig_pos));
619                res
620            }};
621        }
622
623        // We have already encoded some things. Get their combined size from the current position.
624        stats.push(("preamble", self.position()));
625
626        let externally_implementable_items = {
    let orig_pos = self.position();
    let res = (|| self.encode_externally_implementable_items())();
    stats.push(("externally-implementable-items",
            self.position() - orig_pos));
    res
}stat!("externally-implementable-items", || self
627            .encode_externally_implementable_items());
628
629        let (crate_deps, dylib_dependency_formats) =
630            {
    let orig_pos = self.position();
    let res =
        (||
                (self.encode_crate_deps(),
                    self.encode_dylib_dependency_formats()))();
    stats.push(("dep", self.position() - orig_pos));
    res
}stat!("dep", || (self.encode_crate_deps(), self.encode_dylib_dependency_formats()));
631
632        let lib_features = {
    let orig_pos = self.position();
    let res = (|| self.encode_lib_features())();
    stats.push(("lib-features", self.position() - orig_pos));
    res
}stat!("lib-features", || self.encode_lib_features());
633
634        let stability_implications =
635            {
    let orig_pos = self.position();
    let res = (|| self.encode_stability_implications())();
    stats.push(("stability-implications", self.position() - orig_pos));
    res
}stat!("stability-implications", || self.encode_stability_implications());
636
637        let (lang_items, lang_items_missing) = {
    let orig_pos = self.position();
    let res =
        (||
                {
                    (self.encode_lang_items(), self.encode_lang_items_missing())
                })();
    stats.push(("lang-items", self.position() - orig_pos));
    res
}stat!("lang-items", || {
638            (self.encode_lang_items(), self.encode_lang_items_missing())
639        });
640
641        let stripped_cfg_items = {
    let orig_pos = self.position();
    let res = (|| self.encode_stripped_cfg_items())();
    stats.push(("stripped-cfg-items", self.position() - orig_pos));
    res
}stat!("stripped-cfg-items", || self.encode_stripped_cfg_items());
642
643        let diagnostic_items = {
    let orig_pos = self.position();
    let res = (|| self.encode_diagnostic_items())();
    stats.push(("diagnostic-items", self.position() - orig_pos));
    res
}stat!("diagnostic-items", || self.encode_diagnostic_items());
644
645        let canonical_symbols = {
    let orig_pos = self.position();
    let res = (|| self.encode_canonical_symbols())();
    stats.push(("canonical-symbols", self.position() - orig_pos));
    res
}stat!("canonical-symbols", || self.encode_canonical_symbols());
646
647        let fake_doc_items = {
    let orig_pos = self.position();
    let res = (|| self.encode_fake_doc_items())();
    stats.push(("fake-doc-items", self.position() - orig_pos));
    res
}stat!("fake-doc-items", || self.encode_fake_doc_items());
648
649        let native_libraries = {
    let orig_pos = self.position();
    let res = (|| self.encode_native_libraries())();
    stats.push(("native-libs", self.position() - orig_pos));
    res
}stat!("native-libs", || self.encode_native_libraries());
650
651        let foreign_modules = {
    let orig_pos = self.position();
    let res = (|| self.encode_foreign_modules())();
    stats.push(("foreign-modules", self.position() - orig_pos));
    res
}stat!("foreign-modules", || self.encode_foreign_modules());
652
653        _ = {
    let orig_pos = self.position();
    let res = (|| self.encode_def_path_table())();
    stats.push(("def-path-table", self.position() - orig_pos));
    res
}stat!("def-path-table", || self.encode_def_path_table());
654
655        // Encode the def IDs of traits, for rustdoc and diagnostics.
656        let traits = {
    let orig_pos = self.position();
    let res = (|| self.encode_traits())();
    stats.push(("traits", self.position() - orig_pos));
    res
}stat!("traits", || self.encode_traits());
657
658        // Encode the def IDs of impls, for coherence checking.
659        let impls = {
    let orig_pos = self.position();
    let res = (|| self.encode_impls())();
    stats.push(("impls", self.position() - orig_pos));
    res
}stat!("impls", || self.encode_impls());
660
661        let incoherent_impls = {
    let orig_pos = self.position();
    let res = (|| self.encode_incoherent_impls())();
    stats.push(("incoherent-impls", self.position() - orig_pos));
    res
}stat!("incoherent-impls", || self.encode_incoherent_impls());
662
663        _ = {
    let orig_pos = self.position();
    let res = (|| self.encode_mir())();
    stats.push(("mir", self.position() - orig_pos));
    res
}stat!("mir", || self.encode_mir());
664
665        _ = {
    let orig_pos = self.position();
    let res = (|| self.encode_def_ids())();
    stats.push(("def-ids", self.position() - orig_pos));
    res
}stat!("def-ids", || self.encode_def_ids());
666
667        let interpret_alloc_index = {
    let orig_pos = self.position();
    let res =
        (||
                {
                    let mut interpret_alloc_index = Vec::new();
                    let mut n = 0;
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/rmeta/encoder.rs:670",
                                            "rustc_metadata::rmeta::encoder", ::tracing::Level::TRACE,
                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                            ::tracing_core::__macro_support::Option::Some(670u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::TRACE <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::TRACE <=
                                        ::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!("beginning to encode alloc ids")
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    loop {
                        let new_n = self.interpret_allocs.len();
                        if n == new_n { break; }
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/rmeta/encoder.rs:678",
                                                "rustc_metadata::rmeta::encoder", ::tracing::Level::TRACE,
                                                ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                                ::tracing_core::__macro_support::Option::Some(678u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::TRACE <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::TRACE <=
                                            ::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!("encoding {0} further alloc ids",
                                                                            new_n - n) as &dyn ::tracing::field::Value))])
                                    });
                            } else { ; }
                        };
                        for idx in n..new_n {
                            let id = self.interpret_allocs[idx];
                            let pos = self.position() as u64;
                            interpret_alloc_index.push(pos);
                            interpret::specialized_encode_alloc_id(self, tcx, id);
                        }
                        n = new_n;
                    }
                    self.lazy_array(interpret_alloc_index)
                })();
    stats.push(("interpret-alloc-index", self.position() - orig_pos));
    res
}stat!("interpret-alloc-index", || {
668            let mut interpret_alloc_index = Vec::new();
669            let mut n = 0;
670            trace!("beginning to encode alloc ids");
671            loop {
672                let new_n = self.interpret_allocs.len();
673                // if we have found new ids, serialize those, too
674                if n == new_n {
675                    // otherwise, abort
676                    break;
677                }
678                trace!("encoding {} further alloc ids", new_n - n);
679                for idx in n..new_n {
680                    let id = self.interpret_allocs[idx];
681                    let pos = self.position() as u64;
682                    interpret_alloc_index.push(pos);
683                    interpret::specialized_encode_alloc_id(self, tcx, id);
684                }
685                n = new_n;
686            }
687            self.lazy_array(interpret_alloc_index)
688        });
689
690        // Encode the proc macro data. This affects `tables`, so we need to do this before we
691        // encode the tables. This overwrites def_keys, so it must happen after
692        // encode_def_path_table.
693        let proc_macro_data = {
    let orig_pos = self.position();
    let res = (|| self.encode_proc_macros())();
    stats.push(("proc-macro-data", self.position() - orig_pos));
    res
}stat!("proc-macro-data", || self.encode_proc_macros());
694
695        let tables = {
    let orig_pos = self.position();
    let res = (|| self.tables.encode(&mut self.opaque))();
    stats.push(("tables", self.position() - orig_pos));
    res
}stat!("tables", || self.tables.encode(&mut self.opaque));
696
697        let debugger_visualizers =
698            {
    let orig_pos = self.position();
    let res = (|| self.encode_debugger_visualizers())();
    stats.push(("debugger-visualizers", self.position() - orig_pos));
    res
}stat!("debugger-visualizers", || self.encode_debugger_visualizers());
699
700        let exportable_items = {
    let orig_pos = self.position();
    let res = (|| self.encode_exportable_items())();
    stats.push(("exportable-items", self.position() - orig_pos));
    res
}stat!("exportable-items", || self.encode_exportable_items());
701
702        let stable_order_of_exportable_impls =
703            {
    let orig_pos = self.position();
    let res = (|| self.encode_stable_order_of_exportable_impls())();
    stats.push(("exportable-items", self.position() - orig_pos));
    res
}stat!("exportable-items", || self.encode_stable_order_of_exportable_impls());
704
705        // Encode exported symbols info. This is prefetched in `encode_metadata`.
706        let (exported_non_generic_symbols, exported_generic_symbols) =
707            {
    let orig_pos = self.position();
    let res =
        (||
                {
                    (self.encode_exported_symbols(tcx.exported_non_generic_symbols(LOCAL_CRATE)),
                        self.encode_exported_symbols(tcx.exported_generic_symbols(LOCAL_CRATE)))
                })();
    stats.push(("exported-symbols", self.position() - orig_pos));
    res
}stat!("exported-symbols", || {
708                (
709                    self.encode_exported_symbols(tcx.exported_non_generic_symbols(LOCAL_CRATE)),
710                    self.encode_exported_symbols(tcx.exported_generic_symbols(LOCAL_CRATE)),
711                )
712            });
713
714        // Encode the hygiene data.
715        // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The
716        // process of encoding other items (e.g. `optimized_mir`) may cause us to load data from
717        // the incremental cache. If this causes us to deserialize a `Span`, then we may load
718        // additional `SyntaxContext`s into the global `HygieneData`. Therefore, we need to encode
719        // the hygiene data last to ensure that we encode any `SyntaxContext`s that might be used.
720        let (syntax_contexts, expn_data, expn_hashes) = {
    let orig_pos = self.position();
    let res = (|| self.encode_hygiene())();
    stats.push(("hygiene", self.position() - orig_pos));
    res
}stat!("hygiene", || self.encode_hygiene());
721
722        let def_path_hash_map = {
    let orig_pos = self.position();
    let res = (|| self.encode_def_path_hash_map())();
    stats.push(("def-path-hash-map", self.position() - orig_pos));
    res
}stat!("def-path-hash-map", || self.encode_def_path_hash_map());
723
724        // Encode source_map. This needs to be done last, because encoding `Span`s tells us which
725        // `SourceFiles` we actually need to encode.
726        let source_map = {
    let orig_pos = self.position();
    let res = (|| self.encode_source_map())();
    stats.push(("source-map", self.position() - orig_pos));
    res
}stat!("source-map", || self.encode_source_map());
727        let target_modifiers = {
    let orig_pos = self.position();
    let res = (|| self.encode_target_modifiers())();
    stats.push(("target-modifiers", self.position() - orig_pos));
    res
}stat!("target-modifiers", || self.encode_target_modifiers());
728        let denied_partial_mitigations = {
    let orig_pos = self.position();
    let res = (|| self.encode_enabled_denied_partial_mitigations())();
    stats.push(("denied-partial-mitigations", self.position() - orig_pos));
    res
}stat!("denied-partial-mitigations", || self
729            .encode_enabled_denied_partial_mitigations());
730
731        let root = {
    let orig_pos = self.position();
    let res =
        (||
                {
                    let attrs = tcx.hir_krate_attrs();
                    self.lazy(CrateRoot {
                            header: CrateHeader {
                                name: tcx.crate_name(LOCAL_CRATE),
                                triple: tcx.sess.opts.target_triple.clone(),
                                hash: tcx.crate_hash(LOCAL_CRATE),
                                is_proc_macro_crate: proc_macro_data.is_some(),
                                is_stub: false,
                            },
                            extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
                            stable_crate_id: tcx.stable_crate_id(LOCAL_CRATE),
                            required_panic_strategy: tcx.required_panic_strategy(LOCAL_CRATE),
                            panic_in_drop_strategy: tcx.sess.opts.unstable_opts.panic_in_drop,
                            edition: tcx.sess.edition(),
                            has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
                            has_alloc_error_handler: tcx.has_alloc_error_handler(LOCAL_CRATE),
                            has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
                            has_default_lib_allocator: {
                                {
                                        'done:
                                            {
                                            for i in attrs {
                                                #[allow(unused_imports)]
                                                use ::rustc_attr_ir::AttributeKind::*;
                                                let i: &::rustc_attr_ir::Attribute = i;
                                                match i {
                                                    ::rustc_attr_ir::Attribute::Parsed(DefaultLibAllocator) => {
                                                        break 'done Some(());
                                                    }
                                                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }.is_some()
                            },
                            externally_implementable_items,
                            proc_macro_data,
                            debugger_visualizers,
                            compiler_builtins: {
                                {
                                        'done:
                                            {
                                            for i in attrs {
                                                #[allow(unused_imports)]
                                                use ::rustc_attr_ir::AttributeKind::*;
                                                let i: &::rustc_attr_ir::Attribute = i;
                                                match i {
                                                    ::rustc_attr_ir::Attribute::Parsed(CompilerBuiltins) => {
                                                        break 'done Some(());
                                                    }
                                                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }.is_some()
                            },
                            needs_allocator: {
                                {
                                        'done:
                                            {
                                            for i in attrs {
                                                #[allow(unused_imports)]
                                                use ::rustc_attr_ir::AttributeKind::*;
                                                let i: &::rustc_attr_ir::Attribute = i;
                                                match i {
                                                    ::rustc_attr_ir::Attribute::Parsed(NeedsAllocator) => {
                                                        break 'done Some(());
                                                    }
                                                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }.is_some()
                            },
                            needs_panic_runtime: {
                                {
                                        'done:
                                            {
                                            for i in attrs {
                                                #[allow(unused_imports)]
                                                use ::rustc_attr_ir::AttributeKind::*;
                                                let i: &::rustc_attr_ir::Attribute = i;
                                                match i {
                                                    ::rustc_attr_ir::Attribute::Parsed(NeedsPanicRuntime) => {
                                                        break 'done Some(());
                                                    }
                                                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }.is_some()
                            },
                            no_builtins: {
                                {
                                        'done:
                                            {
                                            for i in attrs {
                                                #[allow(unused_imports)]
                                                use ::rustc_attr_ir::AttributeKind::*;
                                                let i: &::rustc_attr_ir::Attribute = i;
                                                match i {
                                                    ::rustc_attr_ir::Attribute::Parsed(NoBuiltins) => {
                                                        break 'done Some(());
                                                    }
                                                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }.is_some()
                            },
                            panic_runtime: {
                                {
                                        'done:
                                            {
                                            for i in attrs {
                                                #[allow(unused_imports)]
                                                use ::rustc_attr_ir::AttributeKind::*;
                                                let i: &::rustc_attr_ir::Attribute = i;
                                                match i {
                                                    ::rustc_attr_ir::Attribute::Parsed(PanicRuntime) => {
                                                        break 'done Some(());
                                                    }
                                                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }.is_some()
                            },
                            profiler_runtime: {
                                {
                                        'done:
                                            {
                                            for i in attrs {
                                                #[allow(unused_imports)]
                                                use ::rustc_attr_ir::AttributeKind::*;
                                                let i: &::rustc_attr_ir::Attribute = i;
                                                match i {
                                                    ::rustc_attr_ir::Attribute::Parsed(ProfilerRuntime) => {
                                                        break 'done Some(());
                                                    }
                                                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }.is_some()
                            },
                            symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(),
                            crate_deps,
                            dylib_dependency_formats,
                            lib_features,
                            stability_implications,
                            lang_items,
                            diagnostic_items,
                            canonical_symbols,
                            fake_doc_items,
                            lang_items_missing,
                            stripped_cfg_items,
                            native_libraries,
                            foreign_modules,
                            source_map,
                            target_modifiers,
                            denied_partial_mitigations,
                            traits,
                            impls,
                            incoherent_impls,
                            exportable_items,
                            stable_order_of_exportable_impls,
                            exported_non_generic_symbols,
                            exported_generic_symbols,
                            interpret_alloc_index,
                            tables,
                            syntax_contexts,
                            expn_data,
                            expn_hashes,
                            def_path_hash_map,
                            specialization_enabled_in: tcx.specialization_enabled_in(LOCAL_CRATE),
                        })
                })();
    stats.push(("final", self.position() - orig_pos));
    res
}stat!("final", || {
732            let attrs = tcx.hir_krate_attrs();
733            self.lazy(CrateRoot {
734                header: CrateHeader {
735                    name: tcx.crate_name(LOCAL_CRATE),
736                    triple: tcx.sess.opts.target_triple.clone(),
737                    hash: tcx.crate_hash(LOCAL_CRATE),
738                    is_proc_macro_crate: proc_macro_data.is_some(),
739                    is_stub: false,
740                },
741                extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
742                stable_crate_id: tcx.stable_crate_id(LOCAL_CRATE),
743                required_panic_strategy: tcx.required_panic_strategy(LOCAL_CRATE),
744                panic_in_drop_strategy: tcx.sess.opts.unstable_opts.panic_in_drop,
745                edition: tcx.sess.edition(),
746                has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
747                has_alloc_error_handler: tcx.has_alloc_error_handler(LOCAL_CRATE),
748                has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
749                has_default_lib_allocator: find_attr!(attrs, DefaultLibAllocator),
750                externally_implementable_items,
751                proc_macro_data,
752                debugger_visualizers,
753                compiler_builtins: find_attr!(attrs, CompilerBuiltins),
754                needs_allocator: find_attr!(attrs, NeedsAllocator),
755                needs_panic_runtime: find_attr!(attrs, NeedsPanicRuntime),
756                no_builtins: find_attr!(attrs, NoBuiltins),
757                panic_runtime: find_attr!(attrs, PanicRuntime),
758                profiler_runtime: find_attr!(attrs, ProfilerRuntime),
759                symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(),
760
761                crate_deps,
762                dylib_dependency_formats,
763                lib_features,
764                stability_implications,
765                lang_items,
766                diagnostic_items,
767                canonical_symbols,
768                fake_doc_items,
769                lang_items_missing,
770                stripped_cfg_items,
771                native_libraries,
772                foreign_modules,
773                source_map,
774                target_modifiers,
775                denied_partial_mitigations,
776                traits,
777                impls,
778                incoherent_impls,
779                exportable_items,
780                stable_order_of_exportable_impls,
781                exported_non_generic_symbols,
782                exported_generic_symbols,
783                interpret_alloc_index,
784                tables,
785                syntax_contexts,
786                expn_data,
787                expn_hashes,
788                def_path_hash_map,
789                specialization_enabled_in: tcx.specialization_enabled_in(LOCAL_CRATE),
790            })
791        });
792
793        let total_bytes = self.position();
794
795        let computed_total_bytes: usize = stats.iter().map(|(_, size)| size).sum();
796        {
    match (&total_bytes, &computed_total_bytes) {
        (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!(total_bytes, computed_total_bytes);
797
798        if tcx.sess.opts.unstable_opts.meta_stats {
799            use std::fmt::Write;
800
801            self.opaque.flush();
802
803            // Rewind and re-read all the metadata to count the zero bytes we wrote.
804            let pos_before_rewind = self.opaque.file().stream_position().unwrap();
805            let mut zero_bytes = 0;
806            self.opaque.file().rewind().unwrap();
807            let file = std::io::BufReader::new(self.opaque.file());
808            for e in file.bytes() {
809                if e.unwrap() == 0 {
810                    zero_bytes += 1;
811                }
812            }
813            {
    match (&self.opaque.file().stream_position().unwrap(), &pos_before_rewind)
        {
        (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!(self.opaque.file().stream_position().unwrap(), pos_before_rewind);
814
815            stats.sort_by_key(|&(_, usize)| usize);
816            stats.reverse(); // bigger items first
817
818            let prefix = "meta-stats";
819            let perc = |bytes| (bytes * 100) as f64 / total_bytes as f64;
820
821            let section_w = 23;
822            let size_w = 10;
823            let banner_w = 64;
824
825            // We write all the text into a string and print it with a single
826            // `eprint!`. This is an attempt to minimize interleaved text if multiple
827            // rustc processes are printing macro-stats at the same time (e.g. with
828            // `RUSTFLAGS='-Zmeta-stats' cargo build`). It still doesn't guarantee
829            // non-interleaving, though.
830            let mut s = String::new();
831            _ = s.write_fmt(format_args!("{1} {0}\n", "=".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "=".repeat(banner_w));
832            _ = s.write_fmt(format_args!("{1} METADATA STATS: {0}\n",
        tcx.crate_name(LOCAL_CRATE), prefix))writeln!(s, "{prefix} METADATA STATS: {}", tcx.crate_name(LOCAL_CRATE));
833            _ = s.write_fmt(format_args!("{2} {0:<3$}{1:>4$}\n", "Section", "Size", prefix,
        section_w, size_w))writeln!(s, "{prefix} {:<section_w$}{:>size_w$}", "Section", "Size");
834            _ = s.write_fmt(format_args!("{1} {0}\n", "-".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "-".repeat(banner_w));
835            for (label, size) in stats {
836                _ = s.write_fmt(format_args!("{3} {0:<4$}{1:>5$} ({2:4.1}%)\n", label,
        usize_with_underscores(size), perc(size), prefix, section_w, size_w))writeln!(
837                    s,
838                    "{prefix} {:<section_w$}{:>size_w$} ({:4.1}%)",
839                    label,
840                    usize_with_underscores(size),
841                    perc(size)
842                );
843            }
844            _ = s.write_fmt(format_args!("{1} {0}\n", "-".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "-".repeat(banner_w));
845            _ = s.write_fmt(format_args!("{3} {0:<4$}{1:>5$} (of which {2:.1}% are zero bytes)\n",
        "Total", usize_with_underscores(total_bytes), perc(zero_bytes),
        prefix, section_w, size_w))writeln!(
846                s,
847                "{prefix} {:<section_w$}{:>size_w$} (of which {:.1}% are zero bytes)",
848                "Total",
849                usize_with_underscores(total_bytes),
850                perc(zero_bytes)
851            );
852            _ = s.write_fmt(format_args!("{1} {0}\n", "=".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "=".repeat(banner_w));
853            { ::std::io::_eprint(format_args!("{0}", s)); };eprint!("{s}");
854        }
855
856        root
857    }
858}
859
860struct AnalyzeAttrState {
861    is_exported: bool,
862    is_doc_hidden: bool,
863}
864
865/// Returns whether an attribute needs to be recorded in metadata, that is, if it's usable and
866/// useful in downstream crates. Local-only attributes are an obvious example, but some
867/// rustdoc-specific attributes can equally be of use while documenting the current crate only.
868///
869/// Removing these superfluous attributes speeds up compilation by making the metadata smaller.
870///
871/// Note: the `is_exported` parameter is used to cache whether the given `DefId` has a public
872/// visibility: this is a piece of data that can be computed once per defid, and not once per
873/// attribute. Some attributes would only be usable downstream if they are public.
874#[inline]
875fn analyze_attr(attr: &hir::Attribute, state: &mut AnalyzeAttrState) -> bool {
876    let mut should_encode = false;
877    if let hir::Attribute::Parsed(p) = attr
878        && p.encode_cross_crate() == EncodeCrossCrate::No
879    {
880        // Attributes not marked encode-cross-crate don't need to be encoded for downstream crates.
881    } else if let Some(name) = attr.name()
882        && [sym::warn, sym::allow, sym::expect, sym::forbid, sym::deny].contains(&name)
883    {
884        // Lint attributes don't need to be encoded for downstream crates.
885        // FIXME remove this when #152369 is re-merged
886    } else if let hir::Attribute::Parsed(AttributeKind::DocComment { .. }) = attr {
887        // We keep all doc comments reachable to rustdoc because they might be "imported" into
888        // downstream crates if they use `#[doc(inline)]` to copy an item's documentation into
889        // their own.
890        if state.is_exported {
891            should_encode = true;
892        }
893    } else if let hir::Attribute::Parsed(AttributeKind::Doc(d)) = attr {
894        should_encode = true;
895        if d.hidden.is_some() {
896            state.is_doc_hidden = true;
897        }
898    } else {
899        should_encode = true;
900    }
901    should_encode
902}
903
904fn should_encode_span(def_kind: DefKind) -> bool {
905    match def_kind {
906        DefKind::Mod
907        | DefKind::Struct
908        | DefKind::Union
909        | DefKind::Enum
910        | DefKind::Variant
911        | DefKind::Trait
912        | DefKind::TyAlias
913        | DefKind::ForeignTy
914        | DefKind::TraitAlias
915        | DefKind::AssocTy
916        | DefKind::TyParam
917        | DefKind::ConstParam
918        | DefKind::LifetimeParam
919        | DefKind::Fn
920        | DefKind::Const
921        | DefKind::Static { .. }
922        | DefKind::Ctor(..)
923        | DefKind::AssocFn
924        | DefKind::AssocConst
925        | DefKind::Macro(_)
926        | DefKind::ExternCrate
927        | DefKind::Use
928        | DefKind::AnonConst
929        | DefKind::OpaqueTy
930        | DefKind::Field
931        | DefKind::Impl { .. }
932        | DefKind::Closure
933        | DefKind::SyntheticCoroutineBody => true,
934        DefKind::ForeignMod | DefKind::GlobalAsm | DefKind::TestBinderConstraints => false,
935    }
936}
937
938fn should_encode_attrs(def_kind: DefKind) -> bool {
939    match def_kind {
940        DefKind::Mod
941        | DefKind::Struct
942        | DefKind::Union
943        | DefKind::Enum
944        | DefKind::Variant
945        | DefKind::Trait
946        | DefKind::TyAlias
947        | DefKind::ForeignTy
948        | DefKind::TraitAlias
949        | DefKind::AssocTy
950        | DefKind::Fn
951        | DefKind::Const
952        | DefKind::Static { nested: false, .. }
953        | DefKind::AssocFn
954        | DefKind::AssocConst
955        | DefKind::Macro(_)
956        | DefKind::Field
957        | DefKind::ConstParam
958        | DefKind::Impl { .. } => true,
959        // Encoding attrs for `Use` items allows `#[doc(hidden)]` on re-exports
960        // to be read cross-crate, which is needed for diagnostic path selection
961        // in `visible_parent_map`. See #153477.
962        DefKind::Use => true,
963        // Tools may want to be able to detect their tool lints on
964        // closures from upstream crates, too. This is used by
965        // https://github.com/model-checking/kani and is not a performance
966        // or maintenance issue for us.
967        DefKind::Closure => true,
968        DefKind::SyntheticCoroutineBody => false,
969        DefKind::TyParam
970        | DefKind::Ctor(..)
971        | DefKind::ExternCrate
972        | DefKind::ForeignMod
973        | DefKind::AnonConst
974        | DefKind::OpaqueTy
975        | DefKind::LifetimeParam
976        | DefKind::Static { nested: true, .. }
977        | DefKind::GlobalAsm
978        | DefKind::TestBinderConstraints => false,
979    }
980}
981
982fn should_encode_expn_that_defined(def_kind: DefKind) -> bool {
983    match def_kind {
984        DefKind::Mod
985        | DefKind::Struct
986        | DefKind::Union
987        | DefKind::Enum
988        | DefKind::Variant
989        | DefKind::Trait
990        | DefKind::Impl { .. } => true,
991        DefKind::TyAlias
992        | DefKind::ForeignTy
993        | DefKind::TraitAlias
994        | DefKind::AssocTy
995        | DefKind::TyParam
996        | DefKind::Fn
997        | DefKind::Const
998        | DefKind::ConstParam
999        | DefKind::Static { .. }
1000        | DefKind::Ctor(..)
1001        | DefKind::AssocFn
1002        | DefKind::AssocConst
1003        | DefKind::Macro(_)
1004        | DefKind::ExternCrate
1005        | DefKind::Use
1006        | DefKind::ForeignMod
1007        | DefKind::AnonConst
1008        | DefKind::OpaqueTy
1009        | DefKind::Field
1010        | DefKind::LifetimeParam
1011        | DefKind::GlobalAsm
1012        | DefKind::Closure
1013        | DefKind::SyntheticCoroutineBody
1014        | DefKind::TestBinderConstraints => false,
1015    }
1016}
1017
1018fn should_encode_visibility(def_kind: DefKind) -> bool {
1019    match def_kind {
1020        DefKind::Mod
1021        | DefKind::Struct
1022        | DefKind::Union
1023        | DefKind::Enum
1024        | DefKind::Variant
1025        | DefKind::Trait
1026        | DefKind::TyAlias
1027        | DefKind::ForeignTy
1028        | DefKind::TraitAlias
1029        | DefKind::AssocTy
1030        | DefKind::Fn
1031        | DefKind::Const
1032        | DefKind::Static { nested: false, .. }
1033        | DefKind::Ctor(..)
1034        | DefKind::AssocFn
1035        | DefKind::AssocConst
1036        | DefKind::Macro(..)
1037        | DefKind::Field => true,
1038        DefKind::Use
1039        | DefKind::ForeignMod
1040        | DefKind::TyParam
1041        | DefKind::ConstParam
1042        | DefKind::LifetimeParam
1043        | DefKind::AnonConst
1044        | DefKind::Static { nested: true, .. }
1045        | DefKind::OpaqueTy
1046        | DefKind::GlobalAsm
1047        | DefKind::Impl { .. }
1048        | DefKind::Closure
1049        | DefKind::ExternCrate
1050        | DefKind::SyntheticCoroutineBody
1051        | DefKind::TestBinderConstraints => false,
1052    }
1053}
1054
1055fn should_encode_stability(def_kind: DefKind) -> bool {
1056    match def_kind {
1057        DefKind::Mod
1058        | DefKind::Ctor(..)
1059        | DefKind::Variant
1060        | DefKind::Field
1061        | DefKind::Struct
1062        | DefKind::AssocTy
1063        | DefKind::AssocFn
1064        | DefKind::AssocConst
1065        | DefKind::TyParam
1066        | DefKind::ConstParam
1067        | DefKind::Static { .. }
1068        | DefKind::Const
1069        | DefKind::Fn
1070        | DefKind::ForeignMod
1071        | DefKind::TyAlias
1072        | DefKind::OpaqueTy
1073        | DefKind::Enum
1074        | DefKind::Union
1075        | DefKind::Impl { .. }
1076        | DefKind::Trait
1077        | DefKind::TraitAlias
1078        | DefKind::Macro(..)
1079        | DefKind::ForeignTy => true,
1080        DefKind::Use
1081        | DefKind::LifetimeParam
1082        | DefKind::AnonConst
1083        | DefKind::GlobalAsm
1084        | DefKind::Closure
1085        | DefKind::ExternCrate
1086        | DefKind::SyntheticCoroutineBody
1087        | DefKind::TestBinderConstraints => false,
1088    }
1089}
1090
1091/// Whether we should encode MIR. Return a pair, resp. for CTFE and for LLVM.
1092///
1093/// Computing, optimizing and encoding the MIR is a relatively expensive operation.
1094/// We want to avoid this work when not required. Therefore:
1095/// - we only compute `mir_for_ctfe` on items with const-eval semantics;
1096/// - we skip `optimized_mir` for check runs.
1097/// - we only encode `optimized_mir` that could be generated in other crates, that is, a code that
1098///   is either generic or has inline hint, and is reachable from the other crates (contained
1099///   in reachable set).
1100///
1101/// Note: Reachable set describes definitions that might be generated or referenced from other
1102/// crates and it can be used to limit optimized MIR that needs to be encoded. On the other hand,
1103/// the reachable set doesn't have much to say about which definitions might be evaluated at compile
1104/// time in other crates, so it cannot be used to omit CTFE MIR. For example, `f` below is
1105/// unreachable and yet it can be evaluated in other crates:
1106///
1107/// ```
1108/// const fn f() -> usize { 0 }
1109/// pub struct S { pub a: [usize; f()] }
1110/// ```
1111fn should_encode_mir(
1112    tcx: TyCtxt<'_>,
1113    reachable_set: &LocalDefIdSet,
1114    def_id: LocalDefId,
1115) -> (bool, bool) {
1116    match tcx.def_kind(def_id) {
1117        // instance_mir uses mir_for_ctfe rather than optimized_mir for constructors
1118        DefKind::Ctor(_, _) => (true, false),
1119        // Constants
1120        DefKind::AnonConst | DefKind::AssocConst | DefKind::Const => (true, false),
1121        // Coroutines require optimized MIR to compute layout.
1122        DefKind::Closure if tcx.is_coroutine(def_id.to_def_id()) => (false, true),
1123        DefKind::SyntheticCoroutineBody => (false, true),
1124        // Full-fledged functions + closures
1125        DefKind::AssocFn | DefKind::Fn | DefKind::Closure => {
1126            let opt = tcx.sess.opts.unstable_opts.always_encode_mir
1127                || (tcx.sess.opts.output_types.should_codegen()
1128                    && reachable_set.contains(&def_id)
1129                    && (tcx.generics_of(def_id).requires_monomorphization(tcx)
1130                        || tcx.cross_crate_inlinable(def_id)));
1131            // Comptime fns do not have optimized MIR at all.
1132            let opt =
1133                opt && !#[allow(non_exhaustive_omitted_patterns)] match tcx.constness(def_id) {
    hir::Constness::Const { always: true } => true,
    _ => false,
}matches!(tcx.constness(def_id), hir::Constness::Const { always: true });
1134            // The function has a `const` modifier or is in a `const trait`.
1135            let is_const_fn = tcx.is_const_fn(def_id.to_def_id());
1136            (is_const_fn, opt)
1137        }
1138        // The others don't have MIR.
1139        _ => (false, false),
1140    }
1141}
1142
1143fn should_encode_variances<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, def_kind: DefKind) -> bool {
1144    match def_kind {
1145        DefKind::Struct
1146        | DefKind::Union
1147        | DefKind::Enum
1148        | DefKind::OpaqueTy
1149        | DefKind::Fn
1150        | DefKind::Ctor(..)
1151        | DefKind::AssocFn => true,
1152        DefKind::AssocTy => {
1153            // Only encode variances for RPITITs (for traits)
1154            #[allow(non_exhaustive_omitted_patterns)] match tcx.opt_rpitit_info(def_id) {
    Some(ty::ImplTraitInTraitData::Trait { .. }) => true,
    _ => false,
}matches!(tcx.opt_rpitit_info(def_id), Some(ty::ImplTraitInTraitData::Trait { .. }))
1155        }
1156        DefKind::Mod
1157        | DefKind::Variant
1158        | DefKind::Field
1159        | DefKind::AssocConst
1160        | DefKind::TyParam
1161        | DefKind::ConstParam
1162        | DefKind::Static { .. }
1163        | DefKind::Const
1164        | DefKind::ForeignMod
1165        | DefKind::TyAlias
1166        | DefKind::Impl { .. }
1167        | DefKind::Trait
1168        | DefKind::TraitAlias
1169        | DefKind::Macro(..)
1170        | DefKind::ForeignTy
1171        | DefKind::Use
1172        | DefKind::LifetimeParam
1173        | DefKind::AnonConst
1174        | DefKind::GlobalAsm
1175        | DefKind::Closure
1176        | DefKind::ExternCrate
1177        | DefKind::SyntheticCoroutineBody
1178        | DefKind::TestBinderConstraints => false,
1179    }
1180}
1181
1182fn should_encode_generics(def_kind: DefKind) -> bool {
1183    match def_kind {
1184        DefKind::Struct
1185        | DefKind::Union
1186        | DefKind::Enum
1187        | DefKind::Variant
1188        | DefKind::Trait
1189        | DefKind::TyAlias
1190        | DefKind::ForeignTy
1191        | DefKind::TraitAlias
1192        | DefKind::AssocTy
1193        | DefKind::Fn
1194        | DefKind::Const
1195        | DefKind::Static { .. }
1196        | DefKind::Ctor(..)
1197        | DefKind::AssocFn
1198        | DefKind::AssocConst
1199        | DefKind::AnonConst
1200        | DefKind::OpaqueTy
1201        | DefKind::Impl { .. }
1202        | DefKind::Field
1203        | DefKind::TyParam
1204        | DefKind::Closure
1205        | DefKind::SyntheticCoroutineBody => true,
1206        DefKind::Mod
1207        | DefKind::ForeignMod
1208        | DefKind::ConstParam
1209        | DefKind::Macro(..)
1210        | DefKind::Use
1211        | DefKind::LifetimeParam
1212        | DefKind::GlobalAsm
1213        | DefKind::ExternCrate
1214        | DefKind::TestBinderConstraints => false,
1215    }
1216}
1217
1218fn should_encode_type(tcx: TyCtxt<'_>, def_id: LocalDefId, def_kind: DefKind) -> bool {
1219    match def_kind {
1220        DefKind::Struct
1221        | DefKind::Union
1222        | DefKind::Enum
1223        | DefKind::Variant
1224        | DefKind::Ctor(..)
1225        | DefKind::Field
1226        | DefKind::Fn
1227        | DefKind::Const
1228        | DefKind::Static { nested: false, .. }
1229        | DefKind::TyAlias
1230        | DefKind::ForeignTy
1231        | DefKind::Impl { .. }
1232        | DefKind::AssocFn
1233        | DefKind::AssocConst
1234        | DefKind::Closure
1235        | DefKind::ConstParam
1236        | DefKind::AnonConst
1237        | DefKind::SyntheticCoroutineBody => true,
1238
1239        DefKind::OpaqueTy => {
1240            let origin = tcx.local_opaque_ty_origin(def_id);
1241            if let hir::OpaqueTyOrigin::FnReturn { parent, .. }
1242            | hir::OpaqueTyOrigin::AsyncFn { parent, .. } = origin
1243                && let hir::Node::TraitItem(trait_item) = tcx.hir_node_by_def_id(parent)
1244                && let (_, hir::TraitFn::Required(..)) = trait_item.expect_fn()
1245            {
1246                false
1247            } else {
1248                true
1249            }
1250        }
1251
1252        DefKind::AssocTy => {
1253            let assoc_item = tcx.associated_item(def_id);
1254            match assoc_item.container {
1255                ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => true,
1256                ty::AssocContainer::Trait => assoc_item.defaultness(tcx).has_value(),
1257            }
1258        }
1259        DefKind::TyParam => {
1260            let hir::Node::GenericParam(param) = tcx.hir_node_by_def_id(def_id) else { bug_impl(None, format_args!("impossible case reached"), Location::caller())bug!() };
1261            let hir::GenericParamKind::Type { default, .. } = param.kind else { bug_impl(None, format_args!("impossible case reached"), Location::caller())bug!() };
1262            default.is_some()
1263        }
1264
1265        DefKind::Trait
1266        | DefKind::TraitAlias
1267        | DefKind::Mod
1268        | DefKind::ForeignMod
1269        | DefKind::Macro(..)
1270        | DefKind::Static { nested: true, .. }
1271        | DefKind::Use
1272        | DefKind::LifetimeParam
1273        | DefKind::GlobalAsm
1274        | DefKind::ExternCrate
1275        | DefKind::TestBinderConstraints => false,
1276    }
1277}
1278
1279fn should_encode_fn_sig(def_kind: DefKind) -> bool {
1280    match def_kind {
1281        DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) => true,
1282
1283        DefKind::Struct
1284        | DefKind::Union
1285        | DefKind::Enum
1286        | DefKind::Variant
1287        | DefKind::Field
1288        | DefKind::Const
1289        | DefKind::Static { .. }
1290        | DefKind::Ctor(..)
1291        | DefKind::TyAlias
1292        | DefKind::OpaqueTy
1293        | DefKind::ForeignTy
1294        | DefKind::Impl { .. }
1295        | DefKind::AssocConst
1296        | DefKind::Closure
1297        | DefKind::ConstParam
1298        | DefKind::AnonConst
1299        | DefKind::AssocTy
1300        | DefKind::TyParam
1301        | DefKind::Trait
1302        | DefKind::TraitAlias
1303        | DefKind::Mod
1304        | DefKind::ForeignMod
1305        | DefKind::Macro(..)
1306        | DefKind::Use
1307        | DefKind::LifetimeParam
1308        | DefKind::GlobalAsm
1309        | DefKind::ExternCrate
1310        | DefKind::SyntheticCoroutineBody
1311        | DefKind::TestBinderConstraints => false,
1312    }
1313}
1314
1315fn should_encode_constness(def_kind: DefKind) -> bool {
1316    match def_kind {
1317        DefKind::Fn
1318        | DefKind::AssocFn
1319        | DefKind::Closure
1320        | DefKind::Ctor(_, CtorKind::Fn)
1321        | DefKind::Impl { of_trait: false } => true,
1322
1323        DefKind::Struct
1324        | DefKind::Union
1325        | DefKind::Enum
1326        | DefKind::Field
1327        | DefKind::Const
1328        | DefKind::AssocConst
1329        | DefKind::AnonConst
1330        | DefKind::Static { .. }
1331        | DefKind::TyAlias
1332        | DefKind::OpaqueTy
1333        | DefKind::Impl { .. }
1334        | DefKind::ForeignTy
1335        | DefKind::ConstParam
1336        | DefKind::AssocTy
1337        | DefKind::TyParam
1338        | DefKind::Trait
1339        | DefKind::TraitAlias
1340        | DefKind::Mod
1341        | DefKind::ForeignMod
1342        | DefKind::Macro(..)
1343        | DefKind::Use
1344        | DefKind::LifetimeParam
1345        | DefKind::GlobalAsm
1346        | DefKind::ExternCrate
1347        | DefKind::Ctor(_, CtorKind::Const)
1348        | DefKind::Variant
1349        | DefKind::SyntheticCoroutineBody
1350        | DefKind::TestBinderConstraints => false,
1351    }
1352}
1353
1354fn should_encode_const(def_kind: DefKind) -> bool {
1355    match def_kind {
1356        // FIXME(mgca): should we remove Const and AssocConst here?
1357        DefKind::Const | DefKind::AssocConst | DefKind::AnonConst => true,
1358
1359        DefKind::Struct
1360        | DefKind::Union
1361        | DefKind::Enum
1362        | DefKind::Variant
1363        | DefKind::Ctor(..)
1364        | DefKind::Field
1365        | DefKind::Fn
1366        | DefKind::Static { .. }
1367        | DefKind::TyAlias
1368        | DefKind::OpaqueTy
1369        | DefKind::ForeignTy
1370        | DefKind::Impl { .. }
1371        | DefKind::AssocFn
1372        | DefKind::Closure
1373        | DefKind::ConstParam
1374        | DefKind::AssocTy
1375        | DefKind::TyParam
1376        | DefKind::Trait
1377        | DefKind::TraitAlias
1378        | DefKind::Mod
1379        | DefKind::ForeignMod
1380        | DefKind::Macro(..)
1381        | DefKind::Use
1382        | DefKind::LifetimeParam
1383        | DefKind::GlobalAsm
1384        | DefKind::ExternCrate
1385        | DefKind::SyntheticCoroutineBody
1386        | DefKind::TestBinderConstraints => false,
1387    }
1388}
1389
1390impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1391    fn encode_attrs(&mut self, def_id: LocalDefId) {
1392        let tcx = self.tcx;
1393        let mut state = AnalyzeAttrState {
1394            is_exported: tcx.effective_visibilities(()).is_exported(def_id),
1395            is_doc_hidden: false,
1396        };
1397        let attr_iter = tcx
1398            .hir_attrs(tcx.local_def_id_to_hir_id(def_id))
1399            .iter()
1400            .filter(|attr| analyze_attr(*attr, &mut state));
1401
1402        {
    {
        let value = attr_iter;
        let lazy = self.lazy_array(value);
        self.tables.attributes.set_some(def_id.to_def_id().index, lazy);
    }
};record_array!(self.tables.attributes[def_id.to_def_id()] <- attr_iter);
1403
1404        let mut attr_flags = AttrFlags::empty();
1405        if state.is_doc_hidden {
1406            attr_flags |= AttrFlags::IS_DOC_HIDDEN;
1407        }
1408        self.tables.attr_flags.set(def_id.local_def_index, attr_flags);
1409    }
1410
1411    fn encode_def_ids(&mut self) {
1412        self.encode_info_for_mod(CRATE_DEF_ID);
1413
1414        // Proc-macro crates only export proc-macro items, which are looked
1415        // up using `proc_macro_data`
1416        if self.is_proc_macro {
1417            return;
1418        }
1419
1420        let tcx = self.tcx;
1421
1422        for local_id in tcx.iter_local_def_id() {
1423            let def_id = local_id.to_def_id();
1424            let def_kind = tcx.def_kind(local_id);
1425            self.tables.def_kind.set_some(def_id.index, def_kind);
1426
1427            // The `DefCollector` will sometimes create unnecessary `DefId`s
1428            // for trivial const arguments which are directly lowered to
1429            // `ConstArgKind::Path`. We never actually access this `DefId`
1430            // anywhere so we don't need to encode it for other crates.
1431            // FIXME(mgca): This probably isn't true, they probably are accessed, but, test case?
1432            if def_kind == DefKind::AnonConst
1433                && #[allow(non_exhaustive_omitted_patterns)] match tcx.hir_node_by_def_id(local_id)
    {
    hir::Node::ConstArg(_) |
        hir::Node::Infer(hir::InferArg { kind: hir::InferArgKind::Const, .. })
        => true,
    _ => false,
}matches!(
1434                    tcx.hir_node_by_def_id(local_id),
1435                    hir::Node::ConstArg(_)
1436                        | hir::Node::Infer(hir::InferArg { kind: hir::InferArgKind::Const, .. })
1437                )
1438            {
1439                continue;
1440            }
1441
1442            if def_kind == DefKind::Field
1443                && let hir::Node::Field(field) = tcx.hir_node_by_def_id(local_id)
1444                && let Some(anon) = field.default
1445            {
1446                {
    {
        let value = anon.def_id.to_def_id();
        let lazy = self.lazy(value);
        self.tables.default_fields.set_some(def_id.index, lazy);
    }
};record!(self.tables.default_fields[def_id] <- anon.def_id.to_def_id());
1447            }
1448
1449            if should_encode_span(def_kind) {
1450                let def_span = tcx.def_span(local_id);
1451                {
    {
        let value = def_span;
        let lazy = self.lazy(value);
        self.tables.def_span.set_some(def_id.index, lazy);
    }
};record!(self.tables.def_span[def_id] <- def_span);
1452            }
1453            if should_encode_attrs(def_kind) {
1454                self.encode_attrs(local_id);
1455            }
1456            if should_encode_expn_that_defined(def_kind) {
1457                {
    {
        let value = self.tcx.expn_that_defined(def_id);
        let lazy = self.lazy(value);
        self.tables.expn_that_defined.set_some(def_id.index, lazy);
    }
};record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id));
1458            }
1459            if should_encode_span(def_kind)
1460                && let Some(ident_span) = tcx.def_ident_span(def_id)
1461            {
1462                {
    {
        let value = ident_span;
        let lazy = self.lazy(value);
        self.tables.def_ident_span.set_some(def_id.index, lazy);
    }
};record!(self.tables.def_ident_span[def_id] <- ident_span);
1463            }
1464            if def_kind.has_codegen_attrs() {
1465                {
    {
        let value = self.tcx.codegen_fn_attrs(def_id);
        let lazy = self.lazy(value);
        self.tables.codegen_fn_attrs.set_some(def_id.index, lazy);
    }
};record!(self.tables.codegen_fn_attrs[def_id] <- self.tcx.codegen_fn_attrs(def_id));
1466            }
1467            if should_encode_visibility(def_kind) {
1468                let vis = self
1469                    .tcx
1470                    .local_visibility(local_id)
1471                    .map_id(|mod_id| mod_id.to_local_def_id().local_def_index);
1472                {
    {
        let value = vis;
        let lazy = self.lazy(value);
        self.tables.visibility.set_some(def_id.index, lazy);
    }
};record!(self.tables.visibility[def_id] <- vis);
1473            }
1474            if should_encode_stability(def_kind) {
1475                self.encode_stability(def_id);
1476                self.encode_const_stability(def_id);
1477                self.encode_default_body_stability(def_id);
1478                self.encode_deprecation(def_id);
1479            }
1480            if should_encode_variances(tcx, def_id, def_kind) {
1481                let v = self.tcx.variances_of(def_id);
1482                {
    {
        let value = v;
        let lazy = self.lazy_array(value);
        self.tables.variances_of.set_some(def_id.index, lazy);
    }
};record_array!(self.tables.variances_of[def_id] <- v);
1483            }
1484            if should_encode_fn_sig(def_kind) {
1485                {
    {
        let value = tcx.fn_sig(def_id);
        let lazy = self.lazy(value);
        self.tables.fn_sig.set_some(def_id.index, lazy);
    }
};record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1486            }
1487            if should_encode_generics(def_kind) {
1488                let g = tcx.generics_of(def_id);
1489                {
    {
        let value = g;
        let lazy = self.lazy(value);
        self.tables.generics_of.set_some(def_id.index, lazy);
    }
};record!(self.tables.generics_of[def_id] <- g);
1490                {
    {
        let value = self.tcx.explicit_clauses_of(def_id);
        let lazy = self.lazy(value);
        self.tables.explicit_clauses_of.set_some(def_id.index, lazy);
    }
};record!(self.tables.explicit_clauses_of[def_id] <- self.tcx.explicit_clauses_of(def_id));
1491                let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
1492                {
    {
        let value = inferred_outlives;
        let lazy = self.lazy_array(value);
        self.tables.inferred_outlives_of.set(def_id.index, lazy);
    }
};record_defaulted_array!(self.tables.inferred_outlives_of[def_id] <- inferred_outlives);
1493
1494                for param in &g.own_params {
1495                    if let ty::GenericParamDefKind::Const { has_default: true, .. } = param.kind {
1496                        let default = self.tcx.const_param_default(param.def_id);
1497                        {
    {
        let value = default;
        let lazy = self.lazy(value);
        self.tables.const_param_default.set_some(param.def_id.index, lazy);
    }
};record!(self.tables.const_param_default[param.def_id] <- default);
1498                    }
1499                }
1500            }
1501            if tcx.is_conditionally_const(def_id) {
1502                {
    {
        let value = self.tcx.const_conditions(def_id);
        let lazy = self.lazy(value);
        self.tables.const_conditions.set_some(def_id.index, lazy);
    }
};record!(self.tables.const_conditions[def_id] <- self.tcx.const_conditions(def_id));
1503            }
1504            if should_encode_type(tcx, local_id, def_kind) {
1505                {
    {
        let value = self.tcx.type_of(def_id);
        let lazy = self.lazy(value);
        self.tables.type_of.set_some(def_id.index, lazy);
    }
};record!(self.tables.type_of[def_id] <- self.tcx.type_of(def_id));
1506            }
1507            if should_encode_constness(def_kind) {
1508                let constness = self.tcx.constness(def_id);
1509                self.tables.constness.set(def_id.index, constness);
1510            }
1511            if let DefKind::Fn | DefKind::AssocFn = def_kind {
1512                let asyncness = tcx.asyncness(def_id);
1513                self.tables.asyncness.set(def_id.index, asyncness);
1514                {
    {
        let value = tcx.fn_arg_idents(def_id);
        let lazy = self.lazy_array(value);
        self.tables.fn_arg_idents.set_some(def_id.index, lazy);
    }
};record_array!(self.tables.fn_arg_idents[def_id] <- tcx.fn_arg_idents(def_id));
1515            }
1516            if let Some(name) = tcx.intrinsic(def_id) {
1517                {
    {
        let value = name;
        let lazy = self.lazy(value);
        self.tables.intrinsic.set_some(def_id.index, lazy);
    }
};record!(self.tables.intrinsic[def_id] <- name);
1518            }
1519            if let DefKind::TyParam | DefKind::Trait = def_kind {
1520                let default = self.tcx.object_lifetime_default(def_id);
1521                {
    {
        let value = default;
        let lazy = self.lazy(value);
        self.tables.object_lifetime_default.set_some(def_id.index, lazy);
    }
};record!(self.tables.object_lifetime_default[def_id] <- default);
1522            }
1523            if let DefKind::Trait = def_kind {
1524                {
    {
        let value = self.tcx.trait_def(def_id);
        let lazy = self.lazy(value);
        self.tables.trait_def.set_some(def_id.index, lazy);
    }
};record!(self.tables.trait_def[def_id] <- self.tcx.trait_def(def_id));
1525                {
    {
        let value = self.tcx.explicit_super_clauses_of(def_id).skip_binder();
        let lazy = self.lazy_array(value);
        self.tables.explicit_super_clauses_of.set(def_id.index, lazy);
    }
};record_defaulted_array!(self.tables.explicit_super_clauses_of[def_id] <-
1526                    self.tcx.explicit_super_clauses_of(def_id).skip_binder());
1527                {
    {
        let value =
            self.tcx.explicit_implied_clauses_of(def_id).skip_binder();
        let lazy = self.lazy_array(value);
        self.tables.explicit_implied_clauses_of.set(def_id.index, lazy);
    }
};record_defaulted_array!(self.tables.explicit_implied_clauses_of[def_id] <-
1528                    self.tcx.explicit_implied_clauses_of(def_id).skip_binder());
1529                let module_children = self.tcx.module_children_local(local_id);
1530                {
    {
        let value =
            module_children.iter().map(|child| child.res.def_id().index);
        let lazy = self.lazy_array(value);
        self.tables.module_children_non_reexports.set_some(def_id.index,
            lazy);
    }
};record_array!(self.tables.module_children_non_reexports[def_id] <-
1531                    module_children.iter().map(|child| child.res.def_id().index));
1532                if self.tcx.is_const_trait(def_id) {
1533                    {
    {
        let value =
            self.tcx.explicit_implied_const_bounds(def_id).skip_binder();
        let lazy = self.lazy_array(value);
        self.tables.explicit_implied_const_bounds.set(def_id.index, lazy);
    }
};record_defaulted_array!(self.tables.explicit_implied_const_bounds[def_id]
1534                        <- self.tcx.explicit_implied_const_bounds(def_id).skip_binder());
1535                }
1536            }
1537            if let DefKind::TraitAlias = def_kind {
1538                {
    {
        let value = self.tcx.trait_def(def_id);
        let lazy = self.lazy(value);
        self.tables.trait_def.set_some(def_id.index, lazy);
    }
};record!(self.tables.trait_def[def_id] <- self.tcx.trait_def(def_id));
1539                {
    {
        let value = self.tcx.explicit_super_clauses_of(def_id).skip_binder();
        let lazy = self.lazy_array(value);
        self.tables.explicit_super_clauses_of.set(def_id.index, lazy);
    }
};record_defaulted_array!(self.tables.explicit_super_clauses_of[def_id] <-
1540                    self.tcx.explicit_super_clauses_of(def_id).skip_binder());
1541                {
    {
        let value =
            self.tcx.explicit_implied_clauses_of(def_id).skip_binder();
        let lazy = self.lazy_array(value);
        self.tables.explicit_implied_clauses_of.set(def_id.index, lazy);
    }
};record_defaulted_array!(self.tables.explicit_implied_clauses_of[def_id] <-
1542                    self.tcx.explicit_implied_clauses_of(def_id).skip_binder());
1543            }
1544            if let DefKind::Trait | DefKind::Impl { .. } = def_kind {
1545                let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1546                {
    {
        let value =
            associated_item_def_ids.iter().map(|&def_id|
                    {
                        if !def_id.is_local() {
                            ::core::panicking::panic("assertion failed: def_id.is_local()")
                        };
                        def_id.index
                    });
        let lazy = self.lazy_array(value);
        self.tables.associated_item_or_field_def_ids.set_some(def_id.index,
            lazy);
    }
};record_array!(self.tables.associated_item_or_field_def_ids[def_id] <-
1547                    associated_item_def_ids.iter().map(|&def_id| {
1548                        assert!(def_id.is_local());
1549                        def_id.index
1550                    })
1551                );
1552                for &def_id in associated_item_def_ids {
1553                    self.encode_info_for_assoc_item(def_id);
1554                }
1555            }
1556            if let DefKind::Closure | DefKind::SyntheticCoroutineBody = def_kind
1557                && let Some(coroutine_kind) = self.tcx.coroutine_kind(def_id)
1558            {
1559                self.tables.coroutine_kind.set(def_id.index, Some(coroutine_kind))
1560            }
1561            if def_kind == DefKind::Closure
1562                && tcx.type_of(def_id).skip_binder().is_coroutine_closure()
1563            {
1564                let coroutine_for_closure = self.tcx.coroutine_for_closure(def_id);
1565                self.tables
1566                    .coroutine_for_closure
1567                    .set_some(def_id.index, coroutine_for_closure.into());
1568
1569                // If this async closure has a by-move body, record it too.
1570                if tcx.needs_coroutine_by_move_body_def_id(coroutine_for_closure) {
1571                    self.tables.coroutine_by_move_body_def_id.set_some(
1572                        coroutine_for_closure.index,
1573                        self.tcx.coroutine_by_move_body_def_id(coroutine_for_closure).into(),
1574                    );
1575                }
1576            }
1577            if let DefKind::Static { .. } = def_kind {
1578                if !self.tcx.is_foreign_item(def_id) {
1579                    match self.tcx.eval_static_initializer(def_id) {
1580                        Ok(data) => {
    {
        let value = data;
        let lazy = self.lazy(value);
        self.tables.eval_static_initializer.set_some(def_id.index, lazy);
    }
}record!(self.tables.eval_static_initializer[def_id] <- data),
1581                        Err(err) => match err {
1582                            interpret::ErrorHandled::Reported(_, _) => {
1583                                self.tcx.dcx().delayed_bug(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("eval_static_initializer returned an error in metadata emission"))
    })format!(
1584                                    "eval_static_initializer returned an error in metadata emission"
1585                                ));
1586                            }
1587                            interpret::ErrorHandled::TooGeneric(span) => {
1588                                bug_impl(Some(span), format_args!("generic static???"), Location::caller());span_bug!(span, "generic static???");
1589                            }
1590                        },
1591                    };
1592                }
1593            }
1594            if let DefKind::Enum | DefKind::Struct | DefKind::Union = def_kind {
1595                self.encode_info_for_adt(local_id);
1596            }
1597            if let DefKind::Mod = def_kind {
1598                self.encode_info_for_mod(local_id);
1599            }
1600            if let DefKind::Macro(_) = def_kind {
1601                self.encode_info_for_macro(local_id);
1602            }
1603            if let DefKind::TyAlias = def_kind {
1604                self.tables
1605                    .type_alias_is_checked
1606                    .set(def_id.index, self.tcx.type_alias_is_checked(def_id));
1607                if self.tcx.type_alias_is_checked(def_id) {
1608                    {
    {
        let value = tcx.args_known_to_outlive_alias_params(def_id);
        let lazy = self.lazy(value);
        self.tables.args_known_to_outlive_alias_params.set_some(def_id.index,
            lazy);
    }
};record!(self.tables.args_known_to_outlive_alias_params[def_id] <- tcx.args_known_to_outlive_alias_params(def_id));
1609                }
1610            }
1611            if let DefKind::OpaqueTy = def_kind {
1612                self.encode_explicit_item_bounds(def_id);
1613                self.encode_explicit_item_self_bounds(def_id);
1614                {
    {
        let value = self.tcx.opaque_ty_origin(def_id);
        let lazy = self.lazy(value);
        self.tables.opaque_ty_origin.set_some(def_id.index, lazy);
    }
};record!(self.tables.opaque_ty_origin[def_id] <- self.tcx.opaque_ty_origin(def_id));
1615                self.encode_precise_capturing_args(def_id);
1616                if tcx.is_conditionally_const(def_id) {
1617                    {
    {
        let value = tcx.explicit_implied_const_bounds(def_id).skip_binder();
        let lazy = self.lazy_array(value);
        self.tables.explicit_implied_const_bounds.set(def_id.index, lazy);
    }
};record_defaulted_array!(self.tables.explicit_implied_const_bounds[def_id]
1618                        <- tcx.explicit_implied_const_bounds(def_id).skip_binder());
1619                }
1620                {
    {
        let value = tcx.args_known_to_outlive_alias_params(def_id);
        let lazy = self.lazy(value);
        self.tables.args_known_to_outlive_alias_params.set_some(def_id.index,
            lazy);
    }
};record!(self.tables.args_known_to_outlive_alias_params[def_id] <- tcx.args_known_to_outlive_alias_params(def_id));
1621            }
1622            if let DefKind::AssocTy = def_kind {
1623                let assoc_item = tcx.associated_item(def_id);
1624                match assoc_item.container {
1625                    ty::AssocContainer::Trait => {
1626                        {
    {
        let value = tcx.args_known_to_outlive_alias_params(def_id);
        let lazy = self.lazy(value);
        self.tables.args_known_to_outlive_alias_params.set_some(def_id.index,
            lazy);
    }
};record!(self.tables.args_known_to_outlive_alias_params[def_id] <- tcx.args_known_to_outlive_alias_params(def_id));
1627                    }
1628                    ty::AssocContainer::InherentImpl => {
1629                        {
    {
        let value = tcx.args_known_to_outlive_alias_params(def_id);
        let lazy = self.lazy(value);
        self.tables.args_known_to_outlive_alias_params.set_some(def_id.index,
            lazy);
    }
};record!(self.tables.args_known_to_outlive_alias_params[def_id] <- tcx.args_known_to_outlive_alias_params(def_id));
1630                    }
1631                    ty::AssocContainer::TraitImpl(_) => {}
1632                }
1633            }
1634            if let DefKind::AnonConst = def_kind {
1635                {
    {
        let value = self.tcx.anon_const_kind(def_id);
        let lazy = self.lazy(value);
        self.tables.anon_const_kind.set_some(def_id.index, lazy);
    }
};record!(self.tables.anon_const_kind[def_id] <- self.tcx.anon_const_kind(def_id));
1636            }
1637            if let DefKind::Const | DefKind::AssocConst = def_kind {
1638                {
    {
        let value = self.tcx.const_of_item(def_id);
        let lazy = self.lazy(value);
        self.tables.const_of_item.set_some(def_id.index, lazy);
    }
};record!(self.tables.const_of_item[def_id] <- self.tcx.const_of_item(def_id));
1639            }
1640            if tcx.impl_method_has_trait_impl_trait_tys(def_id)
1641                && let Ok(table) = self.tcx.collect_return_position_impl_trait_in_trait_tys(def_id)
1642            {
1643                {
    {
        let value = table;
        let lazy = self.lazy(value);
        self.tables.collect_return_position_impl_trait_in_trait_tys.set_some(def_id.index,
            lazy);
    }
};record!(self.tables.collect_return_position_impl_trait_in_trait_tys[def_id] <- table);
1644            }
1645            if let DefKind::Impl { .. } | DefKind::Trait = def_kind {
1646                let table = tcx.associated_types_for_impl_traits_in_trait_or_impl(def_id);
1647                {
    {
        let value = table;
        let lazy = self.lazy(value);
        self.tables.associated_types_for_impl_traits_in_trait_or_impl.set_some(def_id.index,
            lazy);
    }
};record!(self.tables.associated_types_for_impl_traits_in_trait_or_impl[def_id] <- table);
1648            }
1649        }
1650
1651        for (def_id, impls) in &tcx.crate_inherent_impls(()).0.inherent_impls {
1652            {
    {
        let value =
            impls.iter().map(|def_id|
                    {
                        if !def_id.is_local() {
                            ::core::panicking::panic("assertion failed: def_id.is_local()")
                        };
                        def_id.index
                    });
        let lazy = self.lazy_array(value);
        self.tables.inherent_impls.set(def_id.to_def_id().index, lazy);
    }
};record_defaulted_array!(self.tables.inherent_impls[def_id.to_def_id()] <- impls.iter().map(|def_id| {
1653                assert!(def_id.is_local());
1654                def_id.index
1655            }));
1656        }
1657
1658        for (def_id, res_map) in &tcx.resolutions(()).doc_link_resolutions {
1659            {
    {
        let value = res_map;
        let lazy = self.lazy(value);
        self.tables.doc_link_resolutions.set_some(def_id.to_def_id().index,
            lazy);
    }
};record!(self.tables.doc_link_resolutions[def_id.to_def_id()] <- res_map);
1660        }
1661
1662        for (def_id, traits) in &tcx.resolutions(()).doc_link_traits_in_scope {
1663            {
    {
        let value = traits;
        let lazy = self.lazy_array(value);
        self.tables.doc_link_traits_in_scope.set_some(def_id.to_def_id().index,
            lazy);
    }
};record_array!(self.tables.doc_link_traits_in_scope[def_id.to_def_id()] <- traits);
1664        }
1665    }
1666
1667    fn encode_externally_implementable_items(&mut self) -> LazyArray<EiiMapEncodedKeyValue> {
1668        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
1669        let externally_implementable_items = self.tcx.externally_implementable_items(LOCAL_CRATE);
1670
1671        self.lazy_array(externally_implementable_items.iter().map(
1672            |(foreign_item, (decl, impls))| {
1673                (
1674                    *foreign_item,
1675                    (decl.clone(), impls.iter().map(|(impl_did, i)| (*impl_did, *i)).collect()),
1676                )
1677            },
1678        ))
1679    }
1680
1681    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("encode_info_for_adt",
                                    "rustc_metadata::rmeta::encoder", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1681u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("local_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("local_def_id");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&local_def_id)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let def_id = local_def_id.to_def_id();
            let tcx = self.tcx;
            let adt_def = tcx.adt_def(def_id);
            {
                {
                    let value = adt_def.repr();
                    let lazy = self.lazy(value);
                    self.tables.repr_options.set_some(def_id.index, lazy);
                }
            };
            let params_in_repr = self.tcx.params_in_repr(def_id);
            {
                {
                    let value = params_in_repr;
                    let lazy = self.lazy(value);
                    self.tables.params_in_repr.set_some(def_id.index, lazy);
                }
            };
            if adt_def.is_enum() {
                let module_children = tcx.module_children_local(local_def_id);
                {
                    {
                        let value =
                            module_children.iter().map(|child|
                                    child.res.def_id().index);
                        let lazy = self.lazy_array(value);
                        self.tables.module_children_non_reexports.set_some(def_id.index,
                            lazy);
                    }
                };
            } else {
                if true {
                    {
                        match (&adt_def.variants().len(), &1) {
                            (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);
                                }
                            }
                        }
                    };
                };
                if true {
                    {
                        match (&adt_def.non_enum_variant().def_id, &def_id) {
                            (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);
                                }
                            }
                        }
                    };
                };
            }
            for (idx, variant) in adt_def.variants().iter_enumerated() {
                let data =
                    VariantData {
                        discr: variant.discr,
                        idx,
                        ctor: variant.ctor.map(|(kind, def_id)|
                                (kind, def_id.index)),
                        is_non_exhaustive: variant.is_field_list_non_exhaustive(),
                    };
                {
                    {
                        let value = data;
                        let lazy = self.lazy(value);
                        self.tables.variant_data.set_some(variant.def_id.index,
                            lazy);
                    }
                };
                {
                    {
                        let value =
                            variant.fields.iter().map(|f|
                                    {
                                        if !f.did.is_local() {
                                            ::core::panicking::panic("assertion failed: f.did.is_local()")
                                        };
                                        f.did.index
                                    });
                        let lazy = self.lazy_array(value);
                        self.tables.associated_item_or_field_def_ids.set_some(variant.def_id.index,
                            lazy);
                    }
                };
                for field in &variant.fields {
                    self.tables.safety.set(field.did.index, field.safety);
                    {
                        {
                            let value = field.mut_restriction;
                            let lazy = self.lazy(value);
                            self.tables.mut_restriction.set_some(field.did.index, lazy);
                        }
                    };
                }
                if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor {
                    let fn_sig = tcx.fn_sig(ctor_def_id);
                    {
                        {
                            let value = fn_sig;
                            let lazy = self.lazy(value);
                            self.tables.fn_sig.set_some(variant.def_id.index, lazy);
                        }
                    };
                }
            }
            if let Some(destructor) = tcx.adt_destructor(local_def_id) {
                {
                    {
                        let value = destructor;
                        let lazy = self.lazy(value);
                        self.tables.adt_destructor.set_some(def_id.index, lazy);
                    }
                };
            }
            if let Some(destructor) = tcx.adt_async_destructor(local_def_id) {
                {
                    {
                        let value = destructor;
                        let lazy = self.lazy(value);
                        self.tables.adt_async_destructor.set_some(def_id.index,
                            lazy);
                    }
                };
            }
        }
    }
}#[instrument(level = "trace", skip(self))]
1682    fn encode_info_for_adt(&mut self, local_def_id: LocalDefId) {
1683        let def_id = local_def_id.to_def_id();
1684        let tcx = self.tcx;
1685        let adt_def = tcx.adt_def(def_id);
1686        record!(self.tables.repr_options[def_id] <- adt_def.repr());
1687
1688        let params_in_repr = self.tcx.params_in_repr(def_id);
1689        record!(self.tables.params_in_repr[def_id] <- params_in_repr);
1690
1691        if adt_def.is_enum() {
1692            let module_children = tcx.module_children_local(local_def_id);
1693            record_array!(self.tables.module_children_non_reexports[def_id] <-
1694                module_children.iter().map(|child| child.res.def_id().index));
1695        } else {
1696            // For non-enum, there is only one variant, and its def_id is the adt's.
1697            debug_assert_eq!(adt_def.variants().len(), 1);
1698            debug_assert_eq!(adt_def.non_enum_variant().def_id, def_id);
1699            // Therefore, the loop over variants will encode its fields as the adt's children.
1700        }
1701
1702        for (idx, variant) in adt_def.variants().iter_enumerated() {
1703            let data = VariantData {
1704                discr: variant.discr,
1705                idx,
1706                ctor: variant.ctor.map(|(kind, def_id)| (kind, def_id.index)),
1707                is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1708            };
1709            record!(self.tables.variant_data[variant.def_id] <- data);
1710
1711            record_array!(self.tables.associated_item_or_field_def_ids[variant.def_id] <- variant.fields.iter().map(|f| {
1712                assert!(f.did.is_local());
1713                f.did.index
1714            }));
1715
1716            for field in &variant.fields {
1717                self.tables.safety.set(field.did.index, field.safety);
1718                record!(
1719                    self.tables.mut_restriction[field.did] <- field.mut_restriction
1720                );
1721            }
1722
1723            if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor {
1724                let fn_sig = tcx.fn_sig(ctor_def_id);
1725                // FIXME only encode signature for ctor_def_id
1726                record!(self.tables.fn_sig[variant.def_id] <- fn_sig);
1727            }
1728        }
1729
1730        if let Some(destructor) = tcx.adt_destructor(local_def_id) {
1731            record!(self.tables.adt_destructor[def_id] <- destructor);
1732        }
1733
1734        if let Some(destructor) = tcx.adt_async_destructor(local_def_id) {
1735            record!(self.tables.adt_async_destructor[def_id] <- destructor);
1736        }
1737    }
1738
1739    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("encode_info_for_mod",
                                    "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1739u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("local_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("local_def_id");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&local_def_id)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx;
            let def_id = local_def_id.to_def_id();
            if self.is_proc_macro {
                {
                    {
                        let value = tcx.expn_that_defined(local_def_id);
                        let lazy = self.lazy(value);
                        self.tables.expn_that_defined.set_some(def_id.index, lazy);
                    }
                };
            } else {
                let module_children = tcx.module_children_local(local_def_id);
                {
                    {
                        let value =
                            module_children.iter().filter(|child|
                                        child.reexport_chain.is_empty()).map(|child|
                                    child.res.def_id().index);
                        let lazy = self.lazy_array(value);
                        self.tables.module_children_non_reexports.set_some(def_id.index,
                            lazy);
                    }
                };
                {
                    {
                        let value =
                            module_children.iter().filter(|child|
                                    !child.reexport_chain.is_empty());
                        let lazy = self.lazy_array(value);
                        self.tables.module_children_reexports.set(def_id.index,
                            lazy);
                    }
                };
                let ambig_module_children =
                    tcx.resolutions(()).ambig_module_children.get(&local_def_id).map_or_default(|v|
                            &v[..]);
                {
                    {
                        let value = ambig_module_children;
                        let lazy = self.lazy_array(value);
                        self.tables.ambig_module_children.set(def_id.index, lazy);
                    }
                };
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1740    fn encode_info_for_mod(&mut self, local_def_id: LocalDefId) {
1741        let tcx = self.tcx;
1742        let def_id = local_def_id.to_def_id();
1743
1744        // If we are encoding a proc-macro crates, `encode_info_for_mod` will
1745        // only ever get called for the crate root. We still want to encode
1746        // the crate root for consistency with other crates (some of the resolver
1747        // code uses it). However, we skip encoding anything relating to child
1748        // items - we encode information about proc-macros later on.
1749        if self.is_proc_macro {
1750            // Encode this here because we don't do it in encode_def_ids.
1751            record!(self.tables.expn_that_defined[def_id] <- tcx.expn_that_defined(local_def_id));
1752        } else {
1753            let module_children = tcx.module_children_local(local_def_id);
1754
1755            record_array!(self.tables.module_children_non_reexports[def_id] <-
1756                module_children.iter().filter(|child| child.reexport_chain.is_empty())
1757                    .map(|child| child.res.def_id().index));
1758
1759            record_defaulted_array!(self.tables.module_children_reexports[def_id] <-
1760                module_children.iter().filter(|child| !child.reexport_chain.is_empty()));
1761
1762            let ambig_module_children = tcx
1763                .resolutions(())
1764                .ambig_module_children
1765                .get(&local_def_id)
1766                .map_or_default(|v| &v[..]);
1767            record_defaulted_array!(self.tables.ambig_module_children[def_id] <-
1768                ambig_module_children);
1769        }
1770    }
1771
1772    fn encode_explicit_item_bounds(&mut self, def_id: DefId) {
1773        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/rmeta/encoder.rs:1773",
                        "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1773u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                        ::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!("EncodeContext::encode_explicit_item_bounds({0:?})",
                                                    def_id) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id);
1774        let bounds = self.tcx.explicit_item_bounds(def_id).skip_binder();
1775        {
    {
        let value = bounds;
        let lazy = self.lazy_array(value);
        self.tables.explicit_item_bounds.set(def_id.index, lazy);
    }
};record_defaulted_array!(self.tables.explicit_item_bounds[def_id] <- bounds);
1776    }
1777
1778    fn encode_explicit_item_self_bounds(&mut self, def_id: DefId) {
1779        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/rmeta/encoder.rs:1779",
                        "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1779u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                        ::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!("EncodeContext::encode_explicit_item_self_bounds({0:?})",
                                                    def_id) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("EncodeContext::encode_explicit_item_self_bounds({:?})", def_id);
1780        let bounds = self.tcx.explicit_item_self_bounds(def_id).skip_binder();
1781        {
    {
        let value = bounds;
        let lazy = self.lazy_array(value);
        self.tables.explicit_item_self_bounds.set(def_id.index, lazy);
    }
};record_defaulted_array!(self.tables.explicit_item_self_bounds[def_id] <- bounds);
1782    }
1783
1784    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("encode_info_for_assoc_item",
                                    "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1784u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx;
            let item = tcx.associated_item(def_id);
            if #[allow(non_exhaustive_omitted_patterns)] match item.container
                    {
                    AssocContainer::Trait | AssocContainer::TraitImpl(_) =>
                        true,
                    _ => false,
                } {
                self.tables.defaultness.set(def_id.index,
                    item.defaultness(tcx));
            }
            {
                {
                    let value = item.container;
                    let lazy = self.lazy(value);
                    self.tables.assoc_container.set_some(def_id.index, lazy);
                }
            };
            if let AssocContainer::Trait = item.container && item.is_type() {
                self.encode_explicit_item_bounds(def_id);
                self.encode_explicit_item_self_bounds(def_id);
                if tcx.is_conditionally_const(def_id) {
                    {
                        {
                            let value =
                                self.tcx.explicit_implied_const_bounds(def_id).skip_binder();
                            let lazy = self.lazy_array(value);
                            self.tables.explicit_implied_const_bounds.set(def_id.index,
                                lazy);
                        }
                    };
                }
            }
            if let ty::AssocKind::Type {
                    data: ty::AssocTypeData::Rpitit(rpitit_info) } = item.kind {
                {
                    {
                        let value = rpitit_info;
                        let lazy = self.lazy(value);
                        self.tables.opt_rpitit_info.set_some(def_id.index, lazy);
                    }
                };
                if #[allow(non_exhaustive_omitted_patterns)] match rpitit_info
                        {
                        ty::ImplTraitInTraitData::Trait { .. } => true,
                        _ => false,
                    } {
                    {
                        {
                            let value = self.tcx.assumed_wf_types_for_rpitit(def_id);
                            let lazy = self.lazy_array(value);
                            self.tables.assumed_wf_types_for_rpitit.set_some(def_id.index,
                                lazy);
                        }
                    };
                    self.encode_precise_capturing_args(def_id);
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1785    fn encode_info_for_assoc_item(&mut self, def_id: DefId) {
1786        let tcx = self.tcx;
1787        let item = tcx.associated_item(def_id);
1788
1789        if matches!(item.container, AssocContainer::Trait | AssocContainer::TraitImpl(_)) {
1790            self.tables.defaultness.set(def_id.index, item.defaultness(tcx));
1791        }
1792
1793        record!(self.tables.assoc_container[def_id] <- item.container);
1794
1795        if let AssocContainer::Trait = item.container
1796            && item.is_type()
1797        {
1798            self.encode_explicit_item_bounds(def_id);
1799            self.encode_explicit_item_self_bounds(def_id);
1800            if tcx.is_conditionally_const(def_id) {
1801                record_defaulted_array!(self.tables.explicit_implied_const_bounds[def_id]
1802                    <- self.tcx.explicit_implied_const_bounds(def_id).skip_binder());
1803            }
1804        }
1805        if let ty::AssocKind::Type { data: ty::AssocTypeData::Rpitit(rpitit_info) } = item.kind {
1806            record!(self.tables.opt_rpitit_info[def_id] <- rpitit_info);
1807            if matches!(rpitit_info, ty::ImplTraitInTraitData::Trait { .. }) {
1808                record_array!(
1809                    self.tables.assumed_wf_types_for_rpitit[def_id]
1810                        <- self.tcx.assumed_wf_types_for_rpitit(def_id)
1811                );
1812                self.encode_precise_capturing_args(def_id);
1813            }
1814        }
1815    }
1816
1817    fn encode_precise_capturing_args(&mut self, def_id: DefId) {
1818        let Some(precise_capturing_args) = self.tcx.rendered_precise_capturing_args(def_id) else {
1819            return;
1820        };
1821
1822        {
    {
        let value = precise_capturing_args;
        let lazy = self.lazy_array(value);
        self.tables.rendered_precise_capturing_args.set_some(def_id.index,
            lazy);
    }
};record_array!(self.tables.rendered_precise_capturing_args[def_id] <- precise_capturing_args);
1823    }
1824
1825    fn encode_mir(&mut self) {
1826        if self.is_proc_macro {
1827            return;
1828        }
1829
1830        let tcx = self.tcx;
1831        let reachable_set = tcx.reachable_set(());
1832
1833        let keys_and_jobs = tcx.mir_keys(()).iter().filter_map(|&def_id| {
1834            let (encode_const, encode_opt) = should_encode_mir(tcx, reachable_set, def_id);
1835            if encode_const || encode_opt { Some((def_id, encode_const, encode_opt)) } else { None }
1836        });
1837        for (def_id, encode_const, encode_opt) in keys_and_jobs {
1838            if true {
    if !(encode_const || encode_opt) {
        ::core::panicking::panic("assertion failed: encode_const || encode_opt")
    };
};debug_assert!(encode_const || encode_opt);
1839
1840            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/rmeta/encoder.rs:1840",
                        "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1840u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                        ::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!("EntryBuilder::encode_mir({0:?})",
                                                    def_id) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("EntryBuilder::encode_mir({:?})", def_id);
1841            if encode_opt {
1842                {
    {
        let value = tcx.optimized_mir(def_id);
        let lazy = self.lazy(value);
        self.tables.optimized_mir.set_some(def_id.to_def_id().index, lazy);
    }
};record!(self.tables.optimized_mir[def_id.to_def_id()] <- tcx.optimized_mir(def_id));
1843                self.tables
1844                    .cross_crate_inlinable
1845                    .set(def_id.to_def_id().index, self.tcx.cross_crate_inlinable(def_id));
1846                {
    {
        let value = tcx.closure_saved_names_of_captured_variables(def_id);
        let lazy = self.lazy(value);
        self.tables.closure_saved_names_of_captured_variables.set_some(def_id.to_def_id().index,
            lazy);
    }
};record!(self.tables.closure_saved_names_of_captured_variables[def_id.to_def_id()]
1847                    <- tcx.closure_saved_names_of_captured_variables(def_id));
1848
1849                if self.tcx.is_coroutine(def_id.to_def_id())
1850                    && let Some(witnesses) = tcx.mir_coroutine_witnesses(def_id)
1851                {
1852                    {
    {
        let value = witnesses;
        let lazy = self.lazy(value);
        self.tables.mir_coroutine_witnesses.set_some(def_id.to_def_id().index,
            lazy);
    }
};record!(self.tables.mir_coroutine_witnesses[def_id.to_def_id()] <- witnesses);
1853                }
1854            }
1855            let mut is_trivial = false;
1856            if encode_const {
1857                if let Some((val, ty)) = tcx.trivial_const(def_id) {
1858                    is_trivial = true;
1859                    {
    {
        let value = (val, ty);
        let lazy = self.lazy(value);
        self.tables.trivial_const.set_some(def_id.to_def_id().index, lazy);
    }
};record!(self.tables.trivial_const[def_id.to_def_id()] <- (val, ty));
1860                } else {
1861                    is_trivial = false;
1862                    {
    {
        let value = tcx.mir_for_ctfe(def_id);
        let lazy = self.lazy(value);
        self.tables.mir_for_ctfe.set_some(def_id.to_def_id().index, lazy);
    }
};record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- tcx.mir_for_ctfe(def_id));
1863                }
1864
1865                // FIXME(generic_const_exprs): this feels wrong to have in `encode_mir`
1866                let abstract_const = tcx.thir_abstract_const(def_id);
1867                if let Ok(Some(abstract_const)) = abstract_const {
1868                    {
    {
        let value = abstract_const;
        let lazy = self.lazy(value);
        self.tables.thir_abstract_const.set_some(def_id.to_def_id().index,
            lazy);
    }
};record!(self.tables.thir_abstract_const[def_id.to_def_id()] <- abstract_const);
1869                }
1870
1871                if should_encode_const(tcx.def_kind(def_id)) {
1872                    let qualifs = tcx.mir_const_qualif(def_id);
1873                    {
    {
        let value = qualifs;
        let lazy = self.lazy(value);
        self.tables.mir_const_qualif.set_some(def_id.to_def_id().index, lazy);
    }
};record!(self.tables.mir_const_qualif[def_id.to_def_id()] <- qualifs);
1874                    let body = tcx.hir_maybe_body_owned_by(def_id);
1875                    if let Some(body) = body {
1876                        let const_data = rendered_const(self.tcx, &body, def_id);
1877                        {
    {
        let value = const_data;
        let lazy = self.lazy(value);
        self.tables.rendered_const.set_some(def_id.to_def_id().index, lazy);
    }
};record!(self.tables.rendered_const[def_id.to_def_id()] <- const_data);
1878                    }
1879                }
1880            }
1881            if !is_trivial {
1882                {
    {
        let value = tcx.promoted_mir(def_id);
        let lazy = self.lazy(value);
        self.tables.promoted_mir.set_some(def_id.to_def_id().index, lazy);
    }
};record!(self.tables.promoted_mir[def_id.to_def_id()] <- tcx.promoted_mir(def_id));
1883            }
1884
1885            if self.tcx.is_coroutine(def_id.to_def_id())
1886                && let Some(witnesses) = tcx.mir_coroutine_witnesses(def_id)
1887            {
1888                {
    {
        let value = witnesses;
        let lazy = self.lazy(value);
        self.tables.mir_coroutine_witnesses.set_some(def_id.to_def_id().index,
            lazy);
    }
};record!(self.tables.mir_coroutine_witnesses[def_id.to_def_id()] <- witnesses);
1889            }
1890        }
1891
1892        // Encode all the deduced parameter attributes for everything that has MIR, even for items
1893        // that can't be inlined. But don't if we aren't optimizing in non-incremental mode, to
1894        // save the query traffic.
1895        if tcx.sess.opts.output_types.should_codegen()
1896            && tcx.sess.opts.optimize != OptLevel::No
1897            && tcx.sess.opts.incremental.is_none()
1898        {
1899            for &local_def_id in tcx.mir_keys(()) {
1900                if let DefKind::AssocFn | DefKind::Fn = tcx.def_kind(local_def_id) {
1901                    {
    {
        let value = self.tcx.deduced_param_attrs(local_def_id.to_def_id());
        let lazy = self.lazy_array(value);
        self.tables.deduced_param_attrs.set_some(local_def_id.to_def_id().index,
            lazy);
    }
};record_array!(self.tables.deduced_param_attrs[local_def_id.to_def_id()] <-
1902                        self.tcx.deduced_param_attrs(local_def_id.to_def_id()));
1903                }
1904            }
1905        }
1906    }
1907
1908    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("encode_stability",
                                    "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1908u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if self.feat.staged_api() ||
                    self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked
                {
                if let Some(stab) = self.tcx.lookup_stability(def_id) {
                    {
                        {
                            let value = stab;
                            let lazy = self.lazy(value);
                            self.tables.lookup_stability.set_some(def_id.index, lazy);
                        }
                    }
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1909    fn encode_stability(&mut self, def_id: DefId) {
1910        // The query lookup can take a measurable amount of time in crates with many items. Check if
1911        // the stability attributes are even enabled before using their queries.
1912        if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1913            if let Some(stab) = self.tcx.lookup_stability(def_id) {
1914                record!(self.tables.lookup_stability[def_id] <- stab)
1915            }
1916        }
1917    }
1918
1919    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("encode_const_stability",
                                    "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1919u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if self.feat.staged_api() ||
                    self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked
                {
                if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
                    {
                        {
                            let value = stab;
                            let lazy = self.lazy(value);
                            self.tables.lookup_const_stability.set_some(def_id.index,
                                lazy);
                        }
                    }
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1920    fn encode_const_stability(&mut self, def_id: DefId) {
1921        // The query lookup can take a measurable amount of time in crates with many items. Check if
1922        // the stability attributes are even enabled before using their queries.
1923        if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1924            if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1925                record!(self.tables.lookup_const_stability[def_id] <- stab)
1926            }
1927        }
1928    }
1929
1930    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("encode_default_body_stability",
                                    "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1930u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if self.feat.staged_api() ||
                    self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked
                {
                if let Some(stab) =
                        self.tcx.lookup_default_body_stability(def_id) {
                    {
                        {
                            let value = stab;
                            let lazy = self.lazy(value);
                            self.tables.lookup_default_body_stability.set_some(def_id.index,
                                lazy);
                        }
                    }
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1931    fn encode_default_body_stability(&mut self, def_id: DefId) {
1932        // The query lookup can take a measurable amount of time in crates with many items. Check if
1933        // the stability attributes are even enabled before using their queries.
1934        if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1935            if let Some(stab) = self.tcx.lookup_default_body_stability(def_id) {
1936                record!(self.tables.lookup_default_body_stability[def_id] <- stab)
1937            }
1938        }
1939    }
1940
1941    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("encode_deprecation",
                                    "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1941u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
                {
                    {
                        let value = depr;
                        let lazy = self.lazy(value);
                        self.tables.lookup_deprecation_entry.set_some(def_id.index,
                            lazy);
                    }
                };
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1942    fn encode_deprecation(&mut self, def_id: DefId) {
1943        if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1944            record!(self.tables.lookup_deprecation_entry[def_id] <- depr);
1945        }
1946    }
1947
1948    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("encode_info_for_macro",
                                    "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1948u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx;
            let (_, macro_def, _) =
                tcx.hir_expect_item(def_id).expect_macro();
            self.tables.is_macro_rules.set(def_id.local_def_index,
                macro_def.macro_rules);
            {
                {
                    let value = &*macro_def.body;
                    let lazy = self.lazy(value);
                    self.tables.macro_definition.set_some(def_id.to_def_id().index,
                        lazy);
                }
            };
        }
    }
}#[instrument(level = "debug", skip(self))]
1949    fn encode_info_for_macro(&mut self, def_id: LocalDefId) {
1950        let tcx = self.tcx;
1951
1952        let (_, macro_def, _) = tcx.hir_expect_item(def_id).expect_macro();
1953        self.tables.is_macro_rules.set(def_id.local_def_index, macro_def.macro_rules);
1954        record!(self.tables.macro_definition[def_id.to_def_id()] <- &*macro_def.body);
1955    }
1956
1957    fn encode_native_libraries(&mut self) -> LazyArray<NativeLib> {
1958        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
1959        let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1960        self.lazy_array(used_libraries.iter())
1961    }
1962
1963    fn encode_foreign_modules(&mut self) -> LazyArray<ForeignModule> {
1964        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
1965        let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1966        self.lazy_array(foreign_modules.iter().map(|(_, m)| m).cloned())
1967    }
1968
1969    fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) {
1970        let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1971        let mut expn_data_table: TableBuilder<_, _> = Default::default();
1972        let mut expn_hash_table: TableBuilder<_, _> = Default::default();
1973
1974        HygieneEncodeContext::encode(
1975            &Rc::clone(&self.hygiene_ctxt),
1976            &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table),
1977            |(this, syntax_contexts, _, _), index, ctxt_data| {
1978                syntax_contexts.set_some(index, this.lazy(ctxt_data));
1979            },
1980            |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| {
1981                if let Some(index) = index.as_local() {
1982                    expn_data_table
1983                        .set_some(index.as_raw(), this.lazy(expn_data.expect("local expn")));
1984
1985                    expn_hash_table.set_some(index.as_raw(), this.lazy(hash));
1986                }
1987            },
1988        );
1989
1990        (
1991            syntax_contexts.encode(&mut self.opaque),
1992            expn_data_table.encode(&mut self.opaque),
1993            expn_hash_table.encode(&mut self.opaque),
1994        )
1995    }
1996
1997    fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
1998        let is_proc_macro = self.tcx.crate_types().contains(&CrateType::ProcMacro);
1999        if is_proc_macro {
2000            let tcx = self.tcx;
2001            let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index;
2002            let stability = tcx.lookup_stability(CRATE_DEF_ID);
2003            for (i, span) in self.tcx.sess.proc_macro_quoted_spans() {
2004                let span = self.lazy(span);
2005                self.tables.proc_macro_quoted_spans.set_some(i, span);
2006            }
2007
2008            self.tables.def_kind.set_some(LOCAL_CRATE.as_def_id().index, DefKind::Mod);
2009            {
    {
        let value = tcx.def_span(LOCAL_CRATE.as_def_id());
        let lazy = self.lazy(value);
        self.tables.def_span.set_some(LOCAL_CRATE.as_def_id().index, lazy);
    }
};record!(self.tables.def_span[LOCAL_CRATE.as_def_id()] <- tcx.def_span(LOCAL_CRATE.as_def_id()));
2010            self.encode_attrs(LOCAL_CRATE.as_def_id().expect_local());
2011            let vis = tcx
2012                .local_visibility(CRATE_DEF_ID)
2013                .map_id(|mod_id| mod_id.to_local_def_id().local_def_index);
2014            {
    {
        let value = vis;
        let lazy = self.lazy(value);
        self.tables.visibility.set_some(LOCAL_CRATE.as_def_id().index, lazy);
    }
};record!(self.tables.visibility[LOCAL_CRATE.as_def_id()] <- vis);
2015            if let Some(stability) = stability {
2016                {
    {
        let value = stability;
        let lazy = self.lazy(value);
        self.tables.lookup_stability.set_some(LOCAL_CRATE.as_def_id().index,
            lazy);
    }
};record!(self.tables.lookup_stability[LOCAL_CRATE.as_def_id()] <- stability);
2017            }
2018            self.encode_deprecation(LOCAL_CRATE.as_def_id());
2019            if let Some(res_map) = tcx.resolutions(()).doc_link_resolutions.get(&CRATE_MOD_ID) {
2020                {
    {
        let value = res_map;
        let lazy = self.lazy(value);
        self.tables.doc_link_resolutions.set_some(LOCAL_CRATE.as_def_id().index,
            lazy);
    }
};record!(self.tables.doc_link_resolutions[LOCAL_CRATE.as_def_id()] <- res_map);
2021            }
2022            if let Some(traits) = tcx.resolutions(()).doc_link_traits_in_scope.get(&CRATE_MOD_ID) {
2023                {
    {
        let value = traits;
        let lazy = self.lazy_array(value);
        self.tables.doc_link_traits_in_scope.set_some(LOCAL_CRATE.as_def_id().index,
            lazy);
    }
};record_array!(self.tables.doc_link_traits_in_scope[LOCAL_CRATE.as_def_id()] <- traits);
2024            }
2025
2026            let mut macros = ::alloc::vec::Vec::new()vec![];
2027
2028            // Normally, this information is encoded when we walk the items
2029            // defined in this crate. However, we skip doing that for proc-macro crates,
2030            // so we manually encode just the information that we need
2031            for &proc_macro in &tcx.resolutions(()).proc_macros {
2032                let id = proc_macro;
2033                let proc_macro = tcx.local_def_id_to_hir_id(proc_macro);
2034                let mut name = tcx.hir_name(proc_macro);
2035                let span = tcx.hir_span(proc_macro);
2036                // Proc-macros may have attributes like `#[allow_internal_unstable]`,
2037                // so downstream crates need access to them.
2038                let attrs = tcx.hir_attrs(proc_macro);
2039                let (macro_kind, kind) = if {
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(ProcMacro) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, ProcMacro) {
2040                    (MacroKind::Bang, ProcMacroKind::Bang { name: name.as_str().to_owned() })
2041                } else if {
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(ProcMacroAttribute) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, ProcMacroAttribute) {
2042                    (MacroKind::Attr, ProcMacroKind::Attr { name: name.as_str().to_owned() })
2043                } else if let Some((trait_name, helper_attrs)) = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use ::rustc_attr_ir::AttributeKind::*;
            let i: &::rustc_attr_ir::Attribute = i;
            match i {
                ::rustc_attr_ir::Attribute::Parsed(ProcMacroDerive {
                    trait_name, helper_attrs }) => {
                    break 'done Some((trait_name, helper_attrs));
                }
                ::rustc_attr_ir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs,
2044                    ProcMacroDerive { trait_name, helper_attrs } => (trait_name, helper_attrs))
2045                {
2046                    name = *trait_name;
2047                    (
2048                        MacroKind::Derive,
2049                        ProcMacroKind::CustomDerive {
2050                            trait_name: name.as_str().to_owned(),
2051                            attributes: helper_attrs
2052                                .iter()
2053                                .map(|attr| attr.as_str().to_owned())
2054                                .collect(),
2055                        },
2056                    )
2057                } else {
2058                    bug_impl(None, format_args!("Unknown proc-macro type for item {0:?}", id),
    Location::caller());bug!("Unknown proc-macro type for item {:?}", id);
2059                };
2060
2061                macros.push((id.local_def_index, self.lazy(kind)));
2062
2063                let mut def_key = self.tcx.hir_def_key(id);
2064                def_key.disambiguated_data.data = DefPathData::MacroNs(name);
2065
2066                let def_id = id.to_def_id();
2067                self.tables.def_kind.set_some(def_id.index, DefKind::Macro(macro_kind.into()));
2068                self.encode_attrs(id);
2069                {
    {
        let value = def_key;
        let lazy = self.lazy(value);
        self.tables.def_keys.set_some(def_id.index, lazy);
    }
};record!(self.tables.def_keys[def_id] <- def_key);
2070                {
    {
        let value = span;
        let lazy = self.lazy(value);
        self.tables.def_ident_span.set_some(def_id.index, lazy);
    }
};record!(self.tables.def_ident_span[def_id] <- span);
2071                {
    {
        let value = span;
        let lazy = self.lazy(value);
        self.tables.def_span.set_some(def_id.index, lazy);
    }
};record!(self.tables.def_span[def_id] <- span);
2072                {
    {
        let value = ty::Visibility::Public;
        let lazy = self.lazy(value);
        self.tables.visibility.set_some(def_id.index, lazy);
    }
};record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
2073                if let Some(stability) = stability {
2074                    {
    {
        let value = stability;
        let lazy = self.lazy(value);
        self.tables.lookup_stability.set_some(def_id.index, lazy);
    }
};record!(self.tables.lookup_stability[def_id] <- stability);
2075                }
2076            }
2077
2078            let macros = self.lazy_array(macros);
2079
2080            Some(ProcMacroData { proc_macro_decls_static, stability, macros })
2081        } else {
2082            None
2083        }
2084    }
2085
2086    fn encode_debugger_visualizers(&mut self) -> LazyArray<DebuggerVisualizerFile> {
2087        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2088        self.lazy_array(
2089            self.tcx
2090                .debugger_visualizers(LOCAL_CRATE)
2091                .iter()
2092                // Erase the path since it may contain privacy sensitive data
2093                // that we don't want to end up in crate metadata.
2094                // The path is only needed for the local crate because of
2095                // `--emit dep-info`.
2096                .map(DebuggerVisualizerFile::path_erased),
2097        )
2098    }
2099
2100    fn encode_crate_deps(&mut self) -> LazyArray<CrateDep> {
2101        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2102
2103        let deps = self
2104            .tcx
2105            .crates(())
2106            .iter()
2107            .map(|&cnum| {
2108                let dep = CrateDep {
2109                    name: self.tcx.crate_name(cnum),
2110                    hash: self.tcx.crate_hash(cnum),
2111                    host_hash: self.tcx.crate_host_hash(cnum),
2112                    kind: self.tcx.crate_dep_kind(cnum),
2113                    extra_filename: self.tcx.extra_filename(cnum).to_owned(),
2114                    is_private: self.tcx.is_private_dep(cnum),
2115                };
2116                (cnum, dep)
2117            })
2118            .collect::<Vec<_>>();
2119
2120        {
2121            // Sanity-check the crate numbers
2122            let mut expected_cnum = 1;
2123            for &(n, _) in &deps {
2124                {
    match (&n, &CrateNum::new(expected_cnum)) {
        (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!(n, CrateNum::new(expected_cnum));
2125                expected_cnum += 1;
2126            }
2127        }
2128
2129        // We're just going to write a list of crate 'name-hash-version's, with
2130        // the assumption that they are numbered 1 to n.
2131        // FIXME (#2166): This is not nearly enough to support correct versioning
2132        // but is enough to get transitive crate dependencies working.
2133        self.lazy_array(deps.iter().map(|(_, dep)| dep))
2134    }
2135
2136    fn encode_target_modifiers(&mut self) -> LazyArray<TargetModifier> {
2137        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2138        let tcx = self.tcx;
2139        self.lazy_array(tcx.sess.opts.gather_target_modifiers())
2140    }
2141
2142    fn encode_enabled_denied_partial_mitigations(&mut self) -> LazyArray<DeniedPartialMitigation> {
2143        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2144        let tcx = self.tcx;
2145        self.lazy_array(tcx.sess.gather_enabled_denied_partial_mitigations())
2146    }
2147
2148    fn encode_lib_features(&mut self) -> LazyArray<(Symbol, FeatureStability)> {
2149        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2150        let tcx = self.tcx;
2151        let lib_features = tcx.lib_features(LOCAL_CRATE);
2152        self.lazy_array(lib_features.to_sorted_vec())
2153    }
2154
2155    fn encode_stability_implications(&mut self) -> LazyArray<(Symbol, Symbol)> {
2156        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2157        let tcx = self.tcx;
2158        let implications = tcx.stability_implications(LOCAL_CRATE);
2159        let sorted = implications.to_sorted_stable_ord();
2160        self.lazy_array(sorted.into_iter().map(|(k, v)| (*k, *v)))
2161    }
2162
2163    fn encode_canonical_symbols(&mut self) -> LazyArray<(Symbol, DefIndex)> {
2164        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2165        let tcx = self.tcx;
2166        let canonical_symbols = &tcx.canonical_symbols(LOCAL_CRATE);
2167        self.lazy_array(canonical_symbols.iter().map(|cs| (cs.symbol, cs.def_id.index)))
2168    }
2169
2170    fn encode_diagnostic_items(&mut self) -> LazyArray<(Symbol, DefIndex)> {
2171        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2172        let tcx = self.tcx;
2173        let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id;
2174        self.lazy_array(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
2175    }
2176
2177    fn encode_fake_doc_items(&mut self) -> LazyArray<DefIndex> {
2178        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2179        let tcx = self.tcx;
2180        let fake_doc_items = &tcx.fake_doc_items(LOCAL_CRATE);
2181        self.lazy_array(fake_doc_items.iter().map(|cs| cs.index))
2182    }
2183
2184    fn encode_lang_items(&mut self) -> LazyArray<(DefIndex, LangItem)> {
2185        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2186        let lang_items = self.tcx.lang_items().iter();
2187        self.lazy_array(lang_items.filter_map(|(lang_item, def_id)| {
2188            def_id.as_local().map(|id| (id.local_def_index, lang_item))
2189        }))
2190    }
2191
2192    fn encode_lang_items_missing(&mut self) -> LazyArray<LangItem> {
2193        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2194        let tcx = self.tcx;
2195        self.lazy_array(&tcx.lang_items().missing)
2196    }
2197
2198    fn encode_stripped_cfg_items(&mut self) -> LazyArray<StrippedCfgItem<DefIndex>> {
2199        self.lazy_array(
2200            self.tcx
2201                .stripped_cfg_items(LOCAL_CRATE)
2202                .into_iter()
2203                .map(|item| item.clone().map_scope_id(|def_id| def_id.index)),
2204        )
2205    }
2206
2207    fn encode_traits(&mut self) -> LazyArray<DefIndex> {
2208        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2209        self.lazy_array(self.tcx.traits(LOCAL_CRATE).iter().map(|def_id| def_id.index))
2210    }
2211
2212    /// Encodes an index, mapping each trait to its (local) implementations.
2213    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("encode_impls",
                                    "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2213u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: LazyArray<TraitImpls> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if self.is_proc_macro { return LazyArray::default(); };
            let tcx = self.tcx;
            let mut trait_impls:
                    FxIndexMap<DefId, Vec<(DefIndex, Option<SimplifiedType>)>> =
                FxIndexMap::default();
            for id in tcx.hir_free_items() {
                let DefKind::Impl { of_trait } =
                    tcx.def_kind(id.owner_id) else { continue; };
                let def_id = id.owner_id.to_def_id();
                if of_trait {
                    let header = tcx.impl_trait_header(def_id);
                    {
                        {
                            let value = header;
                            let lazy = self.lazy(value);
                            self.tables.impl_trait_header.set_some(def_id.index, lazy);
                        }
                    };
                    let impl_is_fully_generic_for_reflection =
                        tcx.impl_is_fully_generic_for_reflection(def_id);
                    self.tables.impl_is_fully_generic_for_reflection.set(def_id.index,
                        impl_is_fully_generic_for_reflection);
                    self.tables.defaultness.set(def_id.index,
                        tcx.defaultness(def_id));
                    let trait_ref =
                        header.trait_ref.instantiate_identity().skip_norm_wip();
                    let simplified_self_ty =
                        fast_reject::simplify_type(self.tcx, trait_ref.self_ty(),
                            TreatParams::InstantiateWithInfer);
                    trait_impls.entry(trait_ref.def_id).or_default().push((id.owner_id.def_id.local_def_index,
                            simplified_self_ty));
                    let trait_def = tcx.trait_def(trait_ref.def_id);
                    if let Ok(mut an) = trait_def.ancestors(tcx, def_id) &&
                            let Some(specialization_graph::Node::Impl(parent)) =
                                an.nth(1) {
                        self.tables.impl_parent.set_some(def_id.index,
                            parent.into());
                    }
                    if tcx.is_lang_item(trait_ref.def_id,
                            LangItem::CoerceUnsized) {
                        let coerce_unsized_info =
                            tcx.coerce_unsized_info(def_id).unwrap();
                        {
                            {
                                let value = coerce_unsized_info;
                                let lazy = self.lazy(value);
                                self.tables.coerce_unsized_info.set_some(def_id.index,
                                    lazy);
                            }
                        };
                    }
                }
            }
            let trait_impls: Vec<_> =
                trait_impls.into_iter().map(|(trait_def_id, impls)|
                            TraitImpls {
                                trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
                                impls: self.lazy_array(&impls),
                            }).collect();
            self.lazy_array(&trait_impls)
        }
    }
}#[instrument(level = "debug", skip(self))]
2214    fn encode_impls(&mut self) -> LazyArray<TraitImpls> {
2215        empty_proc_macro!(self);
2216        let tcx = self.tcx;
2217        let mut trait_impls: FxIndexMap<DefId, Vec<(DefIndex, Option<SimplifiedType>)>> =
2218            FxIndexMap::default();
2219
2220        for id in tcx.hir_free_items() {
2221            let DefKind::Impl { of_trait } = tcx.def_kind(id.owner_id) else {
2222                continue;
2223            };
2224            let def_id = id.owner_id.to_def_id();
2225
2226            if of_trait {
2227                let header = tcx.impl_trait_header(def_id);
2228                record!(self.tables.impl_trait_header[def_id] <- header);
2229
2230                let impl_is_fully_generic_for_reflection =
2231                    tcx.impl_is_fully_generic_for_reflection(def_id);
2232                self.tables
2233                    .impl_is_fully_generic_for_reflection
2234                    .set(def_id.index, impl_is_fully_generic_for_reflection);
2235
2236                self.tables.defaultness.set(def_id.index, tcx.defaultness(def_id));
2237
2238                let trait_ref = header.trait_ref.instantiate_identity().skip_norm_wip();
2239                let simplified_self_ty = fast_reject::simplify_type(
2240                    self.tcx,
2241                    trait_ref.self_ty(),
2242                    TreatParams::InstantiateWithInfer,
2243                );
2244                trait_impls
2245                    .entry(trait_ref.def_id)
2246                    .or_default()
2247                    .push((id.owner_id.def_id.local_def_index, simplified_self_ty));
2248
2249                let trait_def = tcx.trait_def(trait_ref.def_id);
2250                if let Ok(mut an) = trait_def.ancestors(tcx, def_id)
2251                    && let Some(specialization_graph::Node::Impl(parent)) = an.nth(1)
2252                {
2253                    self.tables.impl_parent.set_some(def_id.index, parent.into());
2254                }
2255
2256                // if this is an impl of `CoerceUnsized`, create its
2257                // "unsized info", else just store None
2258                if tcx.is_lang_item(trait_ref.def_id, LangItem::CoerceUnsized) {
2259                    let coerce_unsized_info = tcx.coerce_unsized_info(def_id).unwrap();
2260                    record!(self.tables.coerce_unsized_info[def_id] <- coerce_unsized_info);
2261                }
2262            }
2263        }
2264
2265        let trait_impls: Vec<_> = trait_impls
2266            .into_iter()
2267            .map(|(trait_def_id, impls)| TraitImpls {
2268                trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
2269                impls: self.lazy_array(&impls),
2270            })
2271            .collect();
2272
2273        self.lazy_array(&trait_impls)
2274    }
2275
2276    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("encode_incoherent_impls",
                                    "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2276u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: LazyArray<IncoherentImpls> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            if self.is_proc_macro { return LazyArray::default(); };
            let tcx = self.tcx;
            let all_impls: Vec<_> =
                tcx.crate_inherent_impls(()).0.incoherent_impls.iter().map(|(&simp,
                                impls)|
                            IncoherentImpls {
                                self_ty: self.lazy(simp),
                                impls: self.lazy_array(impls.iter().map(|def_id|
                                            def_id.local_def_index)),
                            }).collect();
            self.lazy_array(&all_impls)
        }
    }
}#[instrument(level = "debug", skip(self))]
2277    fn encode_incoherent_impls(&mut self) -> LazyArray<IncoherentImpls> {
2278        empty_proc_macro!(self);
2279        let tcx = self.tcx;
2280
2281        let all_impls: Vec<_> = tcx
2282            .crate_inherent_impls(())
2283            .0
2284            .incoherent_impls
2285            .iter()
2286            .map(|(&simp, impls)| IncoherentImpls {
2287                self_ty: self.lazy(simp),
2288                impls: self.lazy_array(impls.iter().map(|def_id| def_id.local_def_index)),
2289            })
2290            .collect();
2291
2292        self.lazy_array(&all_impls)
2293    }
2294
2295    fn encode_exportable_items(&mut self) -> LazyArray<DefIndex> {
2296        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2297        self.lazy_array(self.tcx.exportable_items(LOCAL_CRATE).iter().map(|def_id| def_id.index))
2298    }
2299
2300    fn encode_stable_order_of_exportable_impls(&mut self) -> LazyArray<(DefIndex, usize)> {
2301        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2302        let stable_order_of_exportable_impls =
2303            self.tcx.stable_order_of_exportable_impls(LOCAL_CRATE);
2304        self.lazy_array(
2305            stable_order_of_exportable_impls.iter().map(|(def_id, idx)| (def_id.index, *idx)),
2306        )
2307    }
2308
2309    // Encodes all symbols exported from this crate into the metadata.
2310    //
2311    // This pass is seeded off the reachability list calculated in the
2312    // middle::reachable module but filters out items that either don't have a
2313    // symbol associated with them (they weren't translated) or if they're an FFI
2314    // definition (as that's not defined in this crate).
2315    fn encode_exported_symbols(
2316        &mut self,
2317        exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportInfo)],
2318    ) -> LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)> {
2319        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2320
2321        self.lazy_array(exported_symbols.iter().cloned())
2322    }
2323
2324    fn encode_dylib_dependency_formats(&mut self) -> LazyArray<Option<LinkagePreference>> {
2325        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2326        let formats = self.tcx.dependency_formats(());
2327        if let Some(arr) = formats.get(&CrateType::Dylib) {
2328            return self.lazy_array(arr.iter().skip(1 /* skip LOCAL_CRATE */).map(
2329                |slot| match *slot {
2330                    Linkage::NotLinked | Linkage::IncludedFromDylib => None,
2331
2332                    Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
2333                    Linkage::Static => Some(LinkagePreference::RequireStatic),
2334                },
2335            ));
2336        }
2337        LazyArray::default()
2338    }
2339}
2340
2341/// Used to prefetch queries which will be needed later by metadata encoding.
2342/// Only a subset of the queries are actually prefetched to keep this code smaller.
2343fn prefetch_mir(tcx: TyCtxt<'_>) {
2344    if !tcx.sess.opts.output_types.should_codegen() {
2345        // We won't emit MIR, so don't prefetch it.
2346        return;
2347    }
2348
2349    let reachable_set = tcx.reachable_set(());
2350    par_for_each_in(tcx.mir_keys(()), |&&def_id| {
2351        if tcx.is_trivial_const(def_id) {
2352            return;
2353        }
2354        let (encode_const, encode_opt) = should_encode_mir(tcx, reachable_set, def_id);
2355
2356        if encode_const {
2357            tcx.ensure_done().mir_for_ctfe(def_id);
2358        }
2359        if encode_opt {
2360            tcx.ensure_done().optimized_mir(def_id);
2361        }
2362        if encode_opt || encode_const {
2363            tcx.ensure_done().promoted_mir(def_id);
2364        }
2365    })
2366}
2367
2368// NOTE(eddyb) The following comment was preserved for posterity, even
2369// though it's no longer relevant as EBML (which uses nested & tagged
2370// "documents") was replaced with a scheme that can't go out of bounds.
2371//
2372// And here we run into yet another obscure archive bug: in which metadata
2373// loaded from archives may have trailing garbage bytes. Awhile back one of
2374// our tests was failing sporadically on the macOS 64-bit builders (both nopt
2375// and opt) by having ebml generate an out-of-bounds panic when looking at
2376// metadata.
2377//
2378// Upon investigation it turned out that the metadata file inside of an rlib
2379// (and ar archive) was being corrupted. Some compilations would generate a
2380// metadata file which would end in a few extra bytes, while other
2381// compilations would not have these extra bytes appended to the end. These
2382// extra bytes were interpreted by ebml as an extra tag, so they ended up
2383// being interpreted causing the out-of-bounds.
2384//
2385// The root cause of why these extra bytes were appearing was never
2386// discovered, and in the meantime the solution we're employing is to insert
2387// the length of the metadata to the start of the metadata. Later on this
2388// will allow us to slice the metadata to the precise length that we just
2389// generated regardless of trailing bytes that end up in it.
2390
2391pub struct EncodedMetadata {
2392    // The declaration order matters because `full_metadata` should be dropped
2393    // before `_temp_dir`.
2394    full_metadata: Option<Mmap>,
2395    // This is an optional stub metadata containing only the crate header.
2396    // The header should be very small, so we load it directly into memory.
2397    stub_metadata: Option<Vec<u8>>,
2398    // The path containing the metadata, to record as work product.
2399    path: Option<Box<Path>>,
2400    // We need to carry MaybeTempDir to avoid deleting the temporary
2401    // directory while accessing the Mmap.
2402    _temp_dir: Option<MaybeTempDir>,
2403}
2404
2405impl EncodedMetadata {
2406    #[inline]
2407    pub fn from_path(
2408        path: PathBuf,
2409        stub_path: Option<PathBuf>,
2410        temp_dir: Option<MaybeTempDir>,
2411    ) -> std::io::Result<Self> {
2412        let file = std::fs::File::open(&path)?;
2413        let file_metadata = file.metadata()?;
2414        if file_metadata.len() == 0 {
2415            return Ok(Self {
2416                full_metadata: None,
2417                stub_metadata: None,
2418                path: None,
2419                _temp_dir: None,
2420            });
2421        }
2422        let full_mmap = unsafe { Some(Mmap::map(file)?) };
2423
2424        let stub =
2425            if let Some(stub_path) = stub_path { Some(std::fs::read(stub_path)?) } else { None };
2426
2427        Ok(Self {
2428            full_metadata: full_mmap,
2429            stub_metadata: stub,
2430            path: Some(path.into()),
2431            _temp_dir: temp_dir,
2432        })
2433    }
2434
2435    #[inline]
2436    pub fn full(&self) -> &[u8] {
2437        &self.full_metadata.as_deref().unwrap_or_default()
2438    }
2439
2440    #[inline]
2441    pub fn stub_or_full(&self) -> &[u8] {
2442        self.stub_metadata.as_deref().unwrap_or(self.full())
2443    }
2444
2445    #[inline]
2446    pub fn path(&self) -> Option<&Path> {
2447        self.path.as_deref()
2448    }
2449}
2450
2451impl<S: Encoder> Encodable<S> for EncodedMetadata {
2452    fn encode(&self, s: &mut S) {
2453        self.stub_metadata.encode(s);
2454
2455        let slice = self.full();
2456        slice.encode(s)
2457    }
2458}
2459
2460impl<D: Decoder> Decodable<D> for EncodedMetadata {
2461    fn decode(d: &mut D) -> Self {
2462        let stub = <Option<Vec<u8>>>::decode(d);
2463
2464        let len = d.read_usize();
2465        let full_metadata = if len > 0 {
2466            let mut mmap = MmapMut::map_anon(len).unwrap();
2467            mmap.copy_from_slice(d.read_raw_bytes(len));
2468            Some(mmap.make_read_only().unwrap())
2469        } else {
2470            None
2471        };
2472
2473        Self { full_metadata, stub_metadata: stub, path: None, _temp_dir: None }
2474    }
2475}
2476
2477{}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("encode_metadata",
                                    "rustc_metadata::rmeta::encoder", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2477u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("path")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("path");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ref_path")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ref_path");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ref_path)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            tcx.dep_graph.assert_ignored();
            if let Some(ref_path) = ref_path {
                let _prof_timer =
                    tcx.prof.verbose_generic_activity("generate_crate_metadata_stub");
                with_encode_metadata_header(tcx, ref_path,
                    |ecx|
                        {
                            let header: LazyValue<CrateHeader> =
                                ecx.lazy(CrateHeader {
                                        name: tcx.crate_name(LOCAL_CRATE),
                                        triple: tcx.sess.opts.target_triple.clone(),
                                        hash: tcx.crate_hash(LOCAL_CRATE),
                                        is_proc_macro_crate: false,
                                        is_stub: true,
                                    });
                            header.position.get()
                        })
            }
            let _prof_timer =
                tcx.prof.verbose_generic_activity("generate_crate_metadata");
            let dep_node = tcx.metadata_dep_node();
            if tcx.dep_graph.is_fully_enabled() &&
                            let work_product_id =
                                WorkProductId::from_cgu_name("metadata") &&
                        let Some(work_product) =
                            tcx.dep_graph.previous_work_product(&work_product_id) &&
                    tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some() {
                let saved_path = &work_product.saved_files["rmeta"];
                let incr_comp_session_dir =
                    &tcx.incr_comp_session.unwrap().session_directory;
                let source_file_in_incr_dir =
                    &incr_comp_session_dir.join(saved_path);
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/rmeta/encoder.rs:2512",
                                        "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                        ::tracing_core::__macro_support::Option::Some(2512u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                                        ::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!("copying preexisting metadata from {0:?} to {1:?}",
                                                                    source_file_in_incr_dir, path) as
                                                            &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                match rustc_fs_util::link_or_copy(&source_file_in_incr_dir,
                        path) {
                    Ok(_) => {}
                    Err(err) =>
                        tcx.dcx().emit_fatal(FailCreateFileEncoder { err }),
                };
                return;
            };
            if tcx.sess.opts.jobs.frontend.is_some() {
                par_join(|| prefetch_mir(tcx),
                    ||
                        {
                            let _ = tcx.exported_non_generic_symbols(LOCAL_CRATE);
                            let _ = tcx.exported_generic_symbols(LOCAL_CRATE);
                        });
            }
            tcx.dep_graph.with_task(dep_node, tcx,
                ||
                    {
                        with_encode_metadata_header(tcx, path,
                            |ecx|
                                {
                                    let root = ecx.encode_crate_root();
                                    ecx.opaque.flush();
                                    tcx.prof.artifact_size("crate_metadata", "crate_metadata",
                                        ecx.opaque.file().metadata().unwrap().len());
                                    root.position.get()
                                })
                    }, None);
        }
    }
}#[instrument(level = "trace", skip(tcx))]
2478pub fn encode_metadata(tcx: TyCtxt<'_>, path: &Path, ref_path: Option<&Path>) {
2479    // Since encoding metadata is not in a query, and nothing is cached,
2480    // there's no need to do dep-graph tracking for any of it.
2481    tcx.dep_graph.assert_ignored();
2482
2483    // Generate the metadata stub manually, as that is a small file compared to full metadata.
2484    if let Some(ref_path) = ref_path {
2485        let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata_stub");
2486
2487        with_encode_metadata_header(tcx, ref_path, |ecx| {
2488            let header: LazyValue<CrateHeader> = ecx.lazy(CrateHeader {
2489                name: tcx.crate_name(LOCAL_CRATE),
2490                triple: tcx.sess.opts.target_triple.clone(),
2491                hash: tcx.crate_hash(LOCAL_CRATE),
2492                is_proc_macro_crate: false,
2493                is_stub: true,
2494            });
2495            header.position.get()
2496        })
2497    }
2498
2499    let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata");
2500
2501    let dep_node = tcx.metadata_dep_node();
2502
2503    // If the metadata dep-node is green, try to reuse the saved work product.
2504    if tcx.dep_graph.is_fully_enabled()
2505        && let work_product_id = WorkProductId::from_cgu_name("metadata")
2506        && let Some(work_product) = tcx.dep_graph.previous_work_product(&work_product_id)
2507        && tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some()
2508    {
2509        let saved_path = &work_product.saved_files["rmeta"];
2510        let incr_comp_session_dir = &tcx.incr_comp_session.unwrap().session_directory;
2511        let source_file_in_incr_dir = &incr_comp_session_dir.join(saved_path);
2512        debug!("copying preexisting metadata from {source_file_in_incr_dir:?} to {path:?}");
2513        match rustc_fs_util::link_or_copy(&source_file_in_incr_dir, path) {
2514            Ok(_) => {}
2515            Err(err) => tcx.dcx().emit_fatal(FailCreateFileEncoder { err }),
2516        };
2517        return;
2518    };
2519
2520    if tcx.sess.opts.jobs.frontend.is_some() {
2521        // Prefetch some queries used by metadata encoding.
2522        // This is not necessary for correctness, but is only done for performance reasons.
2523        // It can be removed if it turns out to cause trouble or be detrimental to performance.
2524        par_join(
2525            || prefetch_mir(tcx),
2526            || {
2527                let _ = tcx.exported_non_generic_symbols(LOCAL_CRATE);
2528                let _ = tcx.exported_generic_symbols(LOCAL_CRATE);
2529            },
2530        );
2531    }
2532
2533    // Perform metadata encoding inside a task, so the dep-graph can check if any encoded
2534    // information changes, and maybe reuse the work product.
2535    tcx.dep_graph.with_task(
2536        dep_node,
2537        tcx,
2538        || {
2539            with_encode_metadata_header(tcx, path, |ecx| {
2540                // Encode all the entries and extra information in the crate,
2541                // culminating in the `CrateRoot` which points to all of it.
2542                let root = ecx.encode_crate_root();
2543
2544                // Flush buffer to ensure backing file has the correct size.
2545                ecx.opaque.flush();
2546                // Record metadata size for self-profiling
2547                tcx.prof.artifact_size(
2548                    "crate_metadata",
2549                    "crate_metadata",
2550                    ecx.opaque.file().metadata().unwrap().len(),
2551                );
2552
2553                root.position.get()
2554            })
2555        },
2556        None,
2557    );
2558}
2559
2560fn with_encode_metadata_header(
2561    tcx: TyCtxt<'_>,
2562    path: &Path,
2563    f: impl FnOnce(&mut EncodeContext<'_, '_>) -> usize,
2564) {
2565    let mut encoder = opaque::FileEncoder::new(path)
2566        .unwrap_or_else(|err| tcx.dcx().emit_fatal(FailCreateFileEncoder { err }));
2567    encoder.emit_raw_bytes(METADATA_HEADER);
2568
2569    // Will be filled with the root position after encoding everything.
2570    encoder.emit_raw_bytes(&0u64.to_le_bytes());
2571
2572    let source_map_files = tcx.sess.source_map().files();
2573    let source_file_cache = (Arc::clone(&source_map_files[0]), 0);
2574    let required_source_files = Some(FxIndexSet::default());
2575    drop(source_map_files);
2576
2577    let mut ecx = EncodeContext {
2578        opaque: encoder,
2579        tcx,
2580        feat: tcx.features(),
2581        tables: Default::default(),
2582        lazy_state: LazyState::NoNode,
2583        span_shorthands: Default::default(),
2584        type_shorthands: Default::default(),
2585        predicate_shorthands: Default::default(),
2586        source_file_cache,
2587        interpret_allocs: Default::default(),
2588        required_source_files,
2589        is_proc_macro: tcx.crate_types().contains(&CrateType::ProcMacro),
2590        hygiene_ctxt: Default::default(),
2591        symbol_index_table: Default::default(),
2592    };
2593
2594    // Encode the rustc version string in a predictable location.
2595    rustc_version(tcx.sess.cfg_version).encode(&mut ecx);
2596
2597    let root_position = f(&mut ecx);
2598
2599    // Make sure we report any errors from writing to the file.
2600    // If we forget this, compilation can succeed with an incomplete rmeta file,
2601    // causing an ICE when the rmeta file is read by another compilation.
2602    if let Err((path, err)) = ecx.opaque.finish() {
2603        tcx.dcx().emit_fatal(FailWriteFile { path: &path, err });
2604    }
2605
2606    let file = ecx.opaque.file();
2607    if let Err(err) = encode_root_position(file, root_position) {
2608        tcx.dcx().emit_fatal(FailWriteFile { path: ecx.opaque.path(), err });
2609    }
2610}
2611
2612fn encode_root_position(mut file: &File, pos: usize) -> Result<(), std::io::Error> {
2613    // We will return to this position after writing the root position.
2614    let pos_before_seek = file.stream_position().unwrap();
2615
2616    // Encode the root position.
2617    let header = METADATA_HEADER.len();
2618    file.seek(std::io::SeekFrom::Start(header as u64))?;
2619    file.write_all(&pos.to_le_bytes())?;
2620
2621    // Return to the position where we are before writing the root position.
2622    file.seek(std::io::SeekFrom::Start(pos_before_seek))?;
2623    Ok(())
2624}
2625
2626pub(crate) fn provide(providers: &mut Providers) {
2627    *providers = Providers {
2628        doc_link_resolutions: |tcx, def_id| {
2629            tcx.resolutions(())
2630                .doc_link_resolutions
2631                .get(&def_id)
2632                .unwrap_or_else(|| bug_impl(Some(tcx.def_span(def_id)),
    format_args!("no resolutions for a doc link"), Location::caller())span_bug!(tcx.def_span(def_id), "no resolutions for a doc link"))
2633        },
2634        doc_link_traits_in_scope: |tcx, def_id| {
2635            tcx.resolutions(()).doc_link_traits_in_scope.get(&def_id).unwrap_or_else(|| {
2636                bug_impl(Some(tcx.def_span(def_id)),
    format_args!("no traits in scope for a doc link"), Location::caller())span_bug!(tcx.def_span(def_id), "no traits in scope for a doc link")
2637            })
2638        },
2639
2640        ..*providers
2641    }
2642}
2643
2644/// Build a textual representation of an unevaluated constant expression.
2645///
2646/// If the const expression is too complex, an underscore `_` is returned.
2647/// For const arguments, it's `{ _ }` to be precise.
2648/// This means that the output is not necessarily valid Rust code.
2649///
2650/// Currently, only
2651///
2652/// * literals (optionally with a leading `-`)
2653/// * unit `()`
2654/// * blocks (`{ … }`) around simple expressions and
2655/// * paths without arguments
2656///
2657/// are considered simple enough. Simple blocks are included since they are
2658/// necessary to disambiguate unit from the unit type.
2659/// This list might get extended in the future.
2660///
2661/// Without this censoring, in a lot of cases the output would get too large
2662/// and verbose. Consider `match` expressions, blocks and deeply nested ADTs.
2663/// Further, private and `doc(hidden)` fields of structs would get leaked
2664/// since HIR datatypes like the `body` parameter do not contain enough
2665/// semantic information for this function to be able to hide them –
2666/// at least not without significant performance overhead.
2667///
2668/// Whenever possible, prefer to evaluate the constant first and try to
2669/// use a different method for pretty-printing. Ideally this function
2670/// should only ever be used as a fallback.
2671pub fn rendered_const<'tcx>(tcx: TyCtxt<'tcx>, body: &hir::Body<'_>, def_id: LocalDefId) -> String {
2672    let value = body.value;
2673
2674    #[derive(#[automatically_derived]
impl ::core::marker::StructuralPartialEq for Classification { }
#[automatically_derived]
impl ::core::cmp::PartialEq for Classification {
    #[inline]
    fn eq(&self, other: &Classification) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Classification { }Eq)]
2675    enum Classification {
2676        Literal,
2677        Simple,
2678        Complex,
2679    }
2680
2681    use Classification::*;
2682
2683    fn classify(expr: &hir::Expr<'_>) -> Classification {
2684        match &expr.kind {
2685            hir::ExprKind::Unary(hir::UnOp::Neg, expr) => {
2686                if #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
    hir::ExprKind::Lit(_) => true,
    _ => false,
}matches!(expr.kind, hir::ExprKind::Lit(_)) { Literal } else { Complex }
2687            }
2688            hir::ExprKind::Lit(_) => Literal,
2689            hir::ExprKind::Tup([]) => Simple,
2690            hir::ExprKind::Block(hir::Block { stmts: [], expr: Some(expr), .. }, _) => {
2691                if classify(expr) == Complex { Complex } else { Simple }
2692            }
2693            // Paths with a self-type or arguments are too “complex” following our measure since
2694            // they may leak private fields of structs (with feature `adt_const_params`).
2695            // Consider: `<Self as Trait<{ Struct { private: () } }>>::CONSTANT`.
2696            // Paths without arguments are definitely harmless though.
2697            hir::ExprKind::Path(hir::QPath::Resolved(_, hir::Path { segments, .. })) => {
2698                if segments.iter().all(|segment| segment.args.is_none()) { Simple } else { Complex }
2699            }
2700            // FIXME: Claiming that those kinds of QPaths are simple is probably not true if the Ty
2701            //        contains const arguments. Is there a *concise* way to check for this?
2702            hir::ExprKind::Path(hir::QPath::TypeRelative(..)) => Simple,
2703            _ => Complex,
2704        }
2705    }
2706
2707    match classify(value) {
2708        // For non-macro literals, we avoid invoking the pretty-printer and use the source snippet
2709        // instead to preserve certain stylistic choices the user likely made for the sake of
2710        // legibility, like:
2711        //
2712        // * hexadecimal notation
2713        // * underscores
2714        // * character escapes
2715        //
2716        // FIXME: This passes through `-/*spacer*/0` verbatim.
2717        Literal
2718            if !value.span.from_expansion()
2719                && let Ok(snippet) = tcx.sess.source_map().span_to_snippet(value.span) =>
2720        {
2721            snippet
2722        }
2723
2724        // Otherwise we prefer pretty-printing to get rid of extraneous whitespace, comments and
2725        // other formatting artifacts.
2726        Literal | Simple => id_to_string(&tcx, body.id().hir_id),
2727
2728        // FIXME: Omit the curly braces if the enclosing expression is an array literal
2729        //        with a repeated element (an `ExprKind::Repeat`) as in such case it
2730        //        would not actually need any disambiguation.
2731        Complex => {
2732            if tcx.def_kind(def_id) == DefKind::AnonConst {
2733                "{ _ }".to_owned()
2734            } else {
2735                "_".to_owned()
2736            }
2737        }
2738    }
2739}