Skip to main content

rustc_metadata/rmeta/
encoder.rs

1use std::borrow::Borrow;
2use std::collections::hash_map::Entry;
3use std::fs::File;
4use std::io::{Read, Seek, Write};
5use std::path::{Path, PathBuf};
6use std::sync::Arc;
7
8use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
9use rustc_data_structures::memmap::{Mmap, MmapMut};
10use rustc_data_structures::sync::{par_for_each_in, par_join};
11use rustc_data_structures::temp_dir::MaybeTempDir;
12use rustc_data_structures::thousands::usize_with_underscores;
13use rustc_hir as hir;
14use rustc_hir::attrs::{AttributeKind, EncodeCrossCrate};
15use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE, LocalDefId, LocalDefIdSet};
16use rustc_hir::definitions::DefPathData;
17use rustc_hir::find_attr;
18use rustc_hir_pretty::id_to_string;
19use rustc_middle::dep_graph::WorkProductId;
20use rustc_middle::middle::dependency_format::Linkage;
21use rustc_middle::mir::interpret;
22use rustc_middle::query::Providers;
23use rustc_middle::traits::specialization_graph;
24use rustc_middle::ty::AssocContainer;
25use rustc_middle::ty::codec::TyEncoder;
26use rustc_middle::ty::fast_reject::{self, TreatParams};
27use rustc_middle::{bug, span_bug};
28use rustc_serialize::{Decodable, Decoder, Encodable, Encoder, opaque};
29use rustc_session::config::mitigation_coverage::DeniedPartialMitigation;
30use rustc_session::config::{CrateType, OptLevel, TargetModifier};
31use rustc_span::def_id::CRATE_MOD_ID;
32use rustc_span::hygiene::HygieneEncodeContext;
33use rustc_span::{
34    ByteSymbol, ExternalSource, FileName, SourceFile, SpanData, SpanEncoder, StableSourceFileId,
35    Symbol, SyntaxContext, sym,
36};
37use tracing::{debug, instrument, trace};
38
39use crate::diagnostics::{FailCreateFileEncoder, FailWriteFile};
40use crate::eii::EiiMapEncodedKeyValue;
41use crate::rmeta::*;
42
43pub(super) struct EncodeContext<'a, 'tcx> {
44    opaque: opaque::FileEncoder<'a>,
45    tcx: TyCtxt<'tcx>,
46    feat: &'tcx rustc_feature::Features,
47    tables: TableBuilders,
48
49    lazy_state: LazyState,
50    span_shorthands: FxHashMap<Span, usize>,
51    type_shorthands: FxHashMap<Ty<'tcx>, usize>,
52    predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
53
54    interpret_allocs: FxIndexSet<interpret::AllocId>,
55
56    // This is used to speed up Span encoding.
57    // The `usize` is an index into the `MonotonicVec`
58    // that stores the `SourceFile`
59    source_file_cache: (Arc<SourceFile>, usize),
60    // The indices (into the `SourceMap`'s `MonotonicVec`)
61    // of all of the `SourceFiles` that we need to serialize.
62    // When we serialize a `Span`, we insert the index of its
63    // `SourceFile` into the `FxIndexSet`.
64    // The order inside the `FxIndexSet` is used as on-disk
65    // order of `SourceFiles`, and encoded inside `Span`s.
66    required_source_files: Option<FxIndexSet<usize>>,
67    is_proc_macro: bool,
68    hygiene_ctxt: &'a HygieneEncodeContext,
69    // Used for both `Symbol`s and `ByteSymbol`s.
70    symbol_index_table: FxHashMap<u32, usize>,
71}
72
73/// If the current crate is a proc-macro, returns early with `LazyArray::default()`.
74/// This is useful for skipping the encoding of things that aren't needed
75/// for proc-macro crates.
76macro_rules! empty_proc_macro {
77    ($self:ident) => {
78        if $self.is_proc_macro {
79            return LazyArray::default();
80        }
81    };
82}
83
84macro_rules! encoder_methods {
85    ($($name:ident($ty:ty);)*) => {
86        $(fn $name(&mut self, value: $ty) {
87            self.opaque.$name(value)
88        })*
89    }
90}
91
92impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
93    fn emit_raw_bytes(&mut self, value: &[u8]) {
    self.opaque.emit_raw_bytes(value)
}encoder_methods! {
94        emit_usize(usize);
95        emit_u128(u128);
96        emit_u64(u64);
97        emit_u32(u32);
98        emit_u16(u16);
99        emit_u8(u8);
100
101        emit_isize(isize);
102        emit_i128(i128);
103        emit_i64(i64);
104        emit_i32(i32);
105        emit_i16(i16);
106
107        emit_raw_bytes(&[u8]);
108    }
109}
110
111impl<'a, 'tcx, T> Encodable<EncodeContext<'a, 'tcx>> for LazyValue<T> {
112    fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
113        e.emit_lazy_distance(self.position);
114    }
115}
116
117impl<'a, 'tcx, T> Encodable<EncodeContext<'a, 'tcx>> for LazyArray<T> {
118    fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
119        e.emit_usize(self.num_elems);
120        if self.num_elems > 0 {
121            e.emit_lazy_distance(self.position)
122        }
123    }
124}
125
126impl<'a, 'tcx, I, T> Encodable<EncodeContext<'a, 'tcx>> for LazyTable<I, T> {
127    fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
128        e.emit_usize(self.width);
129        e.emit_usize(self.len);
130        e.emit_lazy_distance(self.position);
131    }
132}
133
134impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnIndex {
135    fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
136        s.emit_u32(self.as_u32());
137    }
138}
139
140impl<'a, 'tcx> SpanEncoder for EncodeContext<'a, 'tcx> {
141    fn encode_crate_num(&mut self, crate_num: CrateNum) {
142        if crate_num != LOCAL_CRATE && self.is_proc_macro {
143            {
    ::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");
144        }
145        self.emit_u32(crate_num.as_u32());
146    }
147
148    fn encode_def_index(&mut self, def_index: DefIndex) {
149        self.emit_u32(def_index.as_u32());
150    }
151
152    fn encode_def_id(&mut self, def_id: DefId) {
153        def_id.krate.encode(self);
154        def_id.index.encode(self);
155    }
156
157    fn encode_syntax_context(&mut self, syntax_context: SyntaxContext) {
158        rustc_span::hygiene::raw_encode_syntax_context(syntax_context, self.hygiene_ctxt, self);
159    }
160
161    fn encode_expn_id(&mut self, expn_id: ExpnId) {
162        if expn_id.krate == LOCAL_CRATE {
163            // We will only write details for local expansions. Non-local expansions will fetch
164            // data from the corresponding crate's metadata.
165            // FIXME(#43047) FIXME(#74731) We may eventually want to avoid relying on external
166            // metadata from proc-macro crates.
167            self.hygiene_ctxt.schedule_expn_data_for_encoding(expn_id);
168        }
169        expn_id.krate.encode(self);
170        expn_id.local_id.encode(self);
171    }
172
173    fn encode_span(&mut self, span: Span) {
174        match self.span_shorthands.entry(span) {
175            Entry::Occupied(o) => {
176                // If an offset is smaller than the absolute position, we encode with the offset.
177                // This saves space since smaller numbers encode in less bits.
178                let last_location = *o.get();
179                // This cannot underflow. Metadata is written with increasing position(), so any
180                // previously saved offset must be smaller than the current position.
181                let offset = self.opaque.position() - last_location;
182                if offset < last_location {
183                    let needed = bytes_needed(offset);
184                    SpanTag::indirect(true, needed as u8).encode(self);
185                    self.opaque.write_with(|dest| {
186                        *dest = offset.to_le_bytes();
187                        needed
188                    });
189                } else {
190                    let needed = bytes_needed(last_location);
191                    SpanTag::indirect(false, needed as u8).encode(self);
192                    self.opaque.write_with(|dest| {
193                        *dest = last_location.to_le_bytes();
194                        needed
195                    });
196                }
197            }
198            Entry::Vacant(v) => {
199                let position = self.opaque.position();
200                v.insert(position);
201                // Data is encoded with a SpanTag prefix (see below).
202                span.data().encode(self);
203            }
204        }
205    }
206
207    fn encode_symbol(&mut self, sym: Symbol) {
208        self.encode_symbol_or_byte_symbol(sym.as_u32(), |this| this.emit_str(sym.as_str()));
209    }
210
211    fn encode_byte_symbol(&mut self, byte_sym: ByteSymbol) {
212        self.encode_symbol_or_byte_symbol(byte_sym.as_u32(), |this| {
213            this.emit_byte_str(byte_sym.as_byte_str())
214        });
215    }
216}
217
218fn bytes_needed(n: usize) -> usize {
219    (usize::BITS - n.leading_zeros()).div_ceil(u8::BITS) as usize
220}
221
222impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for SpanData {
223    fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
224        // Don't serialize any `SyntaxContext`s from a proc-macro crate,
225        // since we don't load proc-macro dependencies during serialization.
226        // This means that any hygiene information from macros used *within*
227        // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro
228        // definition) will be lost.
229        //
230        // This can show up in two ways:
231        //
232        // 1. Any hygiene information associated with identifier of
233        // a proc macro (e.g. `#[proc_macro] pub fn $name`) will be lost.
234        // Since proc-macros can only be invoked from a different crate,
235        // real code should never need to care about this.
236        //
237        // 2. Using `Span::def_site` or `Span::mixed_site` will not
238        // include any hygiene information associated with the definition
239        // site. This means that a proc-macro cannot emit a `$crate`
240        // identifier which resolves to one of its dependencies,
241        // which also should never come up in practice.
242        //
243        // Additionally, this affects `Span::parent`, and any other
244        // span inspection APIs that would otherwise allow traversing
245        // the `SyntaxContexts` associated with a span.
246        //
247        // None of these user-visible effects should result in any
248        // cross-crate inconsistencies (getting one behavior in the same
249        // crate, and a different behavior in another crate) due to the
250        // limited surface that proc-macros can expose.
251        //
252        // IMPORTANT: If this is ever changed, be sure to update
253        // `rustc_span::hygiene::raw_encode_expn_id` to handle
254        // encoding `ExpnData` for proc-macro crates.
255        let ctxt = if s.is_proc_macro { SyntaxContext::root() } else { self.ctxt };
256
257        if self.is_dummy() {
258            let tag = SpanTag::new(SpanKind::Partial, ctxt, 0);
259            tag.encode(s);
260            if tag.context().is_none() {
261                ctxt.encode(s);
262            }
263            return;
264        }
265
266        // The Span infrastructure should make sure that this invariant holds:
267        if true {
    if !(self.lo <= self.hi) {
        ::core::panicking::panic("assertion failed: self.lo <= self.hi")
    };
};debug_assert!(self.lo <= self.hi);
268
269        if !s.source_file_cache.0.contains(self.lo) {
270            let source_map = s.tcx.sess.source_map();
271            let source_file_index = source_map.lookup_source_file_idx(self.lo);
272            s.source_file_cache =
273                (Arc::clone(&source_map.files()[source_file_index]), source_file_index);
274        }
275        let (ref source_file, source_file_index) = s.source_file_cache;
276        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));
277
278        if !source_file.contains(self.hi) {
279            // Unfortunately, macro expansion still sometimes generates Spans
280            // that malformed in this way.
281            let tag = SpanTag::new(SpanKind::Partial, ctxt, 0);
282            tag.encode(s);
283            if tag.context().is_none() {
284                ctxt.encode(s);
285            }
286            return;
287        }
288
289        // There are two possible cases here:
290        // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the
291        // crate we are writing metadata for. When the metadata for *this* crate gets
292        // deserialized, the deserializer will need to know which crate it originally came
293        // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should
294        // be deserialized after the rest of the span data, which tells the deserializer
295        // which crate contains the source map information.
296        // 2. This span comes from our own crate. No special handling is needed - we just
297        // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use
298        // our own source map information.
299        //
300        // If we're a proc-macro crate, we always treat this as a local `Span`.
301        // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata
302        // if we're a proc-macro crate.
303        // This allows us to avoid loading the dependencies of proc-macro crates: all of
304        // the information we need to decode `Span`s is stored in the proc-macro crate.
305        let (kind, metadata_index) = if source_file.is_imported() && !s.is_proc_macro {
306            // To simplify deserialization, we 'rebase' this span onto the crate it originally came
307            // from (the crate that 'owns' the file it references. These rebased 'lo' and 'hi'
308            // values are relative to the source map information for the 'foreign' crate whose
309            // CrateNum we write into the metadata. This allows `imported_source_files` to binary
310            // search through the 'foreign' crate's source map information, using the
311            // deserialized 'lo' and 'hi' values directly.
312            //
313            // All of this logic ensures that the final result of deserialization is a 'normal'
314            // Span that can be used without any additional trouble.
315            let metadata_index = {
316                // Introduce a new scope so that we drop the 'read()' temporary
317                match &*source_file.external_src.read() {
318                    ExternalSource::Foreign { metadata_index, .. } => *metadata_index,
319                    src => {
    ::core::panicking::panic_fmt(format_args!("Unexpected external source {0:?}",
            src));
}panic!("Unexpected external source {src:?}"),
320                }
321            };
322
323            (SpanKind::Foreign, metadata_index)
324        } else {
325            // Record the fact that we need to encode the data for this `SourceFile`
326            let source_files =
327                s.required_source_files.as_mut().expect("Already encoded SourceMap!");
328            let (metadata_index, _) = source_files.insert_full(source_file_index);
329            let metadata_index: u32 =
330                metadata_index.try_into().expect("cannot export more than U32_MAX files");
331
332            (SpanKind::Local, metadata_index)
333        };
334
335        // Encode the start position relative to the file start, so we profit more from the
336        // variable-length integer encoding.
337        let lo = self.lo - source_file.start_pos;
338
339        // Encode length which is usually less than span.hi and profits more
340        // from the variable-length integer encoding that we use.
341        let len = self.hi - self.lo;
342
343        let tag = SpanTag::new(kind, ctxt, len.0 as usize);
344        tag.encode(s);
345        if tag.context().is_none() {
346            ctxt.encode(s);
347        }
348        lo.encode(s);
349        if tag.length().is_none() {
350            len.encode(s);
351        }
352
353        // Encode the index of the `SourceFile` for the span, in order to make decoding faster.
354        metadata_index.encode(s);
355
356        if kind == SpanKind::Foreign {
357            // This needs to be two lines to avoid holding the `s.source_file_cache`
358            // while calling `cnum.encode(s)`
359            let cnum = s.source_file_cache.0.cnum;
360            cnum.encode(s);
361        }
362    }
363}
364
365impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for [u8] {
366    fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
367        Encoder::emit_usize(e, self.len());
368        e.emit_raw_bytes(self);
369    }
370}
371
372impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> {
373    const CLEAR_CROSS_CRATE: bool = true;
374
375    fn position(&self) -> usize {
376        self.opaque.position()
377    }
378
379    fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
380        &mut self.type_shorthands
381    }
382
383    fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
384        &mut self.predicate_shorthands
385    }
386
387    fn encode_alloc_id(&mut self, alloc_id: &rustc_middle::mir::interpret::AllocId) {
388        let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
389
390        index.encode(self);
391    }
392}
393
394// Shorthand for `$self.$tables.$table.set_some($def_id.index, $self.lazy($value))`, which would
395// normally need extra variables to avoid errors about multiple mutable borrows.
396macro_rules! record {
397    ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
398        {
399            let value = $value;
400            let lazy = $self.lazy(value);
401            $self.$tables.$table.set_some($def_id.index, lazy);
402        }
403    }};
404}
405
406// Shorthand for `$self.$tables.$table.set_some($def_id.index, $self.lazy_array($value))`, which would
407// normally need extra variables to avoid errors about multiple mutable borrows.
408macro_rules! record_array {
409    ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
410        {
411            let value = $value;
412            let lazy = $self.lazy_array(value);
413            $self.$tables.$table.set_some($def_id.index, lazy);
414        }
415    }};
416}
417
418macro_rules! record_defaulted_array {
419    ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
420        {
421            let value = $value;
422            let lazy = $self.lazy_array(value);
423            $self.$tables.$table.set($def_id.index, lazy);
424        }
425    }};
426}
427
428impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
429    fn emit_lazy_distance(&mut self, position: NonZero<usize>) {
430        let pos = position.get();
431        let distance = match self.lazy_state {
432            LazyState::NoNode => ::rustc_middle::util::bug::bug_fmt(format_args!("emit_lazy_distance: outside of a metadata node"))bug!("emit_lazy_distance: outside of a metadata node"),
433            LazyState::NodeStart(start) => {
434                let start = start.get();
435                if !(pos <= start) {
    ::core::panicking::panic("assertion failed: pos <= start")
};assert!(pos <= start);
436                start - pos
437            }
438            LazyState::Previous(last_pos) => {
439                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!(
440                    last_pos <= position,
441                    "make sure that the calls to `lazy*` \
442                     are in the same order as the metadata fields",
443                );
444                position.get() - last_pos.get()
445            }
446        };
447        self.lazy_state = LazyState::Previous(NonZero::new(pos).unwrap());
448        self.emit_usize(distance);
449    }
450
451    fn lazy<T: ParameterizedOverTcx, B: Borrow<T::Value<'tcx>>>(&mut self, value: B) -> LazyValue<T>
452    where
453        T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
454    {
455        let pos = NonZero::new(self.position()).unwrap();
456
457        {
    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);
458        self.lazy_state = LazyState::NodeStart(pos);
459        value.borrow().encode(self);
460        self.lazy_state = LazyState::NoNode;
461
462        if !(pos.get() <= self.position()) {
    ::core::panicking::panic("assertion failed: pos.get() <= self.position()")
};assert!(pos.get() <= self.position());
463
464        LazyValue::from_position(pos)
465    }
466
467    fn lazy_array<T: ParameterizedOverTcx, I: IntoIterator<Item = B>, B: Borrow<T::Value<'tcx>>>(
468        &mut self,
469        values: I,
470    ) -> LazyArray<T>
471    where
472        T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
473    {
474        let pos = NonZero::new(self.position()).unwrap();
475
476        {
    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);
477        self.lazy_state = LazyState::NodeStart(pos);
478        let len = values.into_iter().map(|value| value.borrow().encode(self)).count();
479        self.lazy_state = LazyState::NoNode;
480
481        if !(pos.get() <= self.position()) {
    ::core::panicking::panic("assertion failed: pos.get() <= self.position()")
};assert!(pos.get() <= self.position());
482
483        LazyArray::from_position_and_num_elems(pos, len)
484    }
485
486    fn encode_symbol_or_byte_symbol(
487        &mut self,
488        index: u32,
489        emit_str_or_byte_str: impl Fn(&mut Self),
490    ) {
491        // if symbol/byte symbol is predefined, emit tag and symbol index
492        if Symbol::is_predefined(index) {
493            self.opaque.emit_u8(SYMBOL_PREDEFINED);
494            self.opaque.emit_u32(index);
495        } else {
496            // otherwise write it as string or as offset to it
497            match self.symbol_index_table.entry(index) {
498                Entry::Vacant(o) => {
499                    self.opaque.emit_u8(SYMBOL_STR);
500                    let pos = self.opaque.position();
501                    o.insert(pos);
502                    emit_str_or_byte_str(self);
503                }
504                Entry::Occupied(o) => {
505                    let x = *o.get();
506                    self.emit_u8(SYMBOL_OFFSET);
507                    self.emit_usize(x);
508                }
509            }
510        }
511    }
512
513    fn encode_def_path_table(&mut self) {
514        let defs = self.tcx.definitions();
515        if self.is_proc_macro {
516            for def_id in std::iter::once(CRATE_DEF_ID)
517                .chain(self.tcx.resolutions(()).proc_macros.iter().copied())
518            {
519                let def_key = self.lazy(defs.def_key(def_id));
520                let def_path_hash = defs.def_path_hash(def_id);
521                self.tables.def_keys.set_some(def_id.local_def_index, def_key);
522                self.tables
523                    .def_path_hashes
524                    .set(def_id.local_def_index, def_path_hash.local_hash().as_u64());
525            }
526        } else {
527            for (def_index, def_key, def_path_hash) in defs.enumerated_keys_and_path_hashes() {
528                let def_key = self.lazy(def_key);
529                self.tables.def_keys.set_some(def_index, def_key);
530                self.tables.def_path_hashes.set(def_index, def_path_hash.local_hash().as_u64());
531            }
532        }
533    }
534
535    fn encode_def_path_hash_map(&mut self) -> LazyValue<DefPathHashMapRef<'static>> {
536        self.lazy(DefPathHashMapRef::BorrowedFromTcx(self.tcx.def_path_hash_to_def_index_map()))
537    }
538
539    fn encode_source_map(&mut self) -> LazyTable<u32, Option<LazyValue<rustc_span::SourceFile>>> {
540        let source_map = self.tcx.sess.source_map();
541        let all_source_files = source_map.files();
542
543        // By replacing the `Option` with `None`, we ensure that we can't
544        // accidentally serialize any more `Span`s after the source map encoding
545        // is done.
546        let required_source_files = self.required_source_files.take().unwrap();
547
548        let mut adapted = TableBuilder::default();
549
550        let local_crate_stable_id = self.tcx.stable_crate_id(LOCAL_CRATE);
551
552        // Only serialize `SourceFile`s that were used during the encoding of a `Span`.
553        //
554        // The order in which we encode source files is important here: the on-disk format for
555        // `Span` contains the index of the corresponding `SourceFile`.
556        for (on_disk_index, &source_file_index) in required_source_files.iter().enumerate() {
557            let source_file = &all_source_files[source_file_index];
558            // Don't serialize imported `SourceFile`s, unless we're in a proc-macro crate.
559            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);
560
561            // At export time we expand all source file paths to absolute paths because
562            // downstream compilation sessions can have a different compiler working
563            // directory, so relative paths from this or any other upstream crate
564            // won't be valid anymore.
565            //
566            // At this point we also erase the actual on-disk path and only keep
567            // the remapped version -- as is necessary for reproducible builds.
568            let mut adapted_source_file = (**source_file).clone();
569
570            match source_file.name {
571                FileName::Real(ref original_file_name) => {
572                    let mut adapted_file_name = original_file_name.clone();
573                    adapted_file_name.update_for_crate_metadata();
574                    adapted_source_file.name = FileName::Real(adapted_file_name);
575                }
576                _ => {
577                    // expanded code, not from a file
578                }
579            };
580
581            // We're serializing this `SourceFile` into our crate metadata,
582            // so mark it as coming from this crate.
583            // This also ensures that we don't try to deserialize the
584            // `CrateNum` for a proc-macro dependency - since proc macro
585            // dependencies aren't loaded when we deserialize a proc-macro,
586            // trying to remap the `CrateNum` would fail.
587            if self.is_proc_macro {
588                adapted_source_file.cnum = LOCAL_CRATE;
589            }
590
591            // Update the `StableSourceFileId` to make sure it incorporates the
592            // id of the current crate. This way it will be unique within the
593            // crate graph during downstream compilation sessions.
594            adapted_source_file.stable_id = StableSourceFileId::from_filename_for_export(
595                &adapted_source_file.name,
596                local_crate_stable_id,
597            );
598
599            let on_disk_index: u32 =
600                on_disk_index.try_into().expect("cannot export more than U32_MAX files");
601            adapted.set_some(on_disk_index, self.lazy(adapted_source_file));
602        }
603
604        adapted.encode(&mut self.opaque)
605    }
606
607    fn encode_crate_root(&mut self) -> LazyValue<CrateRoot> {
608        let tcx = self.tcx;
609        let mut stats: Vec<(&'static str, usize)> = Vec::with_capacity(32);
610
611        macro_rules! stat {
612            ($label:literal, $f:expr) => {{
613                let orig_pos = self.position();
614                let res = $f();
615                stats.push(($label, self.position() - orig_pos));
616                res
617            }};
618        }
619
620        // We have already encoded some things. Get their combined size from the current position.
621        stats.push(("preamble", self.position()));
622
623        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
624            .encode_externally_implementable_items());
625
626        let (crate_deps, dylib_dependency_formats) =
627            {
    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()));
628
629        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());
630
631        let stability_implications =
632            {
    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());
633
634        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", || {
635            (self.encode_lang_items(), self.encode_lang_items_missing())
636        });
637
638        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());
639
640        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());
641
642        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());
643
644        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());
645
646        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());
647
648        _ = {
    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());
649
650        // Encode the def IDs of traits, for rustdoc and diagnostics.
651        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());
652
653        // Encode the def IDs of impls, for coherence checking.
654        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());
655
656        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());
657
658        _ = {
    let orig_pos = self.position();
    let res = (|| self.encode_mir())();
    stats.push(("mir", self.position() - orig_pos));
    res
}stat!("mir", || self.encode_mir());
659
660        _ = {
    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());
661
662        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 compiler/rustc_metadata/src/rmeta/encoder.rs:665",
                                            "rustc_metadata::rmeta::encoder", ::tracing::Level::TRACE,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                            ::tracing_core::__macro_support::Option::Some(665u32),
                                            ::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 compiler/rustc_metadata/src/rmeta/encoder.rs:673",
                                                "rustc_metadata::rmeta::encoder", ::tracing::Level::TRACE,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                                ::tracing_core::__macro_support::Option::Some(673u32),
                                                ::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", || {
663            let mut interpret_alloc_index = Vec::new();
664            let mut n = 0;
665            trace!("beginning to encode alloc ids");
666            loop {
667                let new_n = self.interpret_allocs.len();
668                // if we have found new ids, serialize those, too
669                if n == new_n {
670                    // otherwise, abort
671                    break;
672                }
673                trace!("encoding {} further alloc ids", new_n - n);
674                for idx in n..new_n {
675                    let id = self.interpret_allocs[idx];
676                    let pos = self.position() as u64;
677                    interpret_alloc_index.push(pos);
678                    interpret::specialized_encode_alloc_id(self, tcx, id);
679                }
680                n = new_n;
681            }
682            self.lazy_array(interpret_alloc_index)
683        });
684
685        // Encode the proc macro data. This affects `tables`, so we need to do this before we
686        // encode the tables. This overwrites def_keys, so it must happen after
687        // encode_def_path_table.
688        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());
689
690        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));
691
692        let debugger_visualizers =
693            {
    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());
694
695        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());
696
697        let stable_order_of_exportable_impls =
698            {
    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());
699
700        // Encode exported symbols info. This is prefetched in `encode_metadata`.
701        let (exported_non_generic_symbols, exported_generic_symbols) =
702            {
    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", || {
703                (
704                    self.encode_exported_symbols(tcx.exported_non_generic_symbols(LOCAL_CRATE)),
705                    self.encode_exported_symbols(tcx.exported_generic_symbols(LOCAL_CRATE)),
706                )
707            });
708
709        // Encode the hygiene data.
710        // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The
711        // process of encoding other items (e.g. `optimized_mir`) may cause us to load data from
712        // the incremental cache. If this causes us to deserialize a `Span`, then we may load
713        // additional `SyntaxContext`s into the global `HygieneData`. Therefore, we need to encode
714        // the hygiene data last to ensure that we encode any `SyntaxContext`s that might be used.
715        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());
716
717        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());
718
719        // Encode source_map. This needs to be done last, because encoding `Span`s tells us which
720        // `SourceFiles` we actually need to encode.
721        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());
722        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());
723        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
724            .encode_enabled_denied_partial_mitigations());
725
726        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_hir::attrs::AttributeKind::*;
                                                let i: &::rustc_hir::Attribute = i;
                                                match i {
                                                    ::rustc_hir::Attribute::Parsed(DefaultLibAllocator) => {
                                                        break 'done Some(());
                                                    }
                                                    ::rustc_hir::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_hir::attrs::AttributeKind::*;
                                                let i: &::rustc_hir::Attribute = i;
                                                match i {
                                                    ::rustc_hir::Attribute::Parsed(CompilerBuiltins) => {
                                                        break 'done Some(());
                                                    }
                                                    ::rustc_hir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }.is_some()
                            },
                            needs_allocator: {
                                {
                                        'done:
                                            {
                                            for i in attrs {
                                                #[allow(unused_imports)]
                                                use ::rustc_hir::attrs::AttributeKind::*;
                                                let i: &::rustc_hir::Attribute = i;
                                                match i {
                                                    ::rustc_hir::Attribute::Parsed(NeedsAllocator) => {
                                                        break 'done Some(());
                                                    }
                                                    ::rustc_hir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }.is_some()
                            },
                            needs_panic_runtime: {
                                {
                                        'done:
                                            {
                                            for i in attrs {
                                                #[allow(unused_imports)]
                                                use ::rustc_hir::attrs::AttributeKind::*;
                                                let i: &::rustc_hir::Attribute = i;
                                                match i {
                                                    ::rustc_hir::Attribute::Parsed(NeedsPanicRuntime) => {
                                                        break 'done Some(());
                                                    }
                                                    ::rustc_hir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }.is_some()
                            },
                            no_builtins: {
                                {
                                        'done:
                                            {
                                            for i in attrs {
                                                #[allow(unused_imports)]
                                                use ::rustc_hir::attrs::AttributeKind::*;
                                                let i: &::rustc_hir::Attribute = i;
                                                match i {
                                                    ::rustc_hir::Attribute::Parsed(NoBuiltins) => {
                                                        break 'done Some(());
                                                    }
                                                    ::rustc_hir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }.is_some()
                            },
                            panic_runtime: {
                                {
                                        'done:
                                            {
                                            for i in attrs {
                                                #[allow(unused_imports)]
                                                use ::rustc_hir::attrs::AttributeKind::*;
                                                let i: &::rustc_hir::Attribute = i;
                                                match i {
                                                    ::rustc_hir::Attribute::Parsed(PanicRuntime) => {
                                                        break 'done Some(());
                                                    }
                                                    ::rustc_hir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }.is_some()
                            },
                            profiler_runtime: {
                                {
                                        'done:
                                            {
                                            for i in attrs {
                                                #[allow(unused_imports)]
                                                use ::rustc_hir::attrs::AttributeKind::*;
                                                let i: &::rustc_hir::Attribute = i;
                                                match i {
                                                    ::rustc_hir::Attribute::Parsed(ProfilerRuntime) => {
                                                        break 'done Some(());
                                                    }
                                                    ::rustc_hir::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,
                            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", || {
727            let attrs = tcx.hir_krate_attrs();
728            self.lazy(CrateRoot {
729                header: CrateHeader {
730                    name: tcx.crate_name(LOCAL_CRATE),
731                    triple: tcx.sess.opts.target_triple.clone(),
732                    hash: tcx.crate_hash(LOCAL_CRATE),
733                    is_proc_macro_crate: proc_macro_data.is_some(),
734                    is_stub: false,
735                },
736                extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
737                stable_crate_id: tcx.stable_crate_id(LOCAL_CRATE),
738                required_panic_strategy: tcx.required_panic_strategy(LOCAL_CRATE),
739                panic_in_drop_strategy: tcx.sess.opts.unstable_opts.panic_in_drop,
740                edition: tcx.sess.edition(),
741                has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
742                has_alloc_error_handler: tcx.has_alloc_error_handler(LOCAL_CRATE),
743                has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
744                has_default_lib_allocator: find_attr!(attrs, DefaultLibAllocator),
745                externally_implementable_items,
746                proc_macro_data,
747                debugger_visualizers,
748                compiler_builtins: find_attr!(attrs, CompilerBuiltins),
749                needs_allocator: find_attr!(attrs, NeedsAllocator),
750                needs_panic_runtime: find_attr!(attrs, NeedsPanicRuntime),
751                no_builtins: find_attr!(attrs, NoBuiltins),
752                panic_runtime: find_attr!(attrs, PanicRuntime),
753                profiler_runtime: find_attr!(attrs, ProfilerRuntime),
754                symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(),
755
756                crate_deps,
757                dylib_dependency_formats,
758                lib_features,
759                stability_implications,
760                lang_items,
761                diagnostic_items,
762                canonical_symbols,
763                lang_items_missing,
764                stripped_cfg_items,
765                native_libraries,
766                foreign_modules,
767                source_map,
768                target_modifiers,
769                denied_partial_mitigations,
770                traits,
771                impls,
772                incoherent_impls,
773                exportable_items,
774                stable_order_of_exportable_impls,
775                exported_non_generic_symbols,
776                exported_generic_symbols,
777                interpret_alloc_index,
778                tables,
779                syntax_contexts,
780                expn_data,
781                expn_hashes,
782                def_path_hash_map,
783                specialization_enabled_in: tcx.specialization_enabled_in(LOCAL_CRATE),
784            })
785        });
786
787        let total_bytes = self.position();
788
789        let computed_total_bytes: usize = stats.iter().map(|(_, size)| size).sum();
790        {
    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);
791
792        if tcx.sess.opts.unstable_opts.meta_stats {
793            use std::fmt::Write;
794
795            self.opaque.flush();
796
797            // Rewind and re-read all the metadata to count the zero bytes we wrote.
798            let pos_before_rewind = self.opaque.file().stream_position().unwrap();
799            let mut zero_bytes = 0;
800            self.opaque.file().rewind().unwrap();
801            let file = std::io::BufReader::new(self.opaque.file());
802            for e in file.bytes() {
803                if e.unwrap() == 0 {
804                    zero_bytes += 1;
805                }
806            }
807            {
    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);
808
809            stats.sort_by_key(|&(_, usize)| usize);
810            stats.reverse(); // bigger items first
811
812            let prefix = "meta-stats";
813            let perc = |bytes| (bytes * 100) as f64 / total_bytes as f64;
814
815            let section_w = 23;
816            let size_w = 10;
817            let banner_w = 64;
818
819            // We write all the text into a string and print it with a single
820            // `eprint!`. This is an attempt to minimize interleaved text if multiple
821            // rustc processes are printing macro-stats at the same time (e.g. with
822            // `RUSTFLAGS='-Zmeta-stats' cargo build`). It still doesn't guarantee
823            // non-interleaving, though.
824            let mut s = String::new();
825            _ = s.write_fmt(format_args!("{1} {0}\n", "=".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "=".repeat(banner_w));
826            _ = 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));
827            _ = 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");
828            _ = s.write_fmt(format_args!("{1} {0}\n", "-".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "-".repeat(banner_w));
829            for (label, size) in stats {
830                _ = 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!(
831                    s,
832                    "{prefix} {:<section_w$}{:>size_w$} ({:4.1}%)",
833                    label,
834                    usize_with_underscores(size),
835                    perc(size)
836                );
837            }
838            _ = s.write_fmt(format_args!("{1} {0}\n", "-".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "-".repeat(banner_w));
839            _ = 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!(
840                s,
841                "{prefix} {:<section_w$}{:>size_w$} (of which {:.1}% are zero bytes)",
842                "Total",
843                usize_with_underscores(total_bytes),
844                perc(zero_bytes)
845            );
846            _ = s.write_fmt(format_args!("{1} {0}\n", "=".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "=".repeat(banner_w));
847            { ::std::io::_eprint(format_args!("{0}", s)); };eprint!("{s}");
848        }
849
850        root
851    }
852}
853
854struct AnalyzeAttrState {
855    is_exported: bool,
856    is_doc_hidden: bool,
857}
858
859/// Returns whether an attribute needs to be recorded in metadata, that is, if it's usable and
860/// useful in downstream crates. Local-only attributes are an obvious example, but some
861/// rustdoc-specific attributes can equally be of use while documenting the current crate only.
862///
863/// Removing these superfluous attributes speeds up compilation by making the metadata smaller.
864///
865/// Note: the `is_exported` parameter is used to cache whether the given `DefId` has a public
866/// visibility: this is a piece of data that can be computed once per defid, and not once per
867/// attribute. Some attributes would only be usable downstream if they are public.
868#[inline]
869fn analyze_attr(attr: &hir::Attribute, state: &mut AnalyzeAttrState) -> bool {
870    let mut should_encode = false;
871    if let hir::Attribute::Parsed(p) = attr
872        && p.encode_cross_crate() == EncodeCrossCrate::No
873    {
874        // Attributes not marked encode-cross-crate don't need to be encoded for downstream crates.
875    } else if let Some(name) = attr.name()
876        && [sym::warn, sym::allow, sym::expect, sym::forbid, sym::deny].contains(&name)
877    {
878        // Lint attributes don't need to be encoded for downstream crates.
879        // FIXME remove this when #152369 is re-merged
880    } else if let hir::Attribute::Parsed(AttributeKind::DocComment { .. }) = attr {
881        // We keep all doc comments reachable to rustdoc because they might be "imported" into
882        // downstream crates if they use `#[doc(inline)]` to copy an item's documentation into
883        // their own.
884        if state.is_exported {
885            should_encode = true;
886        }
887    } else if let hir::Attribute::Parsed(AttributeKind::Doc(d)) = attr {
888        should_encode = true;
889        if d.hidden.is_some() {
890            state.is_doc_hidden = true;
891        }
892    } else {
893        should_encode = true;
894    }
895    should_encode
896}
897
898fn should_encode_span(def_kind: DefKind) -> bool {
899    match def_kind {
900        DefKind::Mod
901        | DefKind::Struct
902        | DefKind::Union
903        | DefKind::Enum
904        | DefKind::Variant
905        | DefKind::Trait
906        | DefKind::TyAlias
907        | DefKind::ForeignTy
908        | DefKind::TraitAlias
909        | DefKind::AssocTy
910        | DefKind::TyParam
911        | DefKind::ConstParam
912        | DefKind::LifetimeParam
913        | DefKind::Fn
914        | DefKind::Const { .. }
915        | DefKind::Static { .. }
916        | DefKind::Ctor(..)
917        | DefKind::AssocFn
918        | DefKind::AssocConst { .. }
919        | DefKind::Macro(_)
920        | DefKind::ExternCrate
921        | DefKind::Use
922        | DefKind::AnonConst
923        | DefKind::OpaqueTy
924        | DefKind::Field
925        | DefKind::Impl { .. }
926        | DefKind::Closure
927        | DefKind::SyntheticCoroutineBody => true,
928        DefKind::ForeignMod | DefKind::GlobalAsm => false,
929    }
930}
931
932fn should_encode_attrs(def_kind: DefKind) -> bool {
933    match def_kind {
934        DefKind::Mod
935        | DefKind::Struct
936        | DefKind::Union
937        | DefKind::Enum
938        | DefKind::Variant
939        | DefKind::Trait
940        | DefKind::TyAlias
941        | DefKind::ForeignTy
942        | DefKind::TraitAlias
943        | DefKind::AssocTy
944        | DefKind::Fn
945        | DefKind::Const { .. }
946        | DefKind::Static { nested: false, .. }
947        | DefKind::AssocFn
948        | DefKind::AssocConst { .. }
949        | DefKind::Macro(_)
950        | DefKind::Field
951        | DefKind::ConstParam
952        | DefKind::Impl { .. } => true,
953        // Encoding attrs for `Use` items allows `#[doc(hidden)]` on re-exports
954        // to be read cross-crate, which is needed for diagnostic path selection
955        // in `visible_parent_map`. See #153477.
956        DefKind::Use => true,
957        // Tools may want to be able to detect their tool lints on
958        // closures from upstream crates, too. This is used by
959        // https://github.com/model-checking/kani and is not a performance
960        // or maintenance issue for us.
961        DefKind::Closure => true,
962        DefKind::SyntheticCoroutineBody => false,
963        DefKind::TyParam
964        | DefKind::Ctor(..)
965        | DefKind::ExternCrate
966        | DefKind::ForeignMod
967        | DefKind::AnonConst
968        | DefKind::OpaqueTy
969        | DefKind::LifetimeParam
970        | DefKind::Static { nested: true, .. }
971        | DefKind::GlobalAsm => false,
972    }
973}
974
975fn should_encode_expn_that_defined(def_kind: DefKind) -> bool {
976    match def_kind {
977        DefKind::Mod
978        | DefKind::Struct
979        | DefKind::Union
980        | DefKind::Enum
981        | DefKind::Variant
982        | DefKind::Trait
983        | DefKind::Impl { .. } => true,
984        DefKind::TyAlias
985        | DefKind::ForeignTy
986        | DefKind::TraitAlias
987        | DefKind::AssocTy
988        | DefKind::TyParam
989        | DefKind::Fn
990        | DefKind::Const { .. }
991        | DefKind::ConstParam
992        | DefKind::Static { .. }
993        | DefKind::Ctor(..)
994        | DefKind::AssocFn
995        | DefKind::AssocConst { .. }
996        | DefKind::Macro(_)
997        | DefKind::ExternCrate
998        | DefKind::Use
999        | DefKind::ForeignMod
1000        | DefKind::AnonConst
1001        | DefKind::OpaqueTy
1002        | DefKind::Field
1003        | DefKind::LifetimeParam
1004        | DefKind::GlobalAsm
1005        | DefKind::Closure
1006        | DefKind::SyntheticCoroutineBody => false,
1007    }
1008}
1009
1010fn should_encode_visibility(def_kind: DefKind) -> bool {
1011    match def_kind {
1012        DefKind::Mod
1013        | DefKind::Struct
1014        | DefKind::Union
1015        | DefKind::Enum
1016        | DefKind::Variant
1017        | DefKind::Trait
1018        | DefKind::TyAlias
1019        | DefKind::ForeignTy
1020        | DefKind::TraitAlias
1021        | DefKind::AssocTy
1022        | DefKind::Fn
1023        | DefKind::Const { .. }
1024        | DefKind::Static { nested: false, .. }
1025        | DefKind::Ctor(..)
1026        | DefKind::AssocFn
1027        | DefKind::AssocConst { .. }
1028        | DefKind::Macro(..)
1029        | DefKind::Field => true,
1030        DefKind::Use
1031        | DefKind::ForeignMod
1032        | DefKind::TyParam
1033        | DefKind::ConstParam
1034        | DefKind::LifetimeParam
1035        | DefKind::AnonConst
1036        | DefKind::Static { nested: true, .. }
1037        | DefKind::OpaqueTy
1038        | DefKind::GlobalAsm
1039        | DefKind::Impl { .. }
1040        | DefKind::Closure
1041        | DefKind::ExternCrate
1042        | DefKind::SyntheticCoroutineBody => false,
1043    }
1044}
1045
1046fn should_encode_stability(def_kind: DefKind) -> bool {
1047    match def_kind {
1048        DefKind::Mod
1049        | DefKind::Ctor(..)
1050        | DefKind::Variant
1051        | DefKind::Field
1052        | DefKind::Struct
1053        | DefKind::AssocTy
1054        | DefKind::AssocFn
1055        | DefKind::AssocConst { .. }
1056        | DefKind::TyParam
1057        | DefKind::ConstParam
1058        | DefKind::Static { .. }
1059        | DefKind::Const { .. }
1060        | DefKind::Fn
1061        | DefKind::ForeignMod
1062        | DefKind::TyAlias
1063        | DefKind::OpaqueTy
1064        | DefKind::Enum
1065        | DefKind::Union
1066        | DefKind::Impl { .. }
1067        | DefKind::Trait
1068        | DefKind::TraitAlias
1069        | DefKind::Macro(..)
1070        | DefKind::ForeignTy => true,
1071        DefKind::Use
1072        | DefKind::LifetimeParam
1073        | DefKind::AnonConst
1074        | DefKind::GlobalAsm
1075        | DefKind::Closure
1076        | DefKind::ExternCrate
1077        | DefKind::SyntheticCoroutineBody => false,
1078    }
1079}
1080
1081/// Whether we should encode MIR. Return a pair, resp. for CTFE and for LLVM.
1082///
1083/// Computing, optimizing and encoding the MIR is a relatively expensive operation.
1084/// We want to avoid this work when not required. Therefore:
1085/// - we only compute `mir_for_ctfe` on items with const-eval semantics;
1086/// - we skip `optimized_mir` for check runs.
1087/// - we only encode `optimized_mir` that could be generated in other crates, that is, a code that
1088///   is either generic or has inline hint, and is reachable from the other crates (contained
1089///   in reachable set).
1090///
1091/// Note: Reachable set describes definitions that might be generated or referenced from other
1092/// crates and it can be used to limit optimized MIR that needs to be encoded. On the other hand,
1093/// the reachable set doesn't have much to say about which definitions might be evaluated at compile
1094/// time in other crates, so it cannot be used to omit CTFE MIR. For example, `f` below is
1095/// unreachable and yet it can be evaluated in other crates:
1096///
1097/// ```
1098/// const fn f() -> usize { 0 }
1099/// pub struct S { pub a: [usize; f()] }
1100/// ```
1101fn should_encode_mir(
1102    tcx: TyCtxt<'_>,
1103    reachable_set: &LocalDefIdSet,
1104    def_id: LocalDefId,
1105) -> (bool, bool) {
1106    match tcx.def_kind(def_id) {
1107        // instance_mir uses mir_for_ctfe rather than optimized_mir for constructors
1108        DefKind::Ctor(_, _) => (true, false),
1109        // Constants
1110        DefKind::AnonConst | DefKind::AssocConst { .. } | DefKind::Const { .. } => (true, false),
1111        // Coroutines require optimized MIR to compute layout.
1112        DefKind::Closure if tcx.is_coroutine(def_id.to_def_id()) => (false, true),
1113        DefKind::SyntheticCoroutineBody => (false, true),
1114        // Full-fledged functions + closures
1115        DefKind::AssocFn | DefKind::Fn | DefKind::Closure => {
1116            let opt = tcx.sess.opts.unstable_opts.always_encode_mir
1117                || (tcx.sess.opts.output_types.should_codegen()
1118                    && reachable_set.contains(&def_id)
1119                    && (tcx.generics_of(def_id).requires_monomorphization(tcx)
1120                        || tcx.cross_crate_inlinable(def_id)));
1121            // Comptime fns do not have optimized MIR at all.
1122            let opt =
1123                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 });
1124            // The function has a `const` modifier or is in a `const trait`.
1125            let is_const_fn = tcx.is_const_fn(def_id.to_def_id());
1126            (is_const_fn, opt)
1127        }
1128        // The others don't have MIR.
1129        _ => (false, false),
1130    }
1131}
1132
1133fn should_encode_variances<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, def_kind: DefKind) -> bool {
1134    match def_kind {
1135        DefKind::Struct
1136        | DefKind::Union
1137        | DefKind::Enum
1138        | DefKind::OpaqueTy
1139        | DefKind::Fn
1140        | DefKind::Ctor(..)
1141        | DefKind::AssocFn => true,
1142        DefKind::AssocTy => {
1143            // Only encode variances for RPITITs (for traits)
1144            #[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 { .. }))
1145        }
1146        DefKind::Mod
1147        | DefKind::Variant
1148        | DefKind::Field
1149        | DefKind::AssocConst { .. }
1150        | DefKind::TyParam
1151        | DefKind::ConstParam
1152        | DefKind::Static { .. }
1153        | DefKind::Const { .. }
1154        | DefKind::ForeignMod
1155        | DefKind::TyAlias
1156        | DefKind::Impl { .. }
1157        | DefKind::Trait
1158        | DefKind::TraitAlias
1159        | DefKind::Macro(..)
1160        | DefKind::ForeignTy
1161        | DefKind::Use
1162        | DefKind::LifetimeParam
1163        | DefKind::AnonConst
1164        | DefKind::GlobalAsm
1165        | DefKind::Closure
1166        | DefKind::ExternCrate
1167        | DefKind::SyntheticCoroutineBody => false,
1168    }
1169}
1170
1171fn should_encode_generics(def_kind: DefKind) -> bool {
1172    match def_kind {
1173        DefKind::Struct
1174        | DefKind::Union
1175        | DefKind::Enum
1176        | DefKind::Variant
1177        | DefKind::Trait
1178        | DefKind::TyAlias
1179        | DefKind::ForeignTy
1180        | DefKind::TraitAlias
1181        | DefKind::AssocTy
1182        | DefKind::Fn
1183        | DefKind::Const { .. }
1184        | DefKind::Static { .. }
1185        | DefKind::Ctor(..)
1186        | DefKind::AssocFn
1187        | DefKind::AssocConst { .. }
1188        | DefKind::AnonConst
1189        | DefKind::OpaqueTy
1190        | DefKind::Impl { .. }
1191        | DefKind::Field
1192        | DefKind::TyParam
1193        | DefKind::Closure
1194        | DefKind::SyntheticCoroutineBody => true,
1195        DefKind::Mod
1196        | DefKind::ForeignMod
1197        | DefKind::ConstParam
1198        | DefKind::Macro(..)
1199        | DefKind::Use
1200        | DefKind::LifetimeParam
1201        | DefKind::GlobalAsm
1202        | DefKind::ExternCrate => false,
1203    }
1204}
1205
1206fn should_encode_type(tcx: TyCtxt<'_>, def_id: LocalDefId, def_kind: DefKind) -> bool {
1207    match def_kind {
1208        DefKind::Struct
1209        | DefKind::Union
1210        | DefKind::Enum
1211        | DefKind::Variant
1212        | DefKind::Ctor(..)
1213        | DefKind::Field
1214        | DefKind::Fn
1215        | DefKind::Const { .. }
1216        | DefKind::Static { nested: false, .. }
1217        | DefKind::TyAlias
1218        | DefKind::ForeignTy
1219        | DefKind::Impl { .. }
1220        | DefKind::AssocFn
1221        | DefKind::AssocConst { .. }
1222        | DefKind::Closure
1223        | DefKind::ConstParam
1224        | DefKind::AnonConst
1225        | DefKind::SyntheticCoroutineBody => true,
1226
1227        DefKind::OpaqueTy => {
1228            let origin = tcx.local_opaque_ty_origin(def_id);
1229            if let hir::OpaqueTyOrigin::FnReturn { parent, .. }
1230            | hir::OpaqueTyOrigin::AsyncFn { parent, .. } = origin
1231                && let hir::Node::TraitItem(trait_item) = tcx.hir_node_by_def_id(parent)
1232                && let (_, hir::TraitFn::Required(..)) = trait_item.expect_fn()
1233            {
1234                false
1235            } else {
1236                true
1237            }
1238        }
1239
1240        DefKind::AssocTy => {
1241            let assoc_item = tcx.associated_item(def_id);
1242            match assoc_item.container {
1243                ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => true,
1244                ty::AssocContainer::Trait => assoc_item.defaultness(tcx).has_value(),
1245            }
1246        }
1247        DefKind::TyParam => {
1248            let hir::Node::GenericParam(param) = tcx.hir_node_by_def_id(def_id) else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
1249            let hir::GenericParamKind::Type { default, .. } = param.kind else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
1250            default.is_some()
1251        }
1252
1253        DefKind::Trait
1254        | DefKind::TraitAlias
1255        | DefKind::Mod
1256        | DefKind::ForeignMod
1257        | DefKind::Macro(..)
1258        | DefKind::Static { nested: true, .. }
1259        | DefKind::Use
1260        | DefKind::LifetimeParam
1261        | DefKind::GlobalAsm
1262        | DefKind::ExternCrate => false,
1263    }
1264}
1265
1266fn should_encode_fn_sig(def_kind: DefKind) -> bool {
1267    match def_kind {
1268        DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) => true,
1269
1270        DefKind::Struct
1271        | DefKind::Union
1272        | DefKind::Enum
1273        | DefKind::Variant
1274        | DefKind::Field
1275        | DefKind::Const { .. }
1276        | DefKind::Static { .. }
1277        | DefKind::Ctor(..)
1278        | DefKind::TyAlias
1279        | DefKind::OpaqueTy
1280        | DefKind::ForeignTy
1281        | DefKind::Impl { .. }
1282        | DefKind::AssocConst { .. }
1283        | DefKind::Closure
1284        | DefKind::ConstParam
1285        | DefKind::AnonConst
1286        | DefKind::AssocTy
1287        | DefKind::TyParam
1288        | DefKind::Trait
1289        | DefKind::TraitAlias
1290        | DefKind::Mod
1291        | DefKind::ForeignMod
1292        | DefKind::Macro(..)
1293        | DefKind::Use
1294        | DefKind::LifetimeParam
1295        | DefKind::GlobalAsm
1296        | DefKind::ExternCrate
1297        | DefKind::SyntheticCoroutineBody => false,
1298    }
1299}
1300
1301fn should_encode_constness(def_kind: DefKind) -> bool {
1302    match def_kind {
1303        DefKind::Fn
1304        | DefKind::AssocFn
1305        | DefKind::Closure
1306        | DefKind::Ctor(_, CtorKind::Fn)
1307        | DefKind::Impl { of_trait: false } => true,
1308
1309        DefKind::Struct
1310        | DefKind::Union
1311        | DefKind::Enum
1312        | DefKind::Field
1313        | DefKind::Const { .. }
1314        | DefKind::AssocConst { .. }
1315        | DefKind::AnonConst
1316        | DefKind::Static { .. }
1317        | DefKind::TyAlias
1318        | DefKind::OpaqueTy
1319        | DefKind::Impl { .. }
1320        | DefKind::ForeignTy
1321        | DefKind::ConstParam
1322        | DefKind::AssocTy
1323        | DefKind::TyParam
1324        | DefKind::Trait
1325        | DefKind::TraitAlias
1326        | DefKind::Mod
1327        | DefKind::ForeignMod
1328        | DefKind::Macro(..)
1329        | DefKind::Use
1330        | DefKind::LifetimeParam
1331        | DefKind::GlobalAsm
1332        | DefKind::ExternCrate
1333        | DefKind::Ctor(_, CtorKind::Const)
1334        | DefKind::Variant
1335        | DefKind::SyntheticCoroutineBody => false,
1336    }
1337}
1338
1339fn should_encode_const(def_kind: DefKind) -> bool {
1340    match def_kind {
1341        // FIXME(mgca): should we remove Const and AssocConst here?
1342        DefKind::Const { .. } | DefKind::AssocConst { .. } | DefKind::AnonConst => true,
1343
1344        DefKind::Struct
1345        | DefKind::Union
1346        | DefKind::Enum
1347        | DefKind::Variant
1348        | DefKind::Ctor(..)
1349        | DefKind::Field
1350        | DefKind::Fn
1351        | DefKind::Static { .. }
1352        | DefKind::TyAlias
1353        | DefKind::OpaqueTy
1354        | DefKind::ForeignTy
1355        | DefKind::Impl { .. }
1356        | DefKind::AssocFn
1357        | DefKind::Closure
1358        | DefKind::ConstParam
1359        | DefKind::AssocTy
1360        | DefKind::TyParam
1361        | DefKind::Trait
1362        | DefKind::TraitAlias
1363        | DefKind::Mod
1364        | DefKind::ForeignMod
1365        | DefKind::Macro(..)
1366        | DefKind::Use
1367        | DefKind::LifetimeParam
1368        | DefKind::GlobalAsm
1369        | DefKind::ExternCrate
1370        | DefKind::SyntheticCoroutineBody => false,
1371    }
1372}
1373
1374fn should_encode_const_of_item<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, def_kind: DefKind) -> bool {
1375    // AssocConst ==> assoc item has value
1376    tcx.is_type_const(def_id)
1377        && (!#[allow(non_exhaustive_omitted_patterns)] match def_kind {
    DefKind::AssocConst { .. } => true,
    _ => false,
}matches!(def_kind, DefKind::AssocConst { .. }) || assoc_item_has_value(tcx, def_id))
1378}
1379
1380fn assoc_item_has_value<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool {
1381    let assoc_item = tcx.associated_item(def_id);
1382    match assoc_item.container {
1383        ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => true,
1384        ty::AssocContainer::Trait => assoc_item.defaultness(tcx).has_value(),
1385    }
1386}
1387
1388impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1389    fn encode_attrs(&mut self, def_id: LocalDefId) {
1390        let tcx = self.tcx;
1391        let mut state = AnalyzeAttrState {
1392            is_exported: tcx.effective_visibilities(()).is_exported(def_id),
1393            is_doc_hidden: false,
1394        };
1395        let attr_iter = tcx
1396            .hir_attrs(tcx.local_def_id_to_hir_id(def_id))
1397            .iter()
1398            .filter(|attr| analyze_attr(*attr, &mut state));
1399
1400        {
    {
        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);
1401
1402        let mut attr_flags = AttrFlags::empty();
1403        if state.is_doc_hidden {
1404            attr_flags |= AttrFlags::IS_DOC_HIDDEN;
1405        }
1406        self.tables.attr_flags.set(def_id.local_def_index, attr_flags);
1407    }
1408
1409    fn encode_def_ids(&mut self) {
1410        self.encode_info_for_mod(CRATE_DEF_ID);
1411
1412        // Proc-macro crates only export proc-macro items, which are looked
1413        // up using `proc_macro_data`
1414        if self.is_proc_macro {
1415            return;
1416        }
1417
1418        let tcx = self.tcx;
1419
1420        for local_id in tcx.iter_local_def_id() {
1421            let def_id = local_id.to_def_id();
1422            let def_kind = tcx.def_kind(local_id);
1423            self.tables.def_kind.set_some(def_id.index, def_kind);
1424
1425            // The `DefCollector` will sometimes create unnecessary `DefId`s
1426            // for trivial const arguments which are directly lowered to
1427            // `ConstArgKind::Path`. We never actually access this `DefId`
1428            // anywhere so we don't need to encode it for other crates.
1429            // FIXME(mgca): This probably isn't true, they probably are accessed, but, test case?
1430            if def_kind == DefKind::AnonConst
1431                && #[allow(non_exhaustive_omitted_patterns)] match tcx.hir_node_by_def_id(local_id)
    {
    hir::Node::ConstArg(_) => true,
    _ => false,
}matches!(tcx.hir_node_by_def_id(local_id), hir::Node::ConstArg(_))
1432            {
1433                continue;
1434            }
1435
1436            if def_kind == DefKind::Field
1437                && let hir::Node::Field(field) = tcx.hir_node_by_def_id(local_id)
1438                && let Some(anon) = field.default
1439            {
1440                {
    {
        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());
1441            }
1442
1443            if should_encode_span(def_kind) {
1444                let def_span = tcx.def_span(local_id);
1445                {
    {
        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);
1446            }
1447            if should_encode_attrs(def_kind) {
1448                self.encode_attrs(local_id);
1449            }
1450            if should_encode_expn_that_defined(def_kind) {
1451                {
    {
        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));
1452            }
1453            if should_encode_span(def_kind)
1454                && let Some(ident_span) = tcx.def_ident_span(def_id)
1455            {
1456                {
    {
        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);
1457            }
1458            if def_kind.has_codegen_attrs() {
1459                {
    {
        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));
1460            }
1461            if should_encode_visibility(def_kind) {
1462                let vis = self
1463                    .tcx
1464                    .local_visibility(local_id)
1465                    .map_id(|mod_id| mod_id.to_local_def_id().local_def_index);
1466                {
    {
        let value = vis;
        let lazy = self.lazy(value);
        self.tables.visibility.set_some(def_id.index, lazy);
    }
};record!(self.tables.visibility[def_id] <- vis);
1467            }
1468            if should_encode_stability(def_kind) {
1469                self.encode_stability(def_id);
1470                self.encode_const_stability(def_id);
1471                self.encode_default_body_stability(def_id);
1472                self.encode_deprecation(def_id);
1473            }
1474            if should_encode_variances(tcx, def_id, def_kind) {
1475                let v = self.tcx.variances_of(def_id);
1476                {
    {
        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);
1477            }
1478            if should_encode_fn_sig(def_kind) {
1479                {
    {
        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));
1480            }
1481            if should_encode_generics(def_kind) {
1482                let g = tcx.generics_of(def_id);
1483                {
    {
        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);
1484                {
    {
        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));
1485                let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
1486                {
    {
        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);
1487
1488                for param in &g.own_params {
1489                    if let ty::GenericParamDefKind::Const { has_default: true, .. } = param.kind {
1490                        let default = self.tcx.const_param_default(param.def_id);
1491                        {
    {
        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);
1492                    }
1493                }
1494            }
1495            if tcx.is_conditionally_const(def_id) {
1496                {
    {
        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));
1497            }
1498            if should_encode_type(tcx, local_id, def_kind) {
1499                {
    {
        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));
1500            }
1501            if should_encode_constness(def_kind) {
1502                let constness = self.tcx.constness(def_id);
1503                self.tables.constness.set(def_id.index, constness);
1504            }
1505            if let DefKind::Fn | DefKind::AssocFn = def_kind {
1506                let asyncness = tcx.asyncness(def_id);
1507                self.tables.asyncness.set(def_id.index, asyncness);
1508                {
    {
        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));
1509            }
1510            if let Some(name) = tcx.intrinsic(def_id) {
1511                {
    {
        let value = name;
        let lazy = self.lazy(value);
        self.tables.intrinsic.set_some(def_id.index, lazy);
    }
};record!(self.tables.intrinsic[def_id] <- name);
1512            }
1513            if let DefKind::TyParam | DefKind::Trait = def_kind {
1514                let default = self.tcx.object_lifetime_default(def_id);
1515                {
    {
        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);
1516            }
1517            if let DefKind::Trait = def_kind {
1518                {
    {
        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));
1519                {
    {
        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] <-
1520                    self.tcx.explicit_super_clauses_of(def_id).skip_binder());
1521                {
    {
        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] <-
1522                    self.tcx.explicit_implied_clauses_of(def_id).skip_binder());
1523                let module_children = self.tcx.module_children_local(local_id);
1524                {
    {
        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] <-
1525                    module_children.iter().map(|child| child.res.def_id().index));
1526                if self.tcx.is_const_trait(def_id) {
1527                    {
    {
        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]
1528                        <- self.tcx.explicit_implied_const_bounds(def_id).skip_binder());
1529                }
1530            }
1531            if let DefKind::TraitAlias = def_kind {
1532                {
    {
        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));
1533                {
    {
        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] <-
1534                    self.tcx.explicit_super_clauses_of(def_id).skip_binder());
1535                {
    {
        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] <-
1536                    self.tcx.explicit_implied_clauses_of(def_id).skip_binder());
1537            }
1538            if let DefKind::Trait | DefKind::Impl { .. } = def_kind {
1539                let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1540                {
    {
        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] <-
1541                    associated_item_def_ids.iter().map(|&def_id| {
1542                        assert!(def_id.is_local());
1543                        def_id.index
1544                    })
1545                );
1546                for &def_id in associated_item_def_ids {
1547                    self.encode_info_for_assoc_item(def_id);
1548                }
1549            }
1550            if let DefKind::Closure | DefKind::SyntheticCoroutineBody = def_kind
1551                && let Some(coroutine_kind) = self.tcx.coroutine_kind(def_id)
1552            {
1553                self.tables.coroutine_kind.set(def_id.index, Some(coroutine_kind))
1554            }
1555            if def_kind == DefKind::Closure
1556                && tcx.type_of(def_id).skip_binder().is_coroutine_closure()
1557            {
1558                let coroutine_for_closure = self.tcx.coroutine_for_closure(def_id);
1559                self.tables
1560                    .coroutine_for_closure
1561                    .set_some(def_id.index, coroutine_for_closure.into());
1562
1563                // If this async closure has a by-move body, record it too.
1564                if tcx.needs_coroutine_by_move_body_def_id(coroutine_for_closure) {
1565                    self.tables.coroutine_by_move_body_def_id.set_some(
1566                        coroutine_for_closure.index,
1567                        self.tcx.coroutine_by_move_body_def_id(coroutine_for_closure).into(),
1568                    );
1569                }
1570            }
1571            if let DefKind::Static { .. } = def_kind {
1572                if !self.tcx.is_foreign_item(def_id) {
1573                    let data = self.tcx.eval_static_initializer(def_id).unwrap();
1574                    {
    {
        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);
1575                }
1576            }
1577            if let DefKind::Enum | DefKind::Struct | DefKind::Union = def_kind {
1578                self.encode_info_for_adt(local_id);
1579            }
1580            if let DefKind::Mod = def_kind {
1581                self.encode_info_for_mod(local_id);
1582            }
1583            if let DefKind::Macro(_) = def_kind {
1584                self.encode_info_for_macro(local_id);
1585            }
1586            if let DefKind::TyAlias = def_kind {
1587                self.tables
1588                    .type_alias_is_checked
1589                    .set(def_id.index, self.tcx.type_alias_is_checked(def_id));
1590                if self.tcx.type_alias_is_checked(def_id) {
1591                    {
    {
        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));
1592                }
1593            }
1594            if let DefKind::OpaqueTy = def_kind {
1595                self.encode_explicit_item_bounds(def_id);
1596                self.encode_explicit_item_self_bounds(def_id);
1597                {
    {
        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));
1598                self.encode_precise_capturing_args(def_id);
1599                if tcx.is_conditionally_const(def_id) {
1600                    {
    {
        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]
1601                        <- tcx.explicit_implied_const_bounds(def_id).skip_binder());
1602                }
1603                {
    {
        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));
1604            }
1605            if let DefKind::AssocTy = def_kind {
1606                let assoc_item = tcx.associated_item(def_id);
1607                match assoc_item.container {
1608                    ty::AssocContainer::Trait => {
1609                        {
    {
        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));
1610                    }
1611                    ty::AssocContainer::InherentImpl => {
1612                        {
    {
        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));
1613                    }
1614                    ty::AssocContainer::TraitImpl(_) => {}
1615                }
1616            }
1617            if let DefKind::AnonConst = def_kind {
1618                {
    {
        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));
1619            }
1620            if should_encode_const_of_item(self.tcx, def_id, def_kind) {
1621                {
    {
        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));
1622            }
1623            if tcx.impl_method_has_trait_impl_trait_tys(def_id)
1624                && let Ok(table) = self.tcx.collect_return_position_impl_trait_in_trait_tys(def_id)
1625            {
1626                {
    {
        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);
1627            }
1628            if let DefKind::Impl { .. } | DefKind::Trait = def_kind {
1629                let table = tcx.associated_types_for_impl_traits_in_trait_or_impl(def_id);
1630                {
    {
        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);
1631            }
1632        }
1633
1634        for (def_id, impls) in &tcx.crate_inherent_impls(()).0.inherent_impls {
1635            {
    {
        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| {
1636                assert!(def_id.is_local());
1637                def_id.index
1638            }));
1639        }
1640
1641        for (def_id, res_map) in &tcx.resolutions(()).doc_link_resolutions {
1642            {
    {
        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);
1643        }
1644
1645        for (def_id, traits) in &tcx.resolutions(()).doc_link_traits_in_scope {
1646            {
    {
        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);
1647        }
1648    }
1649
1650    fn encode_externally_implementable_items(&mut self) -> LazyArray<EiiMapEncodedKeyValue> {
1651        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
1652        let externally_implementable_items = self.tcx.externally_implementable_items(LOCAL_CRATE);
1653
1654        self.lazy_array(externally_implementable_items.iter().map(
1655            |(foreign_item, (decl, impls))| {
1656                (
1657                    *foreign_item,
1658                    (decl.clone(), impls.iter().map(|(impl_did, i)| (*impl_did, *i)).collect()),
1659                )
1660            },
1661        ))
1662    }
1663
1664    #[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("compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1664u32),
                                    ::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))]
1665    fn encode_info_for_adt(&mut self, local_def_id: LocalDefId) {
1666        let def_id = local_def_id.to_def_id();
1667        let tcx = self.tcx;
1668        let adt_def = tcx.adt_def(def_id);
1669        record!(self.tables.repr_options[def_id] <- adt_def.repr());
1670
1671        let params_in_repr = self.tcx.params_in_repr(def_id);
1672        record!(self.tables.params_in_repr[def_id] <- params_in_repr);
1673
1674        if adt_def.is_enum() {
1675            let module_children = tcx.module_children_local(local_def_id);
1676            record_array!(self.tables.module_children_non_reexports[def_id] <-
1677                module_children.iter().map(|child| child.res.def_id().index));
1678        } else {
1679            // For non-enum, there is only one variant, and its def_id is the adt's.
1680            debug_assert_eq!(adt_def.variants().len(), 1);
1681            debug_assert_eq!(adt_def.non_enum_variant().def_id, def_id);
1682            // Therefore, the loop over variants will encode its fields as the adt's children.
1683        }
1684
1685        for (idx, variant) in adt_def.variants().iter_enumerated() {
1686            let data = VariantData {
1687                discr: variant.discr,
1688                idx,
1689                ctor: variant.ctor.map(|(kind, def_id)| (kind, def_id.index)),
1690                is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1691            };
1692            record!(self.tables.variant_data[variant.def_id] <- data);
1693
1694            record_array!(self.tables.associated_item_or_field_def_ids[variant.def_id] <- variant.fields.iter().map(|f| {
1695                assert!(f.did.is_local());
1696                f.did.index
1697            }));
1698
1699            for field in &variant.fields {
1700                self.tables.safety.set(field.did.index, field.safety);
1701                record!(
1702                    self.tables.mut_restriction[field.did] <- field.mut_restriction
1703                );
1704            }
1705
1706            if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor {
1707                let fn_sig = tcx.fn_sig(ctor_def_id);
1708                // FIXME only encode signature for ctor_def_id
1709                record!(self.tables.fn_sig[variant.def_id] <- fn_sig);
1710            }
1711        }
1712
1713        if let Some(destructor) = tcx.adt_destructor(local_def_id) {
1714            record!(self.tables.adt_destructor[def_id] <- destructor);
1715        }
1716
1717        if let Some(destructor) = tcx.adt_async_destructor(local_def_id) {
1718            record!(self.tables.adt_async_destructor[def_id] <- destructor);
1719        }
1720    }
1721
1722    #[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("compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1722u32),
                                    ::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))]
1723    fn encode_info_for_mod(&mut self, local_def_id: LocalDefId) {
1724        let tcx = self.tcx;
1725        let def_id = local_def_id.to_def_id();
1726
1727        // If we are encoding a proc-macro crates, `encode_info_for_mod` will
1728        // only ever get called for the crate root. We still want to encode
1729        // the crate root for consistency with other crates (some of the resolver
1730        // code uses it). However, we skip encoding anything relating to child
1731        // items - we encode information about proc-macros later on.
1732        if self.is_proc_macro {
1733            // Encode this here because we don't do it in encode_def_ids.
1734            record!(self.tables.expn_that_defined[def_id] <- tcx.expn_that_defined(local_def_id));
1735        } else {
1736            let module_children = tcx.module_children_local(local_def_id);
1737
1738            record_array!(self.tables.module_children_non_reexports[def_id] <-
1739                module_children.iter().filter(|child| child.reexport_chain.is_empty())
1740                    .map(|child| child.res.def_id().index));
1741
1742            record_defaulted_array!(self.tables.module_children_reexports[def_id] <-
1743                module_children.iter().filter(|child| !child.reexport_chain.is_empty()));
1744
1745            let ambig_module_children = tcx
1746                .resolutions(())
1747                .ambig_module_children
1748                .get(&local_def_id)
1749                .map_or_default(|v| &v[..]);
1750            record_defaulted_array!(self.tables.ambig_module_children[def_id] <-
1751                ambig_module_children);
1752        }
1753    }
1754
1755    fn encode_explicit_item_bounds(&mut self, def_id: DefId) {
1756        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/rmeta/encoder.rs:1756",
                        "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/encoder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1756u32),
                        ::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);
1757        let bounds = self.tcx.explicit_item_bounds(def_id).skip_binder();
1758        {
    {
        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);
1759    }
1760
1761    fn encode_explicit_item_self_bounds(&mut self, def_id: DefId) {
1762        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/rmeta/encoder.rs:1762",
                        "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/encoder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1762u32),
                        ::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);
1763        let bounds = self.tcx.explicit_item_self_bounds(def_id).skip_binder();
1764        {
    {
        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);
1765    }
1766
1767    #[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("compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1767u32),
                                    ::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))]
1768    fn encode_info_for_assoc_item(&mut self, def_id: DefId) {
1769        let tcx = self.tcx;
1770        let item = tcx.associated_item(def_id);
1771
1772        if matches!(item.container, AssocContainer::Trait | AssocContainer::TraitImpl(_)) {
1773            self.tables.defaultness.set(def_id.index, item.defaultness(tcx));
1774        }
1775
1776        record!(self.tables.assoc_container[def_id] <- item.container);
1777
1778        if let AssocContainer::Trait = item.container
1779            && item.is_type()
1780        {
1781            self.encode_explicit_item_bounds(def_id);
1782            self.encode_explicit_item_self_bounds(def_id);
1783            if tcx.is_conditionally_const(def_id) {
1784                record_defaulted_array!(self.tables.explicit_implied_const_bounds[def_id]
1785                    <- self.tcx.explicit_implied_const_bounds(def_id).skip_binder());
1786            }
1787        }
1788        if let ty::AssocKind::Type { data: ty::AssocTypeData::Rpitit(rpitit_info) } = item.kind {
1789            record!(self.tables.opt_rpitit_info[def_id] <- rpitit_info);
1790            if matches!(rpitit_info, ty::ImplTraitInTraitData::Trait { .. }) {
1791                record_array!(
1792                    self.tables.assumed_wf_types_for_rpitit[def_id]
1793                        <- self.tcx.assumed_wf_types_for_rpitit(def_id)
1794                );
1795                self.encode_precise_capturing_args(def_id);
1796            }
1797        }
1798    }
1799
1800    fn encode_precise_capturing_args(&mut self, def_id: DefId) {
1801        let Some(precise_capturing_args) = self.tcx.rendered_precise_capturing_args(def_id) else {
1802            return;
1803        };
1804
1805        {
    {
        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);
1806    }
1807
1808    fn encode_mir(&mut self) {
1809        if self.is_proc_macro {
1810            return;
1811        }
1812
1813        let tcx = self.tcx;
1814        let reachable_set = tcx.reachable_set(());
1815
1816        let keys_and_jobs = tcx.mir_keys(()).iter().filter_map(|&def_id| {
1817            let (encode_const, encode_opt) = should_encode_mir(tcx, reachable_set, def_id);
1818            if encode_const || encode_opt { Some((def_id, encode_const, encode_opt)) } else { None }
1819        });
1820        for (def_id, encode_const, encode_opt) in keys_and_jobs {
1821            if true {
    if !(encode_const || encode_opt) {
        ::core::panicking::panic("assertion failed: encode_const || encode_opt")
    };
};debug_assert!(encode_const || encode_opt);
1822
1823            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/rmeta/encoder.rs:1823",
                        "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/encoder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1823u32),
                        ::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);
1824            if encode_opt {
1825                {
    {
        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));
1826                self.tables
1827                    .cross_crate_inlinable
1828                    .set(def_id.to_def_id().index, self.tcx.cross_crate_inlinable(def_id));
1829                {
    {
        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()]
1830                    <- tcx.closure_saved_names_of_captured_variables(def_id));
1831
1832                if self.tcx.is_coroutine(def_id.to_def_id())
1833                    && let Some(witnesses) = tcx.mir_coroutine_witnesses(def_id)
1834                {
1835                    {
    {
        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);
1836                }
1837            }
1838            let mut is_trivial = false;
1839            if encode_const {
1840                if let Some((val, ty)) = tcx.trivial_const(def_id) {
1841                    is_trivial = true;
1842                    {
    {
        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));
1843                } else {
1844                    is_trivial = false;
1845                    {
    {
        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));
1846                }
1847
1848                // FIXME(generic_const_exprs): this feels wrong to have in `encode_mir`
1849                let abstract_const = tcx.thir_abstract_const(def_id);
1850                if let Ok(Some(abstract_const)) = abstract_const {
1851                    {
    {
        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);
1852                }
1853
1854                if should_encode_const(tcx.def_kind(def_id)) {
1855                    let qualifs = tcx.mir_const_qualif(def_id);
1856                    {
    {
        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);
1857                    let body = tcx.hir_maybe_body_owned_by(def_id);
1858                    if let Some(body) = body {
1859                        let const_data = rendered_const(self.tcx, &body, def_id);
1860                        {
    {
        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);
1861                    }
1862                }
1863            }
1864            if !is_trivial {
1865                {
    {
        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));
1866            }
1867
1868            if self.tcx.is_coroutine(def_id.to_def_id())
1869                && let Some(witnesses) = tcx.mir_coroutine_witnesses(def_id)
1870            {
1871                {
    {
        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);
1872            }
1873        }
1874
1875        // Encode all the deduced parameter attributes for everything that has MIR, even for items
1876        // that can't be inlined. But don't if we aren't optimizing in non-incremental mode, to
1877        // save the query traffic.
1878        if tcx.sess.opts.output_types.should_codegen()
1879            && tcx.sess.opts.optimize != OptLevel::No
1880            && tcx.sess.opts.incremental.is_none()
1881        {
1882            for &local_def_id in tcx.mir_keys(()) {
1883                if let DefKind::AssocFn | DefKind::Fn = tcx.def_kind(local_def_id) {
1884                    {
    {
        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()] <-
1885                        self.tcx.deduced_param_attrs(local_def_id.to_def_id()));
1886                }
1887            }
1888        }
1889    }
1890
1891    #[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("compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1891u32),
                                    ::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))]
1892    fn encode_stability(&mut self, def_id: DefId) {
1893        // The query lookup can take a measurable amount of time in crates with many items. Check if
1894        // the stability attributes are even enabled before using their queries.
1895        if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1896            if let Some(stab) = self.tcx.lookup_stability(def_id) {
1897                record!(self.tables.lookup_stability[def_id] <- stab)
1898            }
1899        }
1900    }
1901
1902    #[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("compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1902u32),
                                    ::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))]
1903    fn encode_const_stability(&mut self, def_id: DefId) {
1904        // The query lookup can take a measurable amount of time in crates with many items. Check if
1905        // the stability attributes are even enabled before using their queries.
1906        if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1907            if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1908                record!(self.tables.lookup_const_stability[def_id] <- stab)
1909            }
1910        }
1911    }
1912
1913    #[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("compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1913u32),
                                    ::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))]
1914    fn encode_default_body_stability(&mut self, def_id: DefId) {
1915        // The query lookup can take a measurable amount of time in crates with many items. Check if
1916        // the stability attributes are even enabled before using their queries.
1917        if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1918            if let Some(stab) = self.tcx.lookup_default_body_stability(def_id) {
1919                record!(self.tables.lookup_default_body_stability[def_id] <- stab)
1920            }
1921        }
1922    }
1923
1924    #[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("compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1924u32),
                                    ::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))]
1925    fn encode_deprecation(&mut self, def_id: DefId) {
1926        if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1927            record!(self.tables.lookup_deprecation_entry[def_id] <- depr);
1928        }
1929    }
1930
1931    #[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("compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1931u32),
                                    ::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))]
1932    fn encode_info_for_macro(&mut self, def_id: LocalDefId) {
1933        let tcx = self.tcx;
1934
1935        let (_, macro_def, _) = tcx.hir_expect_item(def_id).expect_macro();
1936        self.tables.is_macro_rules.set(def_id.local_def_index, macro_def.macro_rules);
1937        record!(self.tables.macro_definition[def_id.to_def_id()] <- &*macro_def.body);
1938    }
1939
1940    fn encode_native_libraries(&mut self) -> LazyArray<NativeLib> {
1941        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
1942        let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1943        self.lazy_array(used_libraries.iter())
1944    }
1945
1946    fn encode_foreign_modules(&mut self) -> LazyArray<ForeignModule> {
1947        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
1948        let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1949        self.lazy_array(foreign_modules.iter().map(|(_, m)| m).cloned())
1950    }
1951
1952    fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) {
1953        let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1954        let mut expn_data_table: TableBuilder<_, _> = Default::default();
1955        let mut expn_hash_table: TableBuilder<_, _> = Default::default();
1956
1957        self.hygiene_ctxt.encode(
1958            &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table),
1959            |(this, syntax_contexts, _, _), index, ctxt_data| {
1960                syntax_contexts.set_some(index, this.lazy(ctxt_data));
1961            },
1962            |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| {
1963                if let Some(index) = index.as_local() {
1964                    expn_data_table.set_some(index.as_raw(), this.lazy(expn_data));
1965                    expn_hash_table.set_some(index.as_raw(), this.lazy(hash));
1966                }
1967            },
1968        );
1969
1970        (
1971            syntax_contexts.encode(&mut self.opaque),
1972            expn_data_table.encode(&mut self.opaque),
1973            expn_hash_table.encode(&mut self.opaque),
1974        )
1975    }
1976
1977    fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
1978        let is_proc_macro = self.tcx.crate_types().contains(&CrateType::ProcMacro);
1979        if is_proc_macro {
1980            let tcx = self.tcx;
1981            let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index;
1982            let stability = tcx.lookup_stability(CRATE_DEF_ID);
1983            for (i, span) in self.tcx.sess.proc_macro_quoted_spans() {
1984                let span = self.lazy(span);
1985                self.tables.proc_macro_quoted_spans.set_some(i, span);
1986            }
1987
1988            self.tables.def_kind.set_some(LOCAL_CRATE.as_def_id().index, DefKind::Mod);
1989            {
    {
        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()));
1990            self.encode_attrs(LOCAL_CRATE.as_def_id().expect_local());
1991            let vis = tcx
1992                .local_visibility(CRATE_DEF_ID)
1993                .map_id(|mod_id| mod_id.to_local_def_id().local_def_index);
1994            {
    {
        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);
1995            if let Some(stability) = stability {
1996                {
    {
        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);
1997            }
1998            self.encode_deprecation(LOCAL_CRATE.as_def_id());
1999            if let Some(res_map) = tcx.resolutions(()).doc_link_resolutions.get(&CRATE_MOD_ID) {
2000                {
    {
        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);
2001            }
2002            if let Some(traits) = tcx.resolutions(()).doc_link_traits_in_scope.get(&CRATE_MOD_ID) {
2003                {
    {
        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);
2004            }
2005
2006            let mut macros = ::alloc::vec::Vec::new()vec![];
2007
2008            // Normally, this information is encoded when we walk the items
2009            // defined in this crate. However, we skip doing that for proc-macro crates,
2010            // so we manually encode just the information that we need
2011            for &proc_macro in &tcx.resolutions(()).proc_macros {
2012                let id = proc_macro;
2013                let proc_macro = tcx.local_def_id_to_hir_id(proc_macro);
2014                let mut name = tcx.hir_name(proc_macro);
2015                let span = tcx.hir_span(proc_macro);
2016                // Proc-macros may have attributes like `#[allow_internal_unstable]`,
2017                // so downstream crates need access to them.
2018                let attrs = tcx.hir_attrs(proc_macro);
2019                let (macro_kind, kind) = if {
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use ::rustc_hir::attrs::AttributeKind::*;
                    let i: &::rustc_hir::Attribute = i;
                    match i {
                        ::rustc_hir::Attribute::Parsed(ProcMacro) => {
                            break 'done Some(());
                        }
                        ::rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, ProcMacro) {
2020                    (MacroKind::Bang, ProcMacroKind::Bang { name: name.as_str().to_owned() })
2021                } else if {
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use ::rustc_hir::attrs::AttributeKind::*;
                    let i: &::rustc_hir::Attribute = i;
                    match i {
                        ::rustc_hir::Attribute::Parsed(ProcMacroAttribute) => {
                            break 'done Some(());
                        }
                        ::rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, ProcMacroAttribute) {
2022                    (MacroKind::Attr, ProcMacroKind::Attr { name: name.as_str().to_owned() })
2023                } else if let Some((trait_name, helper_attrs)) = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use ::rustc_hir::attrs::AttributeKind::*;
            let i: &::rustc_hir::Attribute = i;
            match i {
                ::rustc_hir::Attribute::Parsed(ProcMacroDerive {
                    trait_name, helper_attrs }) => {
                    break 'done Some((trait_name, helper_attrs));
                }
                ::rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs,
2024                    ProcMacroDerive { trait_name, helper_attrs } => (trait_name, helper_attrs))
2025                {
2026                    name = *trait_name;
2027                    (
2028                        MacroKind::Derive,
2029                        ProcMacroKind::CustomDerive {
2030                            trait_name: name.as_str().to_owned(),
2031                            attributes: helper_attrs
2032                                .iter()
2033                                .map(|attr| attr.as_str().to_owned())
2034                                .collect(),
2035                        },
2036                    )
2037                } else {
2038                    ::rustc_middle::util::bug::bug_fmt(format_args!("Unknown proc-macro type for item {0:?}",
        id));bug!("Unknown proc-macro type for item {:?}", id);
2039                };
2040
2041                macros.push((id.local_def_index, self.lazy(kind)));
2042
2043                let mut def_key = self.tcx.hir_def_key(id);
2044                def_key.disambiguated_data.data = DefPathData::MacroNs(name);
2045
2046                let def_id = id.to_def_id();
2047                self.tables.def_kind.set_some(def_id.index, DefKind::Macro(macro_kind.into()));
2048                self.encode_attrs(id);
2049                {
    {
        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);
2050                {
    {
        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);
2051                {
    {
        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);
2052                {
    {
        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);
2053                if let Some(stability) = stability {
2054                    {
    {
        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);
2055                }
2056            }
2057
2058            let macros = self.lazy_array(macros);
2059
2060            Some(ProcMacroData { proc_macro_decls_static, stability, macros })
2061        } else {
2062            None
2063        }
2064    }
2065
2066    fn encode_debugger_visualizers(&mut self) -> LazyArray<DebuggerVisualizerFile> {
2067        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2068        self.lazy_array(
2069            self.tcx
2070                .debugger_visualizers(LOCAL_CRATE)
2071                .iter()
2072                // Erase the path since it may contain privacy sensitive data
2073                // that we don't want to end up in crate metadata.
2074                // The path is only needed for the local crate because of
2075                // `--emit dep-info`.
2076                .map(DebuggerVisualizerFile::path_erased),
2077        )
2078    }
2079
2080    fn encode_crate_deps(&mut self) -> LazyArray<CrateDep> {
2081        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2082
2083        let deps = self
2084            .tcx
2085            .crates(())
2086            .iter()
2087            .map(|&cnum| {
2088                let dep = CrateDep {
2089                    name: self.tcx.crate_name(cnum),
2090                    hash: self.tcx.crate_hash(cnum),
2091                    host_hash: self.tcx.crate_host_hash(cnum),
2092                    kind: self.tcx.crate_dep_kind(cnum),
2093                    extra_filename: self.tcx.extra_filename(cnum).clone(),
2094                    is_private: self.tcx.is_private_dep(cnum),
2095                };
2096                (cnum, dep)
2097            })
2098            .collect::<Vec<_>>();
2099
2100        {
2101            // Sanity-check the crate numbers
2102            let mut expected_cnum = 1;
2103            for &(n, _) in &deps {
2104                {
    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));
2105                expected_cnum += 1;
2106            }
2107        }
2108
2109        // We're just going to write a list of crate 'name-hash-version's, with
2110        // the assumption that they are numbered 1 to n.
2111        // FIXME (#2166): This is not nearly enough to support correct versioning
2112        // but is enough to get transitive crate dependencies working.
2113        self.lazy_array(deps.iter().map(|(_, dep)| dep))
2114    }
2115
2116    fn encode_target_modifiers(&mut self) -> LazyArray<TargetModifier> {
2117        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2118        let tcx = self.tcx;
2119        self.lazy_array(tcx.sess.opts.gather_target_modifiers())
2120    }
2121
2122    fn encode_enabled_denied_partial_mitigations(&mut self) -> LazyArray<DeniedPartialMitigation> {
2123        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2124        let tcx = self.tcx;
2125        self.lazy_array(tcx.sess.gather_enabled_denied_partial_mitigations())
2126    }
2127
2128    fn encode_lib_features(&mut self) -> LazyArray<(Symbol, FeatureStability)> {
2129        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2130        let tcx = self.tcx;
2131        let lib_features = tcx.lib_features(LOCAL_CRATE);
2132        self.lazy_array(lib_features.to_sorted_vec())
2133    }
2134
2135    fn encode_stability_implications(&mut self) -> LazyArray<(Symbol, Symbol)> {
2136        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2137        let tcx = self.tcx;
2138        let implications = tcx.stability_implications(LOCAL_CRATE);
2139        let sorted = implications.to_sorted_stable_ord();
2140        self.lazy_array(sorted.into_iter().map(|(k, v)| (*k, *v)))
2141    }
2142
2143    fn encode_canonical_symbols(&mut self) -> LazyArray<(Symbol, DefIndex)> {
2144        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2145        let tcx = self.tcx;
2146        let canonical_symbols = &tcx.canonical_symbols(LOCAL_CRATE);
2147        self.lazy_array(canonical_symbols.iter().map(|cs| (cs.symbol, cs.def_id.index)))
2148    }
2149
2150    fn encode_diagnostic_items(&mut self) -> LazyArray<(Symbol, DefIndex)> {
2151        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2152        let tcx = self.tcx;
2153        let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id;
2154        self.lazy_array(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
2155    }
2156
2157    fn encode_lang_items(&mut self) -> LazyArray<(DefIndex, LangItem)> {
2158        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2159        let lang_items = self.tcx.lang_items().iter();
2160        self.lazy_array(lang_items.filter_map(|(lang_item, def_id)| {
2161            def_id.as_local().map(|id| (id.local_def_index, lang_item))
2162        }))
2163    }
2164
2165    fn encode_lang_items_missing(&mut self) -> LazyArray<LangItem> {
2166        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2167        let tcx = self.tcx;
2168        self.lazy_array(&tcx.lang_items().missing)
2169    }
2170
2171    fn encode_stripped_cfg_items(&mut self) -> LazyArray<StrippedCfgItem<DefIndex>> {
2172        self.lazy_array(
2173            self.tcx
2174                .stripped_cfg_items(LOCAL_CRATE)
2175                .into_iter()
2176                .map(|item| item.clone().map_scope_id(|def_id| def_id.index)),
2177        )
2178    }
2179
2180    fn encode_traits(&mut self) -> LazyArray<DefIndex> {
2181        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2182        self.lazy_array(self.tcx.traits(LOCAL_CRATE).iter().map(|def_id| def_id.index))
2183    }
2184
2185    /// Encodes an index, mapping each trait to its (local) implementations.
2186    #[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("compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2186u32),
                                    ::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))]
2187    fn encode_impls(&mut self) -> LazyArray<TraitImpls> {
2188        empty_proc_macro!(self);
2189        let tcx = self.tcx;
2190        let mut trait_impls: FxIndexMap<DefId, Vec<(DefIndex, Option<SimplifiedType>)>> =
2191            FxIndexMap::default();
2192
2193        for id in tcx.hir_free_items() {
2194            let DefKind::Impl { of_trait } = tcx.def_kind(id.owner_id) else {
2195                continue;
2196            };
2197            let def_id = id.owner_id.to_def_id();
2198
2199            if of_trait {
2200                let header = tcx.impl_trait_header(def_id);
2201                record!(self.tables.impl_trait_header[def_id] <- header);
2202
2203                let impl_is_fully_generic_for_reflection =
2204                    tcx.impl_is_fully_generic_for_reflection(def_id);
2205                self.tables
2206                    .impl_is_fully_generic_for_reflection
2207                    .set(def_id.index, impl_is_fully_generic_for_reflection);
2208
2209                self.tables.defaultness.set(def_id.index, tcx.defaultness(def_id));
2210
2211                let trait_ref = header.trait_ref.instantiate_identity().skip_norm_wip();
2212                let simplified_self_ty = fast_reject::simplify_type(
2213                    self.tcx,
2214                    trait_ref.self_ty(),
2215                    TreatParams::InstantiateWithInfer,
2216                );
2217                trait_impls
2218                    .entry(trait_ref.def_id)
2219                    .or_default()
2220                    .push((id.owner_id.def_id.local_def_index, simplified_self_ty));
2221
2222                let trait_def = tcx.trait_def(trait_ref.def_id);
2223                if let Ok(mut an) = trait_def.ancestors(tcx, def_id)
2224                    && let Some(specialization_graph::Node::Impl(parent)) = an.nth(1)
2225                {
2226                    self.tables.impl_parent.set_some(def_id.index, parent.into());
2227                }
2228
2229                // if this is an impl of `CoerceUnsized`, create its
2230                // "unsized info", else just store None
2231                if tcx.is_lang_item(trait_ref.def_id, LangItem::CoerceUnsized) {
2232                    let coerce_unsized_info = tcx.coerce_unsized_info(def_id).unwrap();
2233                    record!(self.tables.coerce_unsized_info[def_id] <- coerce_unsized_info);
2234                }
2235            }
2236        }
2237
2238        let trait_impls: Vec<_> = trait_impls
2239            .into_iter()
2240            .map(|(trait_def_id, impls)| TraitImpls {
2241                trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
2242                impls: self.lazy_array(&impls),
2243            })
2244            .collect();
2245
2246        self.lazy_array(&trait_impls)
2247    }
2248
2249    #[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("compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2249u32),
                                    ::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))]
2250    fn encode_incoherent_impls(&mut self) -> LazyArray<IncoherentImpls> {
2251        empty_proc_macro!(self);
2252        let tcx = self.tcx;
2253
2254        let all_impls: Vec<_> = tcx
2255            .crate_inherent_impls(())
2256            .0
2257            .incoherent_impls
2258            .iter()
2259            .map(|(&simp, impls)| IncoherentImpls {
2260                self_ty: self.lazy(simp),
2261                impls: self.lazy_array(impls.iter().map(|def_id| def_id.local_def_index)),
2262            })
2263            .collect();
2264
2265        self.lazy_array(&all_impls)
2266    }
2267
2268    fn encode_exportable_items(&mut self) -> LazyArray<DefIndex> {
2269        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2270        self.lazy_array(self.tcx.exportable_items(LOCAL_CRATE).iter().map(|def_id| def_id.index))
2271    }
2272
2273    fn encode_stable_order_of_exportable_impls(&mut self) -> LazyArray<(DefIndex, usize)> {
2274        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2275        let stable_order_of_exportable_impls =
2276            self.tcx.stable_order_of_exportable_impls(LOCAL_CRATE);
2277        self.lazy_array(
2278            stable_order_of_exportable_impls.iter().map(|(def_id, idx)| (def_id.index, *idx)),
2279        )
2280    }
2281
2282    // Encodes all symbols exported from this crate into the metadata.
2283    //
2284    // This pass is seeded off the reachability list calculated in the
2285    // middle::reachable module but filters out items that either don't have a
2286    // symbol associated with them (they weren't translated) or if they're an FFI
2287    // definition (as that's not defined in this crate).
2288    fn encode_exported_symbols(
2289        &mut self,
2290        exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportInfo)],
2291    ) -> LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)> {
2292        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2293
2294        self.lazy_array(exported_symbols.iter().cloned())
2295    }
2296
2297    fn encode_dylib_dependency_formats(&mut self) -> LazyArray<Option<LinkagePreference>> {
2298        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2299        let formats = self.tcx.dependency_formats(());
2300        if let Some(arr) = formats.get(&CrateType::Dylib) {
2301            return self.lazy_array(arr.iter().skip(1 /* skip LOCAL_CRATE */).map(
2302                |slot| match *slot {
2303                    Linkage::NotLinked | Linkage::IncludedFromDylib => None,
2304
2305                    Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
2306                    Linkage::Static => Some(LinkagePreference::RequireStatic),
2307                },
2308            ));
2309        }
2310        LazyArray::default()
2311    }
2312}
2313
2314/// Used to prefetch queries which will be needed later by metadata encoding.
2315/// Only a subset of the queries are actually prefetched to keep this code smaller.
2316fn prefetch_mir(tcx: TyCtxt<'_>) {
2317    if !tcx.sess.opts.output_types.should_codegen() {
2318        // We won't emit MIR, so don't prefetch it.
2319        return;
2320    }
2321
2322    let reachable_set = tcx.reachable_set(());
2323    par_for_each_in(tcx.mir_keys(()), |&&def_id| {
2324        if tcx.is_trivial_const(def_id) {
2325            return;
2326        }
2327        let (encode_const, encode_opt) = should_encode_mir(tcx, reachable_set, def_id);
2328
2329        if encode_const {
2330            tcx.ensure_done().mir_for_ctfe(def_id);
2331        }
2332        if encode_opt {
2333            tcx.ensure_done().optimized_mir(def_id);
2334        }
2335        if encode_opt || encode_const {
2336            tcx.ensure_done().promoted_mir(def_id);
2337        }
2338    })
2339}
2340
2341// NOTE(eddyb) The following comment was preserved for posterity, even
2342// though it's no longer relevant as EBML (which uses nested & tagged
2343// "documents") was replaced with a scheme that can't go out of bounds.
2344//
2345// And here we run into yet another obscure archive bug: in which metadata
2346// loaded from archives may have trailing garbage bytes. Awhile back one of
2347// our tests was failing sporadically on the macOS 64-bit builders (both nopt
2348// and opt) by having ebml generate an out-of-bounds panic when looking at
2349// metadata.
2350//
2351// Upon investigation it turned out that the metadata file inside of an rlib
2352// (and ar archive) was being corrupted. Some compilations would generate a
2353// metadata file which would end in a few extra bytes, while other
2354// compilations would not have these extra bytes appended to the end. These
2355// extra bytes were interpreted by ebml as an extra tag, so they ended up
2356// being interpreted causing the out-of-bounds.
2357//
2358// The root cause of why these extra bytes were appearing was never
2359// discovered, and in the meantime the solution we're employing is to insert
2360// the length of the metadata to the start of the metadata. Later on this
2361// will allow us to slice the metadata to the precise length that we just
2362// generated regardless of trailing bytes that end up in it.
2363
2364pub struct EncodedMetadata {
2365    // The declaration order matters because `full_metadata` should be dropped
2366    // before `_temp_dir`.
2367    full_metadata: Option<Mmap>,
2368    // This is an optional stub metadata containing only the crate header.
2369    // The header should be very small, so we load it directly into memory.
2370    stub_metadata: Option<Vec<u8>>,
2371    // The path containing the metadata, to record as work product.
2372    path: Option<Box<Path>>,
2373    // We need to carry MaybeTempDir to avoid deleting the temporary
2374    // directory while accessing the Mmap.
2375    _temp_dir: Option<MaybeTempDir>,
2376}
2377
2378impl EncodedMetadata {
2379    #[inline]
2380    pub fn from_path(
2381        path: PathBuf,
2382        stub_path: Option<PathBuf>,
2383        temp_dir: Option<MaybeTempDir>,
2384    ) -> std::io::Result<Self> {
2385        let file = std::fs::File::open(&path)?;
2386        let file_metadata = file.metadata()?;
2387        if file_metadata.len() == 0 {
2388            return Ok(Self {
2389                full_metadata: None,
2390                stub_metadata: None,
2391                path: None,
2392                _temp_dir: None,
2393            });
2394        }
2395        let full_mmap = unsafe { Some(Mmap::map(file)?) };
2396
2397        let stub =
2398            if let Some(stub_path) = stub_path { Some(std::fs::read(stub_path)?) } else { None };
2399
2400        Ok(Self {
2401            full_metadata: full_mmap,
2402            stub_metadata: stub,
2403            path: Some(path.into()),
2404            _temp_dir: temp_dir,
2405        })
2406    }
2407
2408    #[inline]
2409    pub fn full(&self) -> &[u8] {
2410        &self.full_metadata.as_deref().unwrap_or_default()
2411    }
2412
2413    #[inline]
2414    pub fn stub_or_full(&self) -> &[u8] {
2415        self.stub_metadata.as_deref().unwrap_or(self.full())
2416    }
2417
2418    #[inline]
2419    pub fn path(&self) -> Option<&Path> {
2420        self.path.as_deref()
2421    }
2422}
2423
2424impl<S: Encoder> Encodable<S> for EncodedMetadata {
2425    fn encode(&self, s: &mut S) {
2426        self.stub_metadata.encode(s);
2427
2428        let slice = self.full();
2429        slice.encode(s)
2430    }
2431}
2432
2433impl<D: Decoder> Decodable<D> for EncodedMetadata {
2434    fn decode(d: &mut D) -> Self {
2435        let stub = <Option<Vec<u8>>>::decode(d);
2436
2437        let len = d.read_usize();
2438        let full_metadata = if len > 0 {
2439            let mut mmap = MmapMut::map_anon(len).unwrap();
2440            mmap.copy_from_slice(d.read_raw_bytes(len));
2441            Some(mmap.make_read_only().unwrap())
2442        } else {
2443            None
2444        };
2445
2446        Self { full_metadata, stub_metadata: stub, path: None, _temp_dir: None }
2447    }
2448}
2449
2450#[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("compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2450u32),
                                    ::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.sess.incr_comp_session_dir();
                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 compiler/rustc_metadata/src/rmeta/encoder.rs:2485",
                                        "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                        ::tracing_core::__macro_support::Option::Some(2485u32),
                                        ::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))]
2451pub fn encode_metadata(tcx: TyCtxt<'_>, path: &Path, ref_path: Option<&Path>) {
2452    // Since encoding metadata is not in a query, and nothing is cached,
2453    // there's no need to do dep-graph tracking for any of it.
2454    tcx.dep_graph.assert_ignored();
2455
2456    // Generate the metadata stub manually, as that is a small file compared to full metadata.
2457    if let Some(ref_path) = ref_path {
2458        let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata_stub");
2459
2460        with_encode_metadata_header(tcx, ref_path, |ecx| {
2461            let header: LazyValue<CrateHeader> = ecx.lazy(CrateHeader {
2462                name: tcx.crate_name(LOCAL_CRATE),
2463                triple: tcx.sess.opts.target_triple.clone(),
2464                hash: tcx.crate_hash(LOCAL_CRATE),
2465                is_proc_macro_crate: false,
2466                is_stub: true,
2467            });
2468            header.position.get()
2469        })
2470    }
2471
2472    let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata");
2473
2474    let dep_node = tcx.metadata_dep_node();
2475
2476    // If the metadata dep-node is green, try to reuse the saved work product.
2477    if tcx.dep_graph.is_fully_enabled()
2478        && let work_product_id = WorkProductId::from_cgu_name("metadata")
2479        && let Some(work_product) = tcx.dep_graph.previous_work_product(&work_product_id)
2480        && tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some()
2481    {
2482        let saved_path = &work_product.saved_files["rmeta"];
2483        let incr_comp_session_dir = tcx.sess.incr_comp_session_dir();
2484        let source_file_in_incr_dir = &incr_comp_session_dir.join(saved_path);
2485        debug!("copying preexisting metadata from {source_file_in_incr_dir:?} to {path:?}");
2486        match rustc_fs_util::link_or_copy(&source_file_in_incr_dir, path) {
2487            Ok(_) => {}
2488            Err(err) => tcx.dcx().emit_fatal(FailCreateFileEncoder { err }),
2489        };
2490        return;
2491    };
2492
2493    if tcx.sess.opts.jobs.frontend.is_some() {
2494        // Prefetch some queries used by metadata encoding.
2495        // This is not necessary for correctness, but is only done for performance reasons.
2496        // It can be removed if it turns out to cause trouble or be detrimental to performance.
2497        par_join(
2498            || prefetch_mir(tcx),
2499            || {
2500                let _ = tcx.exported_non_generic_symbols(LOCAL_CRATE);
2501                let _ = tcx.exported_generic_symbols(LOCAL_CRATE);
2502            },
2503        );
2504    }
2505
2506    // Perform metadata encoding inside a task, so the dep-graph can check if any encoded
2507    // information changes, and maybe reuse the work product.
2508    tcx.dep_graph.with_task(
2509        dep_node,
2510        tcx,
2511        || {
2512            with_encode_metadata_header(tcx, path, |ecx| {
2513                // Encode all the entries and extra information in the crate,
2514                // culminating in the `CrateRoot` which points to all of it.
2515                let root = ecx.encode_crate_root();
2516
2517                // Flush buffer to ensure backing file has the correct size.
2518                ecx.opaque.flush();
2519                // Record metadata size for self-profiling
2520                tcx.prof.artifact_size(
2521                    "crate_metadata",
2522                    "crate_metadata",
2523                    ecx.opaque.file().metadata().unwrap().len(),
2524                );
2525
2526                root.position.get()
2527            })
2528        },
2529        None,
2530    );
2531}
2532
2533fn with_encode_metadata_header(
2534    tcx: TyCtxt<'_>,
2535    path: &Path,
2536    f: impl FnOnce(&mut EncodeContext<'_, '_>) -> usize,
2537) {
2538    let mut encoder = opaque::FileEncoder::new(path)
2539        .unwrap_or_else(|err| tcx.dcx().emit_fatal(FailCreateFileEncoder { err }));
2540    encoder.emit_raw_bytes(METADATA_HEADER);
2541
2542    // Will be filled with the root position after encoding everything.
2543    encoder.emit_raw_bytes(&0u64.to_le_bytes());
2544
2545    let source_map_files = tcx.sess.source_map().files();
2546    let source_file_cache = (Arc::clone(&source_map_files[0]), 0);
2547    let required_source_files = Some(FxIndexSet::default());
2548    drop(source_map_files);
2549
2550    let hygiene_ctxt = HygieneEncodeContext::default();
2551
2552    let mut ecx = EncodeContext {
2553        opaque: encoder,
2554        tcx,
2555        feat: tcx.features(),
2556        tables: Default::default(),
2557        lazy_state: LazyState::NoNode,
2558        span_shorthands: Default::default(),
2559        type_shorthands: Default::default(),
2560        predicate_shorthands: Default::default(),
2561        source_file_cache,
2562        interpret_allocs: Default::default(),
2563        required_source_files,
2564        is_proc_macro: tcx.crate_types().contains(&CrateType::ProcMacro),
2565        hygiene_ctxt: &hygiene_ctxt,
2566        symbol_index_table: Default::default(),
2567    };
2568
2569    // Encode the rustc version string in a predictable location.
2570    rustc_version(tcx.sess.cfg_version).encode(&mut ecx);
2571
2572    let root_position = f(&mut ecx);
2573
2574    // Make sure we report any errors from writing to the file.
2575    // If we forget this, compilation can succeed with an incomplete rmeta file,
2576    // causing an ICE when the rmeta file is read by another compilation.
2577    if let Err((path, err)) = ecx.opaque.finish() {
2578        tcx.dcx().emit_fatal(FailWriteFile { path: &path, err });
2579    }
2580
2581    let file = ecx.opaque.file();
2582    if let Err(err) = encode_root_position(file, root_position) {
2583        tcx.dcx().emit_fatal(FailWriteFile { path: ecx.opaque.path(), err });
2584    }
2585}
2586
2587fn encode_root_position(mut file: &File, pos: usize) -> Result<(), std::io::Error> {
2588    // We will return to this position after writing the root position.
2589    let pos_before_seek = file.stream_position().unwrap();
2590
2591    // Encode the root position.
2592    let header = METADATA_HEADER.len();
2593    file.seek(std::io::SeekFrom::Start(header as u64))?;
2594    file.write_all(&pos.to_le_bytes())?;
2595
2596    // Return to the position where we are before writing the root position.
2597    file.seek(std::io::SeekFrom::Start(pos_before_seek))?;
2598    Ok(())
2599}
2600
2601pub(crate) fn provide(providers: &mut Providers) {
2602    *providers = Providers {
2603        doc_link_resolutions: |tcx, def_id| {
2604            tcx.resolutions(())
2605                .doc_link_resolutions
2606                .get(&def_id)
2607                .unwrap_or_else(|| ::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(def_id),
    format_args!("no resolutions for a doc link"))span_bug!(tcx.def_span(def_id), "no resolutions for a doc link"))
2608        },
2609        doc_link_traits_in_scope: |tcx, def_id| {
2610            tcx.resolutions(()).doc_link_traits_in_scope.get(&def_id).unwrap_or_else(|| {
2611                ::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(def_id),
    format_args!("no traits in scope for a doc link"))span_bug!(tcx.def_span(def_id), "no traits in scope for a doc link")
2612            })
2613        },
2614
2615        ..*providers
2616    }
2617}
2618
2619/// Build a textual representation of an unevaluated constant expression.
2620///
2621/// If the const expression is too complex, an underscore `_` is returned.
2622/// For const arguments, it's `{ _ }` to be precise.
2623/// This means that the output is not necessarily valid Rust code.
2624///
2625/// Currently, only
2626///
2627/// * literals (optionally with a leading `-`)
2628/// * unit `()`
2629/// * blocks (`{ … }`) around simple expressions and
2630/// * paths without arguments
2631///
2632/// are considered simple enough. Simple blocks are included since they are
2633/// necessary to disambiguate unit from the unit type.
2634/// This list might get extended in the future.
2635///
2636/// Without this censoring, in a lot of cases the output would get too large
2637/// and verbose. Consider `match` expressions, blocks and deeply nested ADTs.
2638/// Further, private and `doc(hidden)` fields of structs would get leaked
2639/// since HIR datatypes like the `body` parameter do not contain enough
2640/// semantic information for this function to be able to hide them –
2641/// at least not without significant performance overhead.
2642///
2643/// Whenever possible, prefer to evaluate the constant first and try to
2644/// use a different method for pretty-printing. Ideally this function
2645/// should only ever be used as a fallback.
2646pub fn rendered_const<'tcx>(tcx: TyCtxt<'tcx>, body: &hir::Body<'_>, def_id: LocalDefId) -> String {
2647    let value = body.value;
2648
2649    #[derive(#[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 {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq)]
2650    enum Classification {
2651        Literal,
2652        Simple,
2653        Complex,
2654    }
2655
2656    use Classification::*;
2657
2658    fn classify(expr: &hir::Expr<'_>) -> Classification {
2659        match &expr.kind {
2660            hir::ExprKind::Unary(hir::UnOp::Neg, expr) => {
2661                if #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
    hir::ExprKind::Lit(_) => true,
    _ => false,
}matches!(expr.kind, hir::ExprKind::Lit(_)) { Literal } else { Complex }
2662            }
2663            hir::ExprKind::Lit(_) => Literal,
2664            hir::ExprKind::Tup([]) => Simple,
2665            hir::ExprKind::Block(hir::Block { stmts: [], expr: Some(expr), .. }, _) => {
2666                if classify(expr) == Complex { Complex } else { Simple }
2667            }
2668            // Paths with a self-type or arguments are too “complex” following our measure since
2669            // they may leak private fields of structs (with feature `adt_const_params`).
2670            // Consider: `<Self as Trait<{ Struct { private: () } }>>::CONSTANT`.
2671            // Paths without arguments are definitely harmless though.
2672            hir::ExprKind::Path(hir::QPath::Resolved(_, hir::Path { segments, .. })) => {
2673                if segments.iter().all(|segment| segment.args.is_none()) { Simple } else { Complex }
2674            }
2675            // FIXME: Claiming that those kinds of QPaths are simple is probably not true if the Ty
2676            //        contains const arguments. Is there a *concise* way to check for this?
2677            hir::ExprKind::Path(hir::QPath::TypeRelative(..)) => Simple,
2678            _ => Complex,
2679        }
2680    }
2681
2682    match classify(value) {
2683        // For non-macro literals, we avoid invoking the pretty-printer and use the source snippet
2684        // instead to preserve certain stylistic choices the user likely made for the sake of
2685        // legibility, like:
2686        //
2687        // * hexadecimal notation
2688        // * underscores
2689        // * character escapes
2690        //
2691        // FIXME: This passes through `-/*spacer*/0` verbatim.
2692        Literal
2693            if !value.span.from_expansion()
2694                && let Ok(snippet) = tcx.sess.source_map().span_to_snippet(value.span) =>
2695        {
2696            snippet
2697        }
2698
2699        // Otherwise we prefer pretty-printing to get rid of extraneous whitespace, comments and
2700        // other formatting artifacts.
2701        Literal | Simple => id_to_string(&tcx, body.id().hir_id),
2702
2703        // FIXME: Omit the curly braces if the enclosing expression is an array literal
2704        //        with a repeated element (an `ExprKind::Repeat`) as in such case it
2705        //        would not actually need any disambiguation.
2706        Complex => {
2707            if tcx.def_kind(def_id) == DefKind::AnonConst {
2708                "{ _ }".to_owned()
2709            } else {
2710                "_".to_owned()
2711            }
2712        }
2713    }
2714}