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_attr_ir::AttributeKind::*;
                                                let i: &::rustc_attr_ir::Attribute = i;
                                                match i {
                                                    ::rustc_attr_ir::Attribute::Parsed(DefaultLibAllocator) => {
                                                        break 'done Some(());
                                                    }
                                                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }.is_some()
                            },
                            externally_implementable_items,
                            proc_macro_data,
                            debugger_visualizers,
                            compiler_builtins: {
                                {
                                        'done:
                                            {
                                            for i in attrs {
                                                #[allow(unused_imports)]
                                                use ::rustc_attr_ir::AttributeKind::*;
                                                let i: &::rustc_attr_ir::Attribute = i;
                                                match i {
                                                    ::rustc_attr_ir::Attribute::Parsed(CompilerBuiltins) => {
                                                        break 'done Some(());
                                                    }
                                                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }.is_some()
                            },
                            needs_allocator: {
                                {
                                        'done:
                                            {
                                            for i in attrs {
                                                #[allow(unused_imports)]
                                                use ::rustc_attr_ir::AttributeKind::*;
                                                let i: &::rustc_attr_ir::Attribute = i;
                                                match i {
                                                    ::rustc_attr_ir::Attribute::Parsed(NeedsAllocator) => {
                                                        break 'done Some(());
                                                    }
                                                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }.is_some()
                            },
                            needs_panic_runtime: {
                                {
                                        'done:
                                            {
                                            for i in attrs {
                                                #[allow(unused_imports)]
                                                use ::rustc_attr_ir::AttributeKind::*;
                                                let i: &::rustc_attr_ir::Attribute = i;
                                                match i {
                                                    ::rustc_attr_ir::Attribute::Parsed(NeedsPanicRuntime) => {
                                                        break 'done Some(());
                                                    }
                                                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }.is_some()
                            },
                            no_builtins: {
                                {
                                        'done:
                                            {
                                            for i in attrs {
                                                #[allow(unused_imports)]
                                                use ::rustc_attr_ir::AttributeKind::*;
                                                let i: &::rustc_attr_ir::Attribute = i;
                                                match i {
                                                    ::rustc_attr_ir::Attribute::Parsed(NoBuiltins) => {
                                                        break 'done Some(());
                                                    }
                                                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }.is_some()
                            },
                            panic_runtime: {
                                {
                                        'done:
                                            {
                                            for i in attrs {
                                                #[allow(unused_imports)]
                                                use ::rustc_attr_ir::AttributeKind::*;
                                                let i: &::rustc_attr_ir::Attribute = i;
                                                match i {
                                                    ::rustc_attr_ir::Attribute::Parsed(PanicRuntime) => {
                                                        break 'done Some(());
                                                    }
                                                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }.is_some()
                            },
                            profiler_runtime: {
                                {
                                        'done:
                                            {
                                            for i in attrs {
                                                #[allow(unused_imports)]
                                                use ::rustc_attr_ir::AttributeKind::*;
                                                let i: &::rustc_attr_ir::Attribute = i;
                                                match i {
                                                    ::rustc_attr_ir::Attribute::Parsed(ProfilerRuntime) => {
                                                        break 'done Some(());
                                                    }
                                                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }.is_some()
                            },
                            symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(),
                            crate_deps,
                            dylib_dependency_formats,
                            lib_features,
                            stability_implications,
                            lang_items,
                            diagnostic_items,
                            canonical_symbols,
                            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(_) |
        hir::Node::Infer(hir::InferArg { kind: hir::InferArgKind::Const, .. })
        => true,
    _ => false,
}matches!(
1432                    tcx.hir_node_by_def_id(local_id),
1433                    hir::Node::ConstArg(_)
1434                        | hir::Node::Infer(hir::InferArg { kind: hir::InferArgKind::Const, .. })
1435                )
1436            {
1437                continue;
1438            }
1439
1440            if def_kind == DefKind::Field
1441                && let hir::Node::Field(field) = tcx.hir_node_by_def_id(local_id)
1442                && let Some(anon) = field.default
1443            {
1444                {
    {
        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());
1445            }
1446
1447            if should_encode_span(def_kind) {
1448                let def_span = tcx.def_span(local_id);
1449                {
    {
        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);
1450            }
1451            if should_encode_attrs(def_kind) {
1452                self.encode_attrs(local_id);
1453            }
1454            if should_encode_expn_that_defined(def_kind) {
1455                {
    {
        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));
1456            }
1457            if should_encode_span(def_kind)
1458                && let Some(ident_span) = tcx.def_ident_span(def_id)
1459            {
1460                {
    {
        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);
1461            }
1462            if def_kind.has_codegen_attrs() {
1463                {
    {
        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));
1464            }
1465            if should_encode_visibility(def_kind) {
1466                let vis = self
1467                    .tcx
1468                    .local_visibility(local_id)
1469                    .map_id(|mod_id| mod_id.to_local_def_id().local_def_index);
1470                {
    {
        let value = vis;
        let lazy = self.lazy(value);
        self.tables.visibility.set_some(def_id.index, lazy);
    }
};record!(self.tables.visibility[def_id] <- vis);
1471            }
1472            if should_encode_stability(def_kind) {
1473                self.encode_stability(def_id);
1474                self.encode_const_stability(def_id);
1475                self.encode_default_body_stability(def_id);
1476                self.encode_deprecation(def_id);
1477            }
1478            if should_encode_variances(tcx, def_id, def_kind) {
1479                let v = self.tcx.variances_of(def_id);
1480                {
    {
        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);
1481            }
1482            if should_encode_fn_sig(def_kind) {
1483                {
    {
        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));
1484            }
1485            if should_encode_generics(def_kind) {
1486                let g = tcx.generics_of(def_id);
1487                {
    {
        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);
1488                {
    {
        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));
1489                let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
1490                {
    {
        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);
1491
1492                for param in &g.own_params {
1493                    if let ty::GenericParamDefKind::Const { has_default: true, .. } = param.kind {
1494                        let default = self.tcx.const_param_default(param.def_id);
1495                        {
    {
        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);
1496                    }
1497                }
1498            }
1499            if tcx.is_conditionally_const(def_id) {
1500                {
    {
        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));
1501            }
1502            if should_encode_type(tcx, local_id, def_kind) {
1503                {
    {
        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));
1504            }
1505            if should_encode_constness(def_kind) {
1506                let constness = self.tcx.constness(def_id);
1507                self.tables.constness.set(def_id.index, constness);
1508            }
1509            if let DefKind::Fn | DefKind::AssocFn = def_kind {
1510                let asyncness = tcx.asyncness(def_id);
1511                self.tables.asyncness.set(def_id.index, asyncness);
1512                {
    {
        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));
1513            }
1514            if let Some(name) = tcx.intrinsic(def_id) {
1515                {
    {
        let value = name;
        let lazy = self.lazy(value);
        self.tables.intrinsic.set_some(def_id.index, lazy);
    }
};record!(self.tables.intrinsic[def_id] <- name);
1516            }
1517            if let DefKind::TyParam | DefKind::Trait = def_kind {
1518                let default = self.tcx.object_lifetime_default(def_id);
1519                {
    {
        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);
1520            }
1521            if let DefKind::Trait = def_kind {
1522                {
    {
        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));
1523                {
    {
        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] <-
1524                    self.tcx.explicit_super_clauses_of(def_id).skip_binder());
1525                {
    {
        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] <-
1526                    self.tcx.explicit_implied_clauses_of(def_id).skip_binder());
1527                let module_children = self.tcx.module_children_local(local_id);
1528                {
    {
        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] <-
1529                    module_children.iter().map(|child| child.res.def_id().index));
1530                if self.tcx.is_const_trait(def_id) {
1531                    {
    {
        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]
1532                        <- self.tcx.explicit_implied_const_bounds(def_id).skip_binder());
1533                }
1534            }
1535            if let DefKind::TraitAlias = def_kind {
1536                {
    {
        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));
1537                {
    {
        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] <-
1538                    self.tcx.explicit_super_clauses_of(def_id).skip_binder());
1539                {
    {
        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] <-
1540                    self.tcx.explicit_implied_clauses_of(def_id).skip_binder());
1541            }
1542            if let DefKind::Trait | DefKind::Impl { .. } = def_kind {
1543                let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1544                {
    {
        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] <-
1545                    associated_item_def_ids.iter().map(|&def_id| {
1546                        assert!(def_id.is_local());
1547                        def_id.index
1548                    })
1549                );
1550                for &def_id in associated_item_def_ids {
1551                    self.encode_info_for_assoc_item(def_id);
1552                }
1553            }
1554            if let DefKind::Closure | DefKind::SyntheticCoroutineBody = def_kind
1555                && let Some(coroutine_kind) = self.tcx.coroutine_kind(def_id)
1556            {
1557                self.tables.coroutine_kind.set(def_id.index, Some(coroutine_kind))
1558            }
1559            if def_kind == DefKind::Closure
1560                && tcx.type_of(def_id).skip_binder().is_coroutine_closure()
1561            {
1562                let coroutine_for_closure = self.tcx.coroutine_for_closure(def_id);
1563                self.tables
1564                    .coroutine_for_closure
1565                    .set_some(def_id.index, coroutine_for_closure.into());
1566
1567                // If this async closure has a by-move body, record it too.
1568                if tcx.needs_coroutine_by_move_body_def_id(coroutine_for_closure) {
1569                    self.tables.coroutine_by_move_body_def_id.set_some(
1570                        coroutine_for_closure.index,
1571                        self.tcx.coroutine_by_move_body_def_id(coroutine_for_closure).into(),
1572                    );
1573                }
1574            }
1575            if let DefKind::Static { .. } = def_kind {
1576                if !self.tcx.is_foreign_item(def_id) {
1577                    let data = self.tcx.eval_static_initializer(def_id).unwrap();
1578                    {
    {
        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);
1579                }
1580            }
1581            if let DefKind::Enum | DefKind::Struct | DefKind::Union = def_kind {
1582                self.encode_info_for_adt(local_id);
1583            }
1584            if let DefKind::Mod = def_kind {
1585                self.encode_info_for_mod(local_id);
1586            }
1587            if let DefKind::Macro(_) = def_kind {
1588                self.encode_info_for_macro(local_id);
1589            }
1590            if let DefKind::TyAlias = def_kind {
1591                self.tables
1592                    .type_alias_is_checked
1593                    .set(def_id.index, self.tcx.type_alias_is_checked(def_id));
1594                if self.tcx.type_alias_is_checked(def_id) {
1595                    {
    {
        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));
1596                }
1597            }
1598            if let DefKind::OpaqueTy = def_kind {
1599                self.encode_explicit_item_bounds(def_id);
1600                self.encode_explicit_item_self_bounds(def_id);
1601                {
    {
        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));
1602                self.encode_precise_capturing_args(def_id);
1603                if tcx.is_conditionally_const(def_id) {
1604                    {
    {
        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]
1605                        <- tcx.explicit_implied_const_bounds(def_id).skip_binder());
1606                }
1607                {
    {
        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));
1608            }
1609            if let DefKind::AssocTy = def_kind {
1610                let assoc_item = tcx.associated_item(def_id);
1611                match assoc_item.container {
1612                    ty::AssocContainer::Trait => {
1613                        {
    {
        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));
1614                    }
1615                    ty::AssocContainer::InherentImpl => {
1616                        {
    {
        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));
1617                    }
1618                    ty::AssocContainer::TraitImpl(_) => {}
1619                }
1620            }
1621            if let DefKind::AnonConst = def_kind {
1622                {
    {
        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));
1623            }
1624            if should_encode_const_of_item(self.tcx, def_id, def_kind) {
1625                {
    {
        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));
1626            }
1627            if tcx.impl_method_has_trait_impl_trait_tys(def_id)
1628                && let Ok(table) = self.tcx.collect_return_position_impl_trait_in_trait_tys(def_id)
1629            {
1630                {
    {
        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);
1631            }
1632            if let DefKind::Impl { .. } | DefKind::Trait = def_kind {
1633                let table = tcx.associated_types_for_impl_traits_in_trait_or_impl(def_id);
1634                {
    {
        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);
1635            }
1636        }
1637
1638        for (def_id, impls) in &tcx.crate_inherent_impls(()).0.inherent_impls {
1639            {
    {
        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| {
1640                assert!(def_id.is_local());
1641                def_id.index
1642            }));
1643        }
1644
1645        for (def_id, res_map) in &tcx.resolutions(()).doc_link_resolutions {
1646            {
    {
        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);
1647        }
1648
1649        for (def_id, traits) in &tcx.resolutions(()).doc_link_traits_in_scope {
1650            {
    {
        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);
1651        }
1652    }
1653
1654    fn encode_externally_implementable_items(&mut self) -> LazyArray<EiiMapEncodedKeyValue> {
1655        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
1656        let externally_implementable_items = self.tcx.externally_implementable_items(LOCAL_CRATE);
1657
1658        self.lazy_array(externally_implementable_items.iter().map(
1659            |(foreign_item, (decl, impls))| {
1660                (
1661                    *foreign_item,
1662                    (decl.clone(), impls.iter().map(|(impl_did, i)| (*impl_did, *i)).collect()),
1663                )
1664            },
1665        ))
1666    }
1667
1668    #[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(1668u32),
                                    ::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))]
1669    fn encode_info_for_adt(&mut self, local_def_id: LocalDefId) {
1670        let def_id = local_def_id.to_def_id();
1671        let tcx = self.tcx;
1672        let adt_def = tcx.adt_def(def_id);
1673        record!(self.tables.repr_options[def_id] <- adt_def.repr());
1674
1675        let params_in_repr = self.tcx.params_in_repr(def_id);
1676        record!(self.tables.params_in_repr[def_id] <- params_in_repr);
1677
1678        if adt_def.is_enum() {
1679            let module_children = tcx.module_children_local(local_def_id);
1680            record_array!(self.tables.module_children_non_reexports[def_id] <-
1681                module_children.iter().map(|child| child.res.def_id().index));
1682        } else {
1683            // For non-enum, there is only one variant, and its def_id is the adt's.
1684            debug_assert_eq!(adt_def.variants().len(), 1);
1685            debug_assert_eq!(adt_def.non_enum_variant().def_id, def_id);
1686            // Therefore, the loop over variants will encode its fields as the adt's children.
1687        }
1688
1689        for (idx, variant) in adt_def.variants().iter_enumerated() {
1690            let data = VariantData {
1691                discr: variant.discr,
1692                idx,
1693                ctor: variant.ctor.map(|(kind, def_id)| (kind, def_id.index)),
1694                is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1695            };
1696            record!(self.tables.variant_data[variant.def_id] <- data);
1697
1698            record_array!(self.tables.associated_item_or_field_def_ids[variant.def_id] <- variant.fields.iter().map(|f| {
1699                assert!(f.did.is_local());
1700                f.did.index
1701            }));
1702
1703            for field in &variant.fields {
1704                self.tables.safety.set(field.did.index, field.safety);
1705                record!(
1706                    self.tables.mut_restriction[field.did] <- field.mut_restriction
1707                );
1708            }
1709
1710            if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor {
1711                let fn_sig = tcx.fn_sig(ctor_def_id);
1712                // FIXME only encode signature for ctor_def_id
1713                record!(self.tables.fn_sig[variant.def_id] <- fn_sig);
1714            }
1715        }
1716
1717        if let Some(destructor) = tcx.adt_destructor(local_def_id) {
1718            record!(self.tables.adt_destructor[def_id] <- destructor);
1719        }
1720
1721        if let Some(destructor) = tcx.adt_async_destructor(local_def_id) {
1722            record!(self.tables.adt_async_destructor[def_id] <- destructor);
1723        }
1724    }
1725
1726    #[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(1726u32),
                                    ::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))]
1727    fn encode_info_for_mod(&mut self, local_def_id: LocalDefId) {
1728        let tcx = self.tcx;
1729        let def_id = local_def_id.to_def_id();
1730
1731        // If we are encoding a proc-macro crates, `encode_info_for_mod` will
1732        // only ever get called for the crate root. We still want to encode
1733        // the crate root for consistency with other crates (some of the resolver
1734        // code uses it). However, we skip encoding anything relating to child
1735        // items - we encode information about proc-macros later on.
1736        if self.is_proc_macro {
1737            // Encode this here because we don't do it in encode_def_ids.
1738            record!(self.tables.expn_that_defined[def_id] <- tcx.expn_that_defined(local_def_id));
1739        } else {
1740            let module_children = tcx.module_children_local(local_def_id);
1741
1742            record_array!(self.tables.module_children_non_reexports[def_id] <-
1743                module_children.iter().filter(|child| child.reexport_chain.is_empty())
1744                    .map(|child| child.res.def_id().index));
1745
1746            record_defaulted_array!(self.tables.module_children_reexports[def_id] <-
1747                module_children.iter().filter(|child| !child.reexport_chain.is_empty()));
1748
1749            let ambig_module_children = tcx
1750                .resolutions(())
1751                .ambig_module_children
1752                .get(&local_def_id)
1753                .map_or_default(|v| &v[..]);
1754            record_defaulted_array!(self.tables.ambig_module_children[def_id] <-
1755                ambig_module_children);
1756        }
1757    }
1758
1759    fn encode_explicit_item_bounds(&mut self, def_id: DefId) {
1760        {
    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:1760",
                        "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(1760u32),
                        ::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);
1761        let bounds = self.tcx.explicit_item_bounds(def_id).skip_binder();
1762        {
    {
        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);
1763    }
1764
1765    fn encode_explicit_item_self_bounds(&mut self, def_id: DefId) {
1766        {
    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:1766",
                        "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(1766u32),
                        ::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);
1767        let bounds = self.tcx.explicit_item_self_bounds(def_id).skip_binder();
1768        {
    {
        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);
1769    }
1770
1771    #[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(1771u32),
                                    ::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))]
1772    fn encode_info_for_assoc_item(&mut self, def_id: DefId) {
1773        let tcx = self.tcx;
1774        let item = tcx.associated_item(def_id);
1775
1776        if matches!(item.container, AssocContainer::Trait | AssocContainer::TraitImpl(_)) {
1777            self.tables.defaultness.set(def_id.index, item.defaultness(tcx));
1778        }
1779
1780        record!(self.tables.assoc_container[def_id] <- item.container);
1781
1782        if let AssocContainer::Trait = item.container
1783            && item.is_type()
1784        {
1785            self.encode_explicit_item_bounds(def_id);
1786            self.encode_explicit_item_self_bounds(def_id);
1787            if tcx.is_conditionally_const(def_id) {
1788                record_defaulted_array!(self.tables.explicit_implied_const_bounds[def_id]
1789                    <- self.tcx.explicit_implied_const_bounds(def_id).skip_binder());
1790            }
1791        }
1792        if let ty::AssocKind::Type { data: ty::AssocTypeData::Rpitit(rpitit_info) } = item.kind {
1793            record!(self.tables.opt_rpitit_info[def_id] <- rpitit_info);
1794            if matches!(rpitit_info, ty::ImplTraitInTraitData::Trait { .. }) {
1795                record_array!(
1796                    self.tables.assumed_wf_types_for_rpitit[def_id]
1797                        <- self.tcx.assumed_wf_types_for_rpitit(def_id)
1798                );
1799                self.encode_precise_capturing_args(def_id);
1800            }
1801        }
1802    }
1803
1804    fn encode_precise_capturing_args(&mut self, def_id: DefId) {
1805        let Some(precise_capturing_args) = self.tcx.rendered_precise_capturing_args(def_id) else {
1806            return;
1807        };
1808
1809        {
    {
        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);
1810    }
1811
1812    fn encode_mir(&mut self) {
1813        if self.is_proc_macro {
1814            return;
1815        }
1816
1817        let tcx = self.tcx;
1818        let reachable_set = tcx.reachable_set(());
1819
1820        let keys_and_jobs = tcx.mir_keys(()).iter().filter_map(|&def_id| {
1821            let (encode_const, encode_opt) = should_encode_mir(tcx, reachable_set, def_id);
1822            if encode_const || encode_opt { Some((def_id, encode_const, encode_opt)) } else { None }
1823        });
1824        for (def_id, encode_const, encode_opt) in keys_and_jobs {
1825            if true {
    if !(encode_const || encode_opt) {
        ::core::panicking::panic("assertion failed: encode_const || encode_opt")
    };
};debug_assert!(encode_const || encode_opt);
1826
1827            {
    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:1827",
                        "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(1827u32),
                        ::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);
1828            if encode_opt {
1829                {
    {
        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));
1830                self.tables
1831                    .cross_crate_inlinable
1832                    .set(def_id.to_def_id().index, self.tcx.cross_crate_inlinable(def_id));
1833                {
    {
        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()]
1834                    <- tcx.closure_saved_names_of_captured_variables(def_id));
1835
1836                if self.tcx.is_coroutine(def_id.to_def_id())
1837                    && let Some(witnesses) = tcx.mir_coroutine_witnesses(def_id)
1838                {
1839                    {
    {
        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);
1840                }
1841            }
1842            let mut is_trivial = false;
1843            if encode_const {
1844                if let Some((val, ty)) = tcx.trivial_const(def_id) {
1845                    is_trivial = true;
1846                    {
    {
        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));
1847                } else {
1848                    is_trivial = false;
1849                    {
    {
        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));
1850                }
1851
1852                // FIXME(generic_const_exprs): this feels wrong to have in `encode_mir`
1853                let abstract_const = tcx.thir_abstract_const(def_id);
1854                if let Ok(Some(abstract_const)) = abstract_const {
1855                    {
    {
        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);
1856                }
1857
1858                if should_encode_const(tcx.def_kind(def_id)) {
1859                    let qualifs = tcx.mir_const_qualif(def_id);
1860                    {
    {
        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);
1861                    let body = tcx.hir_maybe_body_owned_by(def_id);
1862                    if let Some(body) = body {
1863                        let const_data = rendered_const(self.tcx, &body, def_id);
1864                        {
    {
        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);
1865                    }
1866                }
1867            }
1868            if !is_trivial {
1869                {
    {
        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));
1870            }
1871
1872            if self.tcx.is_coroutine(def_id.to_def_id())
1873                && let Some(witnesses) = tcx.mir_coroutine_witnesses(def_id)
1874            {
1875                {
    {
        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);
1876            }
1877        }
1878
1879        // Encode all the deduced parameter attributes for everything that has MIR, even for items
1880        // that can't be inlined. But don't if we aren't optimizing in non-incremental mode, to
1881        // save the query traffic.
1882        if tcx.sess.opts.output_types.should_codegen()
1883            && tcx.sess.opts.optimize != OptLevel::No
1884            && tcx.sess.opts.incremental.is_none()
1885        {
1886            for &local_def_id in tcx.mir_keys(()) {
1887                if let DefKind::AssocFn | DefKind::Fn = tcx.def_kind(local_def_id) {
1888                    {
    {
        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()] <-
1889                        self.tcx.deduced_param_attrs(local_def_id.to_def_id()));
1890                }
1891            }
1892        }
1893    }
1894
1895    #[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(1895u32),
                                    ::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))]
1896    fn encode_stability(&mut self, def_id: DefId) {
1897        // The query lookup can take a measurable amount of time in crates with many items. Check if
1898        // the stability attributes are even enabled before using their queries.
1899        if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1900            if let Some(stab) = self.tcx.lookup_stability(def_id) {
1901                record!(self.tables.lookup_stability[def_id] <- stab)
1902            }
1903        }
1904    }
1905
1906    #[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(1906u32),
                                    ::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))]
1907    fn encode_const_stability(&mut self, def_id: DefId) {
1908        // The query lookup can take a measurable amount of time in crates with many items. Check if
1909        // the stability attributes are even enabled before using their queries.
1910        if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1911            if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1912                record!(self.tables.lookup_const_stability[def_id] <- stab)
1913            }
1914        }
1915    }
1916
1917    #[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(1917u32),
                                    ::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))]
1918    fn encode_default_body_stability(&mut self, def_id: DefId) {
1919        // The query lookup can take a measurable amount of time in crates with many items. Check if
1920        // the stability attributes are even enabled before using their queries.
1921        if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1922            if let Some(stab) = self.tcx.lookup_default_body_stability(def_id) {
1923                record!(self.tables.lookup_default_body_stability[def_id] <- stab)
1924            }
1925        }
1926    }
1927
1928    #[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(1928u32),
                                    ::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))]
1929    fn encode_deprecation(&mut self, def_id: DefId) {
1930        if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1931            record!(self.tables.lookup_deprecation_entry[def_id] <- depr);
1932        }
1933    }
1934
1935    #[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(1935u32),
                                    ::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))]
1936    fn encode_info_for_macro(&mut self, def_id: LocalDefId) {
1937        let tcx = self.tcx;
1938
1939        let (_, macro_def, _) = tcx.hir_expect_item(def_id).expect_macro();
1940        self.tables.is_macro_rules.set(def_id.local_def_index, macro_def.macro_rules);
1941        record!(self.tables.macro_definition[def_id.to_def_id()] <- &*macro_def.body);
1942    }
1943
1944    fn encode_native_libraries(&mut self) -> LazyArray<NativeLib> {
1945        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
1946        let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1947        self.lazy_array(used_libraries.iter())
1948    }
1949
1950    fn encode_foreign_modules(&mut self) -> LazyArray<ForeignModule> {
1951        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
1952        let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1953        self.lazy_array(foreign_modules.iter().map(|(_, m)| m).cloned())
1954    }
1955
1956    fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) {
1957        let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1958        let mut expn_data_table: TableBuilder<_, _> = Default::default();
1959        let mut expn_hash_table: TableBuilder<_, _> = Default::default();
1960
1961        self.hygiene_ctxt.encode(
1962            &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table),
1963            |(this, syntax_contexts, _, _), index, ctxt_data| {
1964                syntax_contexts.set_some(index, this.lazy(ctxt_data));
1965            },
1966            |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| {
1967                if let Some(index) = index.as_local() {
1968                    expn_data_table.set_some(index.as_raw(), this.lazy(expn_data));
1969                    expn_hash_table.set_some(index.as_raw(), this.lazy(hash));
1970                }
1971            },
1972        );
1973
1974        (
1975            syntax_contexts.encode(&mut self.opaque),
1976            expn_data_table.encode(&mut self.opaque),
1977            expn_hash_table.encode(&mut self.opaque),
1978        )
1979    }
1980
1981    fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
1982        let is_proc_macro = self.tcx.crate_types().contains(&CrateType::ProcMacro);
1983        if is_proc_macro {
1984            let tcx = self.tcx;
1985            let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index;
1986            let stability = tcx.lookup_stability(CRATE_DEF_ID);
1987            for (i, span) in self.tcx.sess.proc_macro_quoted_spans() {
1988                let span = self.lazy(span);
1989                self.tables.proc_macro_quoted_spans.set_some(i, span);
1990            }
1991
1992            self.tables.def_kind.set_some(LOCAL_CRATE.as_def_id().index, DefKind::Mod);
1993            {
    {
        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()));
1994            self.encode_attrs(LOCAL_CRATE.as_def_id().expect_local());
1995            let vis = tcx
1996                .local_visibility(CRATE_DEF_ID)
1997                .map_id(|mod_id| mod_id.to_local_def_id().local_def_index);
1998            {
    {
        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);
1999            if let Some(stability) = stability {
2000                {
    {
        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);
2001            }
2002            self.encode_deprecation(LOCAL_CRATE.as_def_id());
2003            if let Some(res_map) = tcx.resolutions(()).doc_link_resolutions.get(&CRATE_MOD_ID) {
2004                {
    {
        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);
2005            }
2006            if let Some(traits) = tcx.resolutions(()).doc_link_traits_in_scope.get(&CRATE_MOD_ID) {
2007                {
    {
        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);
2008            }
2009
2010            let mut macros = ::alloc::vec::Vec::new()vec![];
2011
2012            // Normally, this information is encoded when we walk the items
2013            // defined in this crate. However, we skip doing that for proc-macro crates,
2014            // so we manually encode just the information that we need
2015            for &proc_macro in &tcx.resolutions(()).proc_macros {
2016                let id = proc_macro;
2017                let proc_macro = tcx.local_def_id_to_hir_id(proc_macro);
2018                let mut name = tcx.hir_name(proc_macro);
2019                let span = tcx.hir_span(proc_macro);
2020                // Proc-macros may have attributes like `#[allow_internal_unstable]`,
2021                // so downstream crates need access to them.
2022                let attrs = tcx.hir_attrs(proc_macro);
2023                let (macro_kind, kind) = if {
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(ProcMacro) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, ProcMacro) {
2024                    (MacroKind::Bang, ProcMacroKind::Bang { name: name.as_str().to_owned() })
2025                } else if {
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(ProcMacroAttribute) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, ProcMacroAttribute) {
2026                    (MacroKind::Attr, ProcMacroKind::Attr { name: name.as_str().to_owned() })
2027                } else if let Some((trait_name, helper_attrs)) = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use ::rustc_attr_ir::AttributeKind::*;
            let i: &::rustc_attr_ir::Attribute = i;
            match i {
                ::rustc_attr_ir::Attribute::Parsed(ProcMacroDerive {
                    trait_name, helper_attrs }) => {
                    break 'done Some((trait_name, helper_attrs));
                }
                ::rustc_attr_ir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs,
2028                    ProcMacroDerive { trait_name, helper_attrs } => (trait_name, helper_attrs))
2029                {
2030                    name = *trait_name;
2031                    (
2032                        MacroKind::Derive,
2033                        ProcMacroKind::CustomDerive {
2034                            trait_name: name.as_str().to_owned(),
2035                            attributes: helper_attrs
2036                                .iter()
2037                                .map(|attr| attr.as_str().to_owned())
2038                                .collect(),
2039                        },
2040                    )
2041                } else {
2042                    ::rustc_middle::util::bug::bug_fmt(format_args!("Unknown proc-macro type for item {0:?}",
        id));bug!("Unknown proc-macro type for item {:?}", id);
2043                };
2044
2045                macros.push((id.local_def_index, self.lazy(kind)));
2046
2047                let mut def_key = self.tcx.hir_def_key(id);
2048                def_key.disambiguated_data.data = DefPathData::MacroNs(name);
2049
2050                let def_id = id.to_def_id();
2051                self.tables.def_kind.set_some(def_id.index, DefKind::Macro(macro_kind.into()));
2052                self.encode_attrs(id);
2053                {
    {
        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);
2054                {
    {
        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);
2055                {
    {
        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);
2056                {
    {
        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);
2057                if let Some(stability) = stability {
2058                    {
    {
        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);
2059                }
2060            }
2061
2062            let macros = self.lazy_array(macros);
2063
2064            Some(ProcMacroData { proc_macro_decls_static, stability, macros })
2065        } else {
2066            None
2067        }
2068    }
2069
2070    fn encode_debugger_visualizers(&mut self) -> LazyArray<DebuggerVisualizerFile> {
2071        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2072        self.lazy_array(
2073            self.tcx
2074                .debugger_visualizers(LOCAL_CRATE)
2075                .iter()
2076                // Erase the path since it may contain privacy sensitive data
2077                // that we don't want to end up in crate metadata.
2078                // The path is only needed for the local crate because of
2079                // `--emit dep-info`.
2080                .map(DebuggerVisualizerFile::path_erased),
2081        )
2082    }
2083
2084    fn encode_crate_deps(&mut self) -> LazyArray<CrateDep> {
2085        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2086
2087        let deps = self
2088            .tcx
2089            .crates(())
2090            .iter()
2091            .map(|&cnum| {
2092                let dep = CrateDep {
2093                    name: self.tcx.crate_name(cnum),
2094                    hash: self.tcx.crate_hash(cnum),
2095                    host_hash: self.tcx.crate_host_hash(cnum),
2096                    kind: self.tcx.crate_dep_kind(cnum),
2097                    extra_filename: self.tcx.extra_filename(cnum).clone(),
2098                    is_private: self.tcx.is_private_dep(cnum),
2099                };
2100                (cnum, dep)
2101            })
2102            .collect::<Vec<_>>();
2103
2104        {
2105            // Sanity-check the crate numbers
2106            let mut expected_cnum = 1;
2107            for &(n, _) in &deps {
2108                {
    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));
2109                expected_cnum += 1;
2110            }
2111        }
2112
2113        // We're just going to write a list of crate 'name-hash-version's, with
2114        // the assumption that they are numbered 1 to n.
2115        // FIXME (#2166): This is not nearly enough to support correct versioning
2116        // but is enough to get transitive crate dependencies working.
2117        self.lazy_array(deps.iter().map(|(_, dep)| dep))
2118    }
2119
2120    fn encode_target_modifiers(&mut self) -> LazyArray<TargetModifier> {
2121        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2122        let tcx = self.tcx;
2123        self.lazy_array(tcx.sess.opts.gather_target_modifiers())
2124    }
2125
2126    fn encode_enabled_denied_partial_mitigations(&mut self) -> LazyArray<DeniedPartialMitigation> {
2127        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2128        let tcx = self.tcx;
2129        self.lazy_array(tcx.sess.gather_enabled_denied_partial_mitigations())
2130    }
2131
2132    fn encode_lib_features(&mut self) -> LazyArray<(Symbol, FeatureStability)> {
2133        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2134        let tcx = self.tcx;
2135        let lib_features = tcx.lib_features(LOCAL_CRATE);
2136        self.lazy_array(lib_features.to_sorted_vec())
2137    }
2138
2139    fn encode_stability_implications(&mut self) -> LazyArray<(Symbol, Symbol)> {
2140        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2141        let tcx = self.tcx;
2142        let implications = tcx.stability_implications(LOCAL_CRATE);
2143        let sorted = implications.to_sorted_stable_ord();
2144        self.lazy_array(sorted.into_iter().map(|(k, v)| (*k, *v)))
2145    }
2146
2147    fn encode_canonical_symbols(&mut self) -> LazyArray<(Symbol, DefIndex)> {
2148        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2149        let tcx = self.tcx;
2150        let canonical_symbols = &tcx.canonical_symbols(LOCAL_CRATE);
2151        self.lazy_array(canonical_symbols.iter().map(|cs| (cs.symbol, cs.def_id.index)))
2152    }
2153
2154    fn encode_diagnostic_items(&mut self) -> LazyArray<(Symbol, DefIndex)> {
2155        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2156        let tcx = self.tcx;
2157        let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id;
2158        self.lazy_array(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
2159    }
2160
2161    fn encode_lang_items(&mut self) -> LazyArray<(DefIndex, LangItem)> {
2162        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2163        let lang_items = self.tcx.lang_items().iter();
2164        self.lazy_array(lang_items.filter_map(|(lang_item, def_id)| {
2165            def_id.as_local().map(|id| (id.local_def_index, lang_item))
2166        }))
2167    }
2168
2169    fn encode_lang_items_missing(&mut self) -> LazyArray<LangItem> {
2170        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2171        let tcx = self.tcx;
2172        self.lazy_array(&tcx.lang_items().missing)
2173    }
2174
2175    fn encode_stripped_cfg_items(&mut self) -> LazyArray<StrippedCfgItem<DefIndex>> {
2176        self.lazy_array(
2177            self.tcx
2178                .stripped_cfg_items(LOCAL_CRATE)
2179                .into_iter()
2180                .map(|item| item.clone().map_scope_id(|def_id| def_id.index)),
2181        )
2182    }
2183
2184    fn encode_traits(&mut self) -> LazyArray<DefIndex> {
2185        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2186        self.lazy_array(self.tcx.traits(LOCAL_CRATE).iter().map(|def_id| def_id.index))
2187    }
2188
2189    /// Encodes an index, mapping each trait to its (local) implementations.
2190    #[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(2190u32),
                                    ::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))]
2191    fn encode_impls(&mut self) -> LazyArray<TraitImpls> {
2192        empty_proc_macro!(self);
2193        let tcx = self.tcx;
2194        let mut trait_impls: FxIndexMap<DefId, Vec<(DefIndex, Option<SimplifiedType>)>> =
2195            FxIndexMap::default();
2196
2197        for id in tcx.hir_free_items() {
2198            let DefKind::Impl { of_trait } = tcx.def_kind(id.owner_id) else {
2199                continue;
2200            };
2201            let def_id = id.owner_id.to_def_id();
2202
2203            if of_trait {
2204                let header = tcx.impl_trait_header(def_id);
2205                record!(self.tables.impl_trait_header[def_id] <- header);
2206
2207                let impl_is_fully_generic_for_reflection =
2208                    tcx.impl_is_fully_generic_for_reflection(def_id);
2209                self.tables
2210                    .impl_is_fully_generic_for_reflection
2211                    .set(def_id.index, impl_is_fully_generic_for_reflection);
2212
2213                self.tables.defaultness.set(def_id.index, tcx.defaultness(def_id));
2214
2215                let trait_ref = header.trait_ref.instantiate_identity().skip_norm_wip();
2216                let simplified_self_ty = fast_reject::simplify_type(
2217                    self.tcx,
2218                    trait_ref.self_ty(),
2219                    TreatParams::InstantiateWithInfer,
2220                );
2221                trait_impls
2222                    .entry(trait_ref.def_id)
2223                    .or_default()
2224                    .push((id.owner_id.def_id.local_def_index, simplified_self_ty));
2225
2226                let trait_def = tcx.trait_def(trait_ref.def_id);
2227                if let Ok(mut an) = trait_def.ancestors(tcx, def_id)
2228                    && let Some(specialization_graph::Node::Impl(parent)) = an.nth(1)
2229                {
2230                    self.tables.impl_parent.set_some(def_id.index, parent.into());
2231                }
2232
2233                // if this is an impl of `CoerceUnsized`, create its
2234                // "unsized info", else just store None
2235                if tcx.is_lang_item(trait_ref.def_id, LangItem::CoerceUnsized) {
2236                    let coerce_unsized_info = tcx.coerce_unsized_info(def_id).unwrap();
2237                    record!(self.tables.coerce_unsized_info[def_id] <- coerce_unsized_info);
2238                }
2239            }
2240        }
2241
2242        let trait_impls: Vec<_> = trait_impls
2243            .into_iter()
2244            .map(|(trait_def_id, impls)| TraitImpls {
2245                trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
2246                impls: self.lazy_array(&impls),
2247            })
2248            .collect();
2249
2250        self.lazy_array(&trait_impls)
2251    }
2252
2253    #[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(2253u32),
                                    ::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))]
2254    fn encode_incoherent_impls(&mut self) -> LazyArray<IncoherentImpls> {
2255        empty_proc_macro!(self);
2256        let tcx = self.tcx;
2257
2258        let all_impls: Vec<_> = tcx
2259            .crate_inherent_impls(())
2260            .0
2261            .incoherent_impls
2262            .iter()
2263            .map(|(&simp, impls)| IncoherentImpls {
2264                self_ty: self.lazy(simp),
2265                impls: self.lazy_array(impls.iter().map(|def_id| def_id.local_def_index)),
2266            })
2267            .collect();
2268
2269        self.lazy_array(&all_impls)
2270    }
2271
2272    fn encode_exportable_items(&mut self) -> LazyArray<DefIndex> {
2273        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2274        self.lazy_array(self.tcx.exportable_items(LOCAL_CRATE).iter().map(|def_id| def_id.index))
2275    }
2276
2277    fn encode_stable_order_of_exportable_impls(&mut self) -> LazyArray<(DefIndex, usize)> {
2278        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2279        let stable_order_of_exportable_impls =
2280            self.tcx.stable_order_of_exportable_impls(LOCAL_CRATE);
2281        self.lazy_array(
2282            stable_order_of_exportable_impls.iter().map(|(def_id, idx)| (def_id.index, *idx)),
2283        )
2284    }
2285
2286    // Encodes all symbols exported from this crate into the metadata.
2287    //
2288    // This pass is seeded off the reachability list calculated in the
2289    // middle::reachable module but filters out items that either don't have a
2290    // symbol associated with them (they weren't translated) or if they're an FFI
2291    // definition (as that's not defined in this crate).
2292    fn encode_exported_symbols(
2293        &mut self,
2294        exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportInfo)],
2295    ) -> LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)> {
2296        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2297
2298        self.lazy_array(exported_symbols.iter().cloned())
2299    }
2300
2301    fn encode_dylib_dependency_formats(&mut self) -> LazyArray<Option<LinkagePreference>> {
2302        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2303        let formats = self.tcx.dependency_formats(());
2304        if let Some(arr) = formats.get(&CrateType::Dylib) {
2305            return self.lazy_array(arr.iter().skip(1 /* skip LOCAL_CRATE */).map(
2306                |slot| match *slot {
2307                    Linkage::NotLinked | Linkage::IncludedFromDylib => None,
2308
2309                    Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
2310                    Linkage::Static => Some(LinkagePreference::RequireStatic),
2311                },
2312            ));
2313        }
2314        LazyArray::default()
2315    }
2316}
2317
2318/// Used to prefetch queries which will be needed later by metadata encoding.
2319/// Only a subset of the queries are actually prefetched to keep this code smaller.
2320fn prefetch_mir(tcx: TyCtxt<'_>) {
2321    if !tcx.sess.opts.output_types.should_codegen() {
2322        // We won't emit MIR, so don't prefetch it.
2323        return;
2324    }
2325
2326    let reachable_set = tcx.reachable_set(());
2327    par_for_each_in(tcx.mir_keys(()), |&&def_id| {
2328        if tcx.is_trivial_const(def_id) {
2329            return;
2330        }
2331        let (encode_const, encode_opt) = should_encode_mir(tcx, reachable_set, def_id);
2332
2333        if encode_const {
2334            tcx.ensure_done().mir_for_ctfe(def_id);
2335        }
2336        if encode_opt {
2337            tcx.ensure_done().optimized_mir(def_id);
2338        }
2339        if encode_opt || encode_const {
2340            tcx.ensure_done().promoted_mir(def_id);
2341        }
2342    })
2343}
2344
2345// NOTE(eddyb) The following comment was preserved for posterity, even
2346// though it's no longer relevant as EBML (which uses nested & tagged
2347// "documents") was replaced with a scheme that can't go out of bounds.
2348//
2349// And here we run into yet another obscure archive bug: in which metadata
2350// loaded from archives may have trailing garbage bytes. Awhile back one of
2351// our tests was failing sporadically on the macOS 64-bit builders (both nopt
2352// and opt) by having ebml generate an out-of-bounds panic when looking at
2353// metadata.
2354//
2355// Upon investigation it turned out that the metadata file inside of an rlib
2356// (and ar archive) was being corrupted. Some compilations would generate a
2357// metadata file which would end in a few extra bytes, while other
2358// compilations would not have these extra bytes appended to the end. These
2359// extra bytes were interpreted by ebml as an extra tag, so they ended up
2360// being interpreted causing the out-of-bounds.
2361//
2362// The root cause of why these extra bytes were appearing was never
2363// discovered, and in the meantime the solution we're employing is to insert
2364// the length of the metadata to the start of the metadata. Later on this
2365// will allow us to slice the metadata to the precise length that we just
2366// generated regardless of trailing bytes that end up in it.
2367
2368pub struct EncodedMetadata {
2369    // The declaration order matters because `full_metadata` should be dropped
2370    // before `_temp_dir`.
2371    full_metadata: Option<Mmap>,
2372    // This is an optional stub metadata containing only the crate header.
2373    // The header should be very small, so we load it directly into memory.
2374    stub_metadata: Option<Vec<u8>>,
2375    // The path containing the metadata, to record as work product.
2376    path: Option<Box<Path>>,
2377    // We need to carry MaybeTempDir to avoid deleting the temporary
2378    // directory while accessing the Mmap.
2379    _temp_dir: Option<MaybeTempDir>,
2380}
2381
2382impl EncodedMetadata {
2383    #[inline]
2384    pub fn from_path(
2385        path: PathBuf,
2386        stub_path: Option<PathBuf>,
2387        temp_dir: Option<MaybeTempDir>,
2388    ) -> std::io::Result<Self> {
2389        let file = std::fs::File::open(&path)?;
2390        let file_metadata = file.metadata()?;
2391        if file_metadata.len() == 0 {
2392            return Ok(Self {
2393                full_metadata: None,
2394                stub_metadata: None,
2395                path: None,
2396                _temp_dir: None,
2397            });
2398        }
2399        let full_mmap = unsafe { Some(Mmap::map(file)?) };
2400
2401        let stub =
2402            if let Some(stub_path) = stub_path { Some(std::fs::read(stub_path)?) } else { None };
2403
2404        Ok(Self {
2405            full_metadata: full_mmap,
2406            stub_metadata: stub,
2407            path: Some(path.into()),
2408            _temp_dir: temp_dir,
2409        })
2410    }
2411
2412    #[inline]
2413    pub fn full(&self) -> &[u8] {
2414        &self.full_metadata.as_deref().unwrap_or_default()
2415    }
2416
2417    #[inline]
2418    pub fn stub_or_full(&self) -> &[u8] {
2419        self.stub_metadata.as_deref().unwrap_or(self.full())
2420    }
2421
2422    #[inline]
2423    pub fn path(&self) -> Option<&Path> {
2424        self.path.as_deref()
2425    }
2426}
2427
2428impl<S: Encoder> Encodable<S> for EncodedMetadata {
2429    fn encode(&self, s: &mut S) {
2430        self.stub_metadata.encode(s);
2431
2432        let slice = self.full();
2433        slice.encode(s)
2434    }
2435}
2436
2437impl<D: Decoder> Decodable<D> for EncodedMetadata {
2438    fn decode(d: &mut D) -> Self {
2439        let stub = <Option<Vec<u8>>>::decode(d);
2440
2441        let len = d.read_usize();
2442        let full_metadata = if len > 0 {
2443            let mut mmap = MmapMut::map_anon(len).unwrap();
2444            mmap.copy_from_slice(d.read_raw_bytes(len));
2445            Some(mmap.make_read_only().unwrap())
2446        } else {
2447            None
2448        };
2449
2450        Self { full_metadata, stub_metadata: stub, path: None, _temp_dir: None }
2451    }
2452}
2453
2454#[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(2454u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("path")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("path");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ref_path")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ref_path");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ref_path)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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