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 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());
643
644        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());
645
646        _ = {
    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());
647
648        // Encode the def IDs of traits, for rustdoc and diagnostics.
649        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());
650
651        // Encode the def IDs of impls, for coherence checking.
652        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());
653
654        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());
655
656        _ = {
    let orig_pos = self.position();
    let res = (|| self.encode_mir())();
    stats.push(("mir", self.position() - orig_pos));
    res
}stat!("mir", || self.encode_mir());
657
658        _ = {
    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());
659
660        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:663",
                                            "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(663u32),
                                            ::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:671",
                                                "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(671u32),
                                                ::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", || {
661            let mut interpret_alloc_index = Vec::new();
662            let mut n = 0;
663            trace!("beginning to encode alloc ids");
664            loop {
665                let new_n = self.interpret_allocs.len();
666                // if we have found new ids, serialize those, too
667                if n == new_n {
668                    // otherwise, abort
669                    break;
670                }
671                trace!("encoding {} further alloc ids", new_n - n);
672                for idx in n..new_n {
673                    let id = self.interpret_allocs[idx];
674                    let pos = self.position() as u64;
675                    interpret_alloc_index.push(pos);
676                    interpret::specialized_encode_alloc_id(self, tcx, id);
677                }
678                n = new_n;
679            }
680            self.lazy_array(interpret_alloc_index)
681        });
682
683        // Encode the proc macro data. This affects `tables`, so we need to do this before we
684        // encode the tables. This overwrites def_keys, so it must happen after
685        // encode_def_path_table.
686        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());
687
688        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));
689
690        let debugger_visualizers =
691            {
    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());
692
693        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());
694
695        let stable_order_of_exportable_impls =
696            {
    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());
697
698        // Encode exported symbols info. This is prefetched in `encode_metadata`.
699        let (exported_non_generic_symbols, exported_generic_symbols) =
700            {
    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", || {
701                (
702                    self.encode_exported_symbols(tcx.exported_non_generic_symbols(LOCAL_CRATE)),
703                    self.encode_exported_symbols(tcx.exported_generic_symbols(LOCAL_CRATE)),
704                )
705            });
706
707        // Encode the hygiene data.
708        // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The
709        // process of encoding other items (e.g. `optimized_mir`) may cause us to load data from
710        // the incremental cache. If this causes us to deserialize a `Span`, then we may load
711        // additional `SyntaxContext`s into the global `HygieneData`. Therefore, we need to encode
712        // the hygiene data last to ensure that we encode any `SyntaxContext`s that might be used.
713        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());
714
715        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());
716
717        // Encode source_map. This needs to be done last, because encoding `Span`s tells us which
718        // `SourceFiles` we actually need to encode.
719        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());
720        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());
721        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
722            .encode_enabled_denied_partial_mitigations());
723
724        let root = {
    let orig_pos = self.position();
    let res =
        (||
                {
                    let attrs = tcx.hir_krate_attrs();
                    self.lazy(CrateRoot {
                            header: CrateHeader {
                                name: tcx.crate_name(LOCAL_CRATE),
                                triple: tcx.sess.opts.target_triple.clone(),
                                hash: tcx.crate_hash(LOCAL_CRATE),
                                is_proc_macro_crate: proc_macro_data.is_some(),
                                is_stub: false,
                            },
                            extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
                            stable_crate_id: tcx.stable_crate_id(LOCAL_CRATE),
                            required_panic_strategy: tcx.required_panic_strategy(LOCAL_CRATE),
                            panic_in_drop_strategy: tcx.sess.opts.unstable_opts.panic_in_drop,
                            edition: tcx.sess.edition(),
                            has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
                            has_alloc_error_handler: tcx.has_alloc_error_handler(LOCAL_CRATE),
                            has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
                            has_default_lib_allocator: {
                                {
                                        'done:
                                            {
                                            for i in attrs {
                                                #[allow(unused_imports)]
                                                use rustc_hir::attrs::AttributeKind::*;
                                                let i: &rustc_hir::Attribute = i;
                                                match i {
                                                    rustc_hir::Attribute::Parsed(DefaultLibAllocator) => {
                                                        break 'done Some(());
                                                    }
                                                    rustc_hir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }.is_some()
                            },
                            externally_implementable_items,
                            proc_macro_data,
                            debugger_visualizers,
                            compiler_builtins: {
                                {
                                        'done:
                                            {
                                            for i in attrs {
                                                #[allow(unused_imports)]
                                                use rustc_hir::attrs::AttributeKind::*;
                                                let i: &rustc_hir::Attribute = i;
                                                match i {
                                                    rustc_hir::Attribute::Parsed(CompilerBuiltins) => {
                                                        break 'done Some(());
                                                    }
                                                    rustc_hir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }.is_some()
                            },
                            needs_allocator: {
                                {
                                        'done:
                                            {
                                            for i in attrs {
                                                #[allow(unused_imports)]
                                                use rustc_hir::attrs::AttributeKind::*;
                                                let i: &rustc_hir::Attribute = i;
                                                match i {
                                                    rustc_hir::Attribute::Parsed(NeedsAllocator) => {
                                                        break 'done Some(());
                                                    }
                                                    rustc_hir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }.is_some()
                            },
                            needs_panic_runtime: {
                                {
                                        'done:
                                            {
                                            for i in attrs {
                                                #[allow(unused_imports)]
                                                use rustc_hir::attrs::AttributeKind::*;
                                                let i: &rustc_hir::Attribute = i;
                                                match i {
                                                    rustc_hir::Attribute::Parsed(NeedsPanicRuntime) => {
                                                        break 'done Some(());
                                                    }
                                                    rustc_hir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }.is_some()
                            },
                            no_builtins: {
                                {
                                        'done:
                                            {
                                            for i in attrs {
                                                #[allow(unused_imports)]
                                                use rustc_hir::attrs::AttributeKind::*;
                                                let i: &rustc_hir::Attribute = i;
                                                match i {
                                                    rustc_hir::Attribute::Parsed(NoBuiltins) => {
                                                        break 'done Some(());
                                                    }
                                                    rustc_hir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }.is_some()
                            },
                            panic_runtime: {
                                {
                                        'done:
                                            {
                                            for i in attrs {
                                                #[allow(unused_imports)]
                                                use rustc_hir::attrs::AttributeKind::*;
                                                let i: &rustc_hir::Attribute = i;
                                                match i {
                                                    rustc_hir::Attribute::Parsed(PanicRuntime) => {
                                                        break 'done Some(());
                                                    }
                                                    rustc_hir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }.is_some()
                            },
                            profiler_runtime: {
                                {
                                        'done:
                                            {
                                            for i in attrs {
                                                #[allow(unused_imports)]
                                                use rustc_hir::attrs::AttributeKind::*;
                                                let i: &rustc_hir::Attribute = i;
                                                match i {
                                                    rustc_hir::Attribute::Parsed(ProfilerRuntime) => {
                                                        break 'done Some(());
                                                    }
                                                    rustc_hir::Attribute::Unparsed(..) =>
                                                        {}
                                                        #[deny(unreachable_patterns)]
                                                        _ => {}
                                                }
                                            }
                                            None
                                        }
                                    }.is_some()
                            },
                            symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(),
                            crate_deps,
                            dylib_dependency_formats,
                            lib_features,
                            stability_implications,
                            lang_items,
                            diagnostic_items,
                            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", || {
725            let attrs = tcx.hir_krate_attrs();
726            self.lazy(CrateRoot {
727                header: CrateHeader {
728                    name: tcx.crate_name(LOCAL_CRATE),
729                    triple: tcx.sess.opts.target_triple.clone(),
730                    hash: tcx.crate_hash(LOCAL_CRATE),
731                    is_proc_macro_crate: proc_macro_data.is_some(),
732                    is_stub: false,
733                },
734                extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
735                stable_crate_id: tcx.stable_crate_id(LOCAL_CRATE),
736                required_panic_strategy: tcx.required_panic_strategy(LOCAL_CRATE),
737                panic_in_drop_strategy: tcx.sess.opts.unstable_opts.panic_in_drop,
738                edition: tcx.sess.edition(),
739                has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
740                has_alloc_error_handler: tcx.has_alloc_error_handler(LOCAL_CRATE),
741                has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
742                has_default_lib_allocator: find_attr!(attrs, DefaultLibAllocator),
743                externally_implementable_items,
744                proc_macro_data,
745                debugger_visualizers,
746                compiler_builtins: find_attr!(attrs, CompilerBuiltins),
747                needs_allocator: find_attr!(attrs, NeedsAllocator),
748                needs_panic_runtime: find_attr!(attrs, NeedsPanicRuntime),
749                no_builtins: find_attr!(attrs, NoBuiltins),
750                panic_runtime: find_attr!(attrs, PanicRuntime),
751                profiler_runtime: find_attr!(attrs, ProfilerRuntime),
752                symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(),
753
754                crate_deps,
755                dylib_dependency_formats,
756                lib_features,
757                stability_implications,
758                lang_items,
759                diagnostic_items,
760                lang_items_missing,
761                stripped_cfg_items,
762                native_libraries,
763                foreign_modules,
764                source_map,
765                target_modifiers,
766                denied_partial_mitigations,
767                traits,
768                impls,
769                incoherent_impls,
770                exportable_items,
771                stable_order_of_exportable_impls,
772                exported_non_generic_symbols,
773                exported_generic_symbols,
774                interpret_alloc_index,
775                tables,
776                syntax_contexts,
777                expn_data,
778                expn_hashes,
779                def_path_hash_map,
780                specialization_enabled_in: tcx.specialization_enabled_in(LOCAL_CRATE),
781            })
782        });
783
784        let total_bytes = self.position();
785
786        let computed_total_bytes: usize = stats.iter().map(|(_, size)| size).sum();
787        {
    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);
788
789        if tcx.sess.opts.unstable_opts.meta_stats {
790            use std::fmt::Write;
791
792            self.opaque.flush();
793
794            // Rewind and re-read all the metadata to count the zero bytes we wrote.
795            let pos_before_rewind = self.opaque.file().stream_position().unwrap();
796            let mut zero_bytes = 0;
797            self.opaque.file().rewind().unwrap();
798            let file = std::io::BufReader::new(self.opaque.file());
799            for e in file.bytes() {
800                if e.unwrap() == 0 {
801                    zero_bytes += 1;
802                }
803            }
804            {
    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);
805
806            stats.sort_by_key(|&(_, usize)| usize);
807            stats.reverse(); // bigger items first
808
809            let prefix = "meta-stats";
810            let perc = |bytes| (bytes * 100) as f64 / total_bytes as f64;
811
812            let section_w = 23;
813            let size_w = 10;
814            let banner_w = 64;
815
816            // We write all the text into a string and print it with a single
817            // `eprint!`. This is an attempt to minimize interleaved text if multiple
818            // rustc processes are printing macro-stats at the same time (e.g. with
819            // `RUSTFLAGS='-Zmeta-stats' cargo build`). It still doesn't guarantee
820            // non-interleaving, though.
821            let mut s = String::new();
822            _ = s.write_fmt(format_args!("{1} {0}\n", "=".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "=".repeat(banner_w));
823            _ = 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));
824            _ = 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");
825            _ = s.write_fmt(format_args!("{1} {0}\n", "-".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "-".repeat(banner_w));
826            for (label, size) in stats {
827                _ = 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!(
828                    s,
829                    "{prefix} {:<section_w$}{:>size_w$} ({:4.1}%)",
830                    label,
831                    usize_with_underscores(size),
832                    perc(size)
833                );
834            }
835            _ = s.write_fmt(format_args!("{1} {0}\n", "-".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "-".repeat(banner_w));
836            _ = 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!(
837                s,
838                "{prefix} {:<section_w$}{:>size_w$} (of which {:.1}% are zero bytes)",
839                "Total",
840                usize_with_underscores(total_bytes),
841                perc(zero_bytes)
842            );
843            _ = s.write_fmt(format_args!("{1} {0}\n", "=".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "=".repeat(banner_w));
844            { ::std::io::_eprint(format_args!("{0}", s)); };eprint!("{s}");
845        }
846
847        root
848    }
849}
850
851struct AnalyzeAttrState {
852    is_exported: bool,
853    is_doc_hidden: bool,
854}
855
856/// Returns whether an attribute needs to be recorded in metadata, that is, if it's usable and
857/// useful in downstream crates. Local-only attributes are an obvious example, but some
858/// rustdoc-specific attributes can equally be of use while documenting the current crate only.
859///
860/// Removing these superfluous attributes speeds up compilation by making the metadata smaller.
861///
862/// Note: the `is_exported` parameter is used to cache whether the given `DefId` has a public
863/// visibility: this is a piece of data that can be computed once per defid, and not once per
864/// attribute. Some attributes would only be usable downstream if they are public.
865#[inline]
866fn analyze_attr(attr: &hir::Attribute, state: &mut AnalyzeAttrState) -> bool {
867    let mut should_encode = false;
868    if let hir::Attribute::Parsed(p) = attr
869        && p.encode_cross_crate() == EncodeCrossCrate::No
870    {
871        // Attributes not marked encode-cross-crate don't need to be encoded for downstream crates.
872    } else if let Some(name) = attr.name()
873        && [sym::warn, sym::allow, sym::expect, sym::forbid, sym::deny].contains(&name)
874    {
875        // Lint attributes don't need to be encoded for downstream crates.
876        // FIXME remove this when #152369 is re-merged
877    } else if let hir::Attribute::Parsed(AttributeKind::DocComment { .. }) = attr {
878        // We keep all doc comments reachable to rustdoc because they might be "imported" into
879        // downstream crates if they use `#[doc(inline)]` to copy an item's documentation into
880        // their own.
881        if state.is_exported {
882            should_encode = true;
883        }
884    } else if let hir::Attribute::Parsed(AttributeKind::Doc(d)) = attr {
885        should_encode = true;
886        if d.hidden.is_some() {
887            state.is_doc_hidden = true;
888        }
889    } else {
890        should_encode = true;
891    }
892    should_encode
893}
894
895fn should_encode_span(def_kind: DefKind) -> bool {
896    match def_kind {
897        DefKind::Mod
898        | DefKind::Struct
899        | DefKind::Union
900        | DefKind::Enum
901        | DefKind::Variant
902        | DefKind::Trait
903        | DefKind::TyAlias
904        | DefKind::ForeignTy
905        | DefKind::TraitAlias
906        | DefKind::AssocTy
907        | DefKind::TyParam
908        | DefKind::ConstParam
909        | DefKind::LifetimeParam
910        | DefKind::Fn
911        | DefKind::Const { .. }
912        | DefKind::Static { .. }
913        | DefKind::Ctor(..)
914        | DefKind::AssocFn
915        | DefKind::AssocConst { .. }
916        | DefKind::Macro(_)
917        | DefKind::ExternCrate
918        | DefKind::Use
919        | DefKind::AnonConst
920        | DefKind::OpaqueTy
921        | DefKind::Field
922        | DefKind::Impl { .. }
923        | DefKind::Closure
924        | DefKind::SyntheticCoroutineBody => true,
925        DefKind::ForeignMod | DefKind::GlobalAsm => false,
926    }
927}
928
929fn should_encode_attrs(def_kind: DefKind) -> bool {
930    match def_kind {
931        DefKind::Mod
932        | DefKind::Struct
933        | DefKind::Union
934        | DefKind::Enum
935        | DefKind::Variant
936        | DefKind::Trait
937        | DefKind::TyAlias
938        | DefKind::ForeignTy
939        | DefKind::TraitAlias
940        | DefKind::AssocTy
941        | DefKind::Fn
942        | DefKind::Const { .. }
943        | DefKind::Static { nested: false, .. }
944        | DefKind::AssocFn
945        | DefKind::AssocConst { .. }
946        | DefKind::Macro(_)
947        | DefKind::Field
948        | DefKind::Impl { .. } => true,
949        // Encoding attrs for `Use` items allows `#[doc(hidden)]` on re-exports
950        // to be read cross-crate, which is needed for diagnostic path selection
951        // in `visible_parent_map`. See #153477.
952        DefKind::Use => true,
953        // Tools may want to be able to detect their tool lints on
954        // closures from upstream crates, too. This is used by
955        // https://github.com/model-checking/kani and is not a performance
956        // or maintenance issue for us.
957        DefKind::Closure => true,
958        DefKind::SyntheticCoroutineBody => false,
959        DefKind::TyParam
960        | DefKind::ConstParam
961        | DefKind::Ctor(..)
962        | DefKind::ExternCrate
963        | DefKind::ForeignMod
964        | DefKind::AnonConst
965        | DefKind::OpaqueTy
966        | DefKind::LifetimeParam
967        | DefKind::Static { nested: true, .. }
968        | DefKind::GlobalAsm => false,
969    }
970}
971
972fn should_encode_expn_that_defined(def_kind: DefKind) -> bool {
973    match def_kind {
974        DefKind::Mod
975        | DefKind::Struct
976        | DefKind::Union
977        | DefKind::Enum
978        | DefKind::Variant
979        | DefKind::Trait
980        | DefKind::Impl { .. } => true,
981        DefKind::TyAlias
982        | DefKind::ForeignTy
983        | DefKind::TraitAlias
984        | DefKind::AssocTy
985        | DefKind::TyParam
986        | DefKind::Fn
987        | DefKind::Const { .. }
988        | DefKind::ConstParam
989        | DefKind::Static { .. }
990        | DefKind::Ctor(..)
991        | DefKind::AssocFn
992        | DefKind::AssocConst { .. }
993        | DefKind::Macro(_)
994        | DefKind::ExternCrate
995        | DefKind::Use
996        | DefKind::ForeignMod
997        | DefKind::AnonConst
998        | DefKind::OpaqueTy
999        | DefKind::Field
1000        | DefKind::LifetimeParam
1001        | DefKind::GlobalAsm
1002        | DefKind::Closure
1003        | DefKind::SyntheticCoroutineBody => false,
1004    }
1005}
1006
1007fn should_encode_visibility(def_kind: DefKind) -> bool {
1008    match def_kind {
1009        DefKind::Mod
1010        | DefKind::Struct
1011        | DefKind::Union
1012        | DefKind::Enum
1013        | DefKind::Variant
1014        | DefKind::Trait
1015        | DefKind::TyAlias
1016        | DefKind::ForeignTy
1017        | DefKind::TraitAlias
1018        | DefKind::AssocTy
1019        | DefKind::Fn
1020        | DefKind::Const { .. }
1021        | DefKind::Static { nested: false, .. }
1022        | DefKind::Ctor(..)
1023        | DefKind::AssocFn
1024        | DefKind::AssocConst { .. }
1025        | DefKind::Macro(..)
1026        | DefKind::Field => true,
1027        DefKind::Use
1028        | DefKind::ForeignMod
1029        | DefKind::TyParam
1030        | DefKind::ConstParam
1031        | DefKind::LifetimeParam
1032        | DefKind::AnonConst
1033        | DefKind::Static { nested: true, .. }
1034        | DefKind::OpaqueTy
1035        | DefKind::GlobalAsm
1036        | DefKind::Impl { .. }
1037        | DefKind::Closure
1038        | DefKind::ExternCrate
1039        | DefKind::SyntheticCoroutineBody => false,
1040    }
1041}
1042
1043fn should_encode_stability(def_kind: DefKind) -> bool {
1044    match def_kind {
1045        DefKind::Mod
1046        | DefKind::Ctor(..)
1047        | DefKind::Variant
1048        | DefKind::Field
1049        | DefKind::Struct
1050        | DefKind::AssocTy
1051        | DefKind::AssocFn
1052        | DefKind::AssocConst { .. }
1053        | DefKind::TyParam
1054        | DefKind::ConstParam
1055        | DefKind::Static { .. }
1056        | DefKind::Const { .. }
1057        | DefKind::Fn
1058        | DefKind::ForeignMod
1059        | DefKind::TyAlias
1060        | DefKind::OpaqueTy
1061        | DefKind::Enum
1062        | DefKind::Union
1063        | DefKind::Impl { .. }
1064        | DefKind::Trait
1065        | DefKind::TraitAlias
1066        | DefKind::Macro(..)
1067        | DefKind::ForeignTy => true,
1068        DefKind::Use
1069        | DefKind::LifetimeParam
1070        | DefKind::AnonConst
1071        | DefKind::GlobalAsm
1072        | DefKind::Closure
1073        | DefKind::ExternCrate
1074        | DefKind::SyntheticCoroutineBody => false,
1075    }
1076}
1077
1078/// Whether we should encode MIR. Return a pair, resp. for CTFE and for LLVM.
1079///
1080/// Computing, optimizing and encoding the MIR is a relatively expensive operation.
1081/// We want to avoid this work when not required. Therefore:
1082/// - we only compute `mir_for_ctfe` on items with const-eval semantics;
1083/// - we skip `optimized_mir` for check runs.
1084/// - we only encode `optimized_mir` that could be generated in other crates, that is, a code that
1085///   is either generic or has inline hint, and is reachable from the other crates (contained
1086///   in reachable set).
1087///
1088/// Note: Reachable set describes definitions that might be generated or referenced from other
1089/// crates and it can be used to limit optimized MIR that needs to be encoded. On the other hand,
1090/// the reachable set doesn't have much to say about which definitions might be evaluated at compile
1091/// time in other crates, so it cannot be used to omit CTFE MIR. For example, `f` below is
1092/// unreachable and yet it can be evaluated in other crates:
1093///
1094/// ```
1095/// const fn f() -> usize { 0 }
1096/// pub struct S { pub a: [usize; f()] }
1097/// ```
1098fn should_encode_mir(
1099    tcx: TyCtxt<'_>,
1100    reachable_set: &LocalDefIdSet,
1101    def_id: LocalDefId,
1102) -> (bool, bool) {
1103    match tcx.def_kind(def_id) {
1104        // instance_mir uses mir_for_ctfe rather than optimized_mir for constructors
1105        DefKind::Ctor(_, _) => (true, false),
1106        // Constants
1107        DefKind::AnonConst | DefKind::AssocConst { .. } | DefKind::Const { .. } => (true, false),
1108        // Coroutines require optimized MIR to compute layout.
1109        DefKind::Closure if tcx.is_coroutine(def_id.to_def_id()) => (false, true),
1110        DefKind::SyntheticCoroutineBody => (false, true),
1111        // Full-fledged functions + closures
1112        DefKind::AssocFn | DefKind::Fn | DefKind::Closure => {
1113            let opt = tcx.sess.opts.unstable_opts.always_encode_mir
1114                || (tcx.sess.opts.output_types.should_codegen()
1115                    && reachable_set.contains(&def_id)
1116                    && (tcx.generics_of(def_id).requires_monomorphization(tcx)
1117                        || tcx.cross_crate_inlinable(def_id)));
1118            // Comptime fns do not have optimized MIR at all.
1119            let opt =
1120                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 });
1121            // The function has a `const` modifier or is in a `const trait`.
1122            let is_const_fn = tcx.is_const_fn(def_id.to_def_id());
1123            (is_const_fn, opt)
1124        }
1125        // The others don't have MIR.
1126        _ => (false, false),
1127    }
1128}
1129
1130fn should_encode_variances<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, def_kind: DefKind) -> bool {
1131    match def_kind {
1132        DefKind::Struct
1133        | DefKind::Union
1134        | DefKind::Enum
1135        | DefKind::OpaqueTy
1136        | DefKind::Fn
1137        | DefKind::Ctor(..)
1138        | DefKind::AssocFn => true,
1139        DefKind::AssocTy => {
1140            // Only encode variances for RPITITs (for traits)
1141            #[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 { .. }))
1142        }
1143        DefKind::Mod
1144        | DefKind::Variant
1145        | DefKind::Field
1146        | DefKind::AssocConst { .. }
1147        | DefKind::TyParam
1148        | DefKind::ConstParam
1149        | DefKind::Static { .. }
1150        | DefKind::Const { .. }
1151        | DefKind::ForeignMod
1152        | DefKind::TyAlias
1153        | DefKind::Impl { .. }
1154        | DefKind::Trait
1155        | DefKind::TraitAlias
1156        | DefKind::Macro(..)
1157        | DefKind::ForeignTy
1158        | DefKind::Use
1159        | DefKind::LifetimeParam
1160        | DefKind::AnonConst
1161        | DefKind::GlobalAsm
1162        | DefKind::Closure
1163        | DefKind::ExternCrate
1164        | DefKind::SyntheticCoroutineBody => false,
1165    }
1166}
1167
1168fn should_encode_generics(def_kind: DefKind) -> bool {
1169    match def_kind {
1170        DefKind::Struct
1171        | DefKind::Union
1172        | DefKind::Enum
1173        | DefKind::Variant
1174        | DefKind::Trait
1175        | DefKind::TyAlias
1176        | DefKind::ForeignTy
1177        | DefKind::TraitAlias
1178        | DefKind::AssocTy
1179        | DefKind::Fn
1180        | DefKind::Const { .. }
1181        | DefKind::Static { .. }
1182        | DefKind::Ctor(..)
1183        | DefKind::AssocFn
1184        | DefKind::AssocConst { .. }
1185        | DefKind::AnonConst
1186        | DefKind::OpaqueTy
1187        | DefKind::Impl { .. }
1188        | DefKind::Field
1189        | DefKind::TyParam
1190        | DefKind::Closure
1191        | DefKind::SyntheticCoroutineBody => true,
1192        DefKind::Mod
1193        | DefKind::ForeignMod
1194        | DefKind::ConstParam
1195        | DefKind::Macro(..)
1196        | DefKind::Use
1197        | DefKind::LifetimeParam
1198        | DefKind::GlobalAsm
1199        | DefKind::ExternCrate => false,
1200    }
1201}
1202
1203fn should_encode_type(tcx: TyCtxt<'_>, def_id: LocalDefId, def_kind: DefKind) -> bool {
1204    match def_kind {
1205        DefKind::Struct
1206        | DefKind::Union
1207        | DefKind::Enum
1208        | DefKind::Variant
1209        | DefKind::Ctor(..)
1210        | DefKind::Field
1211        | DefKind::Fn
1212        | DefKind::Const { .. }
1213        | DefKind::Static { nested: false, .. }
1214        | DefKind::TyAlias
1215        | DefKind::ForeignTy
1216        | DefKind::Impl { .. }
1217        | DefKind::AssocFn
1218        | DefKind::AssocConst { .. }
1219        | DefKind::Closure
1220        | DefKind::ConstParam
1221        | DefKind::AnonConst
1222        | DefKind::SyntheticCoroutineBody => true,
1223
1224        DefKind::OpaqueTy => {
1225            let origin = tcx.local_opaque_ty_origin(def_id);
1226            if let hir::OpaqueTyOrigin::FnReturn { parent, .. }
1227            | hir::OpaqueTyOrigin::AsyncFn { parent, .. } = origin
1228                && let hir::Node::TraitItem(trait_item) = tcx.hir_node_by_def_id(parent)
1229                && let (_, hir::TraitFn::Required(..)) = trait_item.expect_fn()
1230            {
1231                false
1232            } else {
1233                true
1234            }
1235        }
1236
1237        DefKind::AssocTy => {
1238            let assoc_item = tcx.associated_item(def_id);
1239            match assoc_item.container {
1240                ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => true,
1241                ty::AssocContainer::Trait => assoc_item.defaultness(tcx).has_value(),
1242            }
1243        }
1244        DefKind::TyParam => {
1245            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!() };
1246            let hir::GenericParamKind::Type { default, .. } = param.kind else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
1247            default.is_some()
1248        }
1249
1250        DefKind::Trait
1251        | DefKind::TraitAlias
1252        | DefKind::Mod
1253        | DefKind::ForeignMod
1254        | DefKind::Macro(..)
1255        | DefKind::Static { nested: true, .. }
1256        | DefKind::Use
1257        | DefKind::LifetimeParam
1258        | DefKind::GlobalAsm
1259        | DefKind::ExternCrate => false,
1260    }
1261}
1262
1263fn should_encode_fn_sig(def_kind: DefKind) -> bool {
1264    match def_kind {
1265        DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) => true,
1266
1267        DefKind::Struct
1268        | DefKind::Union
1269        | DefKind::Enum
1270        | DefKind::Variant
1271        | DefKind::Field
1272        | DefKind::Const { .. }
1273        | DefKind::Static { .. }
1274        | DefKind::Ctor(..)
1275        | DefKind::TyAlias
1276        | DefKind::OpaqueTy
1277        | DefKind::ForeignTy
1278        | DefKind::Impl { .. }
1279        | DefKind::AssocConst { .. }
1280        | DefKind::Closure
1281        | DefKind::ConstParam
1282        | DefKind::AnonConst
1283        | DefKind::AssocTy
1284        | DefKind::TyParam
1285        | DefKind::Trait
1286        | DefKind::TraitAlias
1287        | DefKind::Mod
1288        | DefKind::ForeignMod
1289        | DefKind::Macro(..)
1290        | DefKind::Use
1291        | DefKind::LifetimeParam
1292        | DefKind::GlobalAsm
1293        | DefKind::ExternCrate
1294        | DefKind::SyntheticCoroutineBody => false,
1295    }
1296}
1297
1298fn should_encode_constness(def_kind: DefKind) -> bool {
1299    match def_kind {
1300        DefKind::Fn
1301        | DefKind::AssocFn
1302        | DefKind::Closure
1303        | DefKind::Ctor(_, CtorKind::Fn)
1304        | DefKind::Impl { of_trait: false } => true,
1305
1306        DefKind::Struct
1307        | DefKind::Union
1308        | DefKind::Enum
1309        | DefKind::Field
1310        | DefKind::Const { .. }
1311        | DefKind::AssocConst { .. }
1312        | DefKind::AnonConst
1313        | DefKind::Static { .. }
1314        | DefKind::TyAlias
1315        | DefKind::OpaqueTy
1316        | DefKind::Impl { .. }
1317        | DefKind::ForeignTy
1318        | DefKind::ConstParam
1319        | DefKind::AssocTy
1320        | DefKind::TyParam
1321        | DefKind::Trait
1322        | DefKind::TraitAlias
1323        | DefKind::Mod
1324        | DefKind::ForeignMod
1325        | DefKind::Macro(..)
1326        | DefKind::Use
1327        | DefKind::LifetimeParam
1328        | DefKind::GlobalAsm
1329        | DefKind::ExternCrate
1330        | DefKind::Ctor(_, CtorKind::Const)
1331        | DefKind::Variant
1332        | DefKind::SyntheticCoroutineBody => false,
1333    }
1334}
1335
1336fn should_encode_const(def_kind: DefKind) -> bool {
1337    match def_kind {
1338        // FIXME(mgca): should we remove Const and AssocConst here?
1339        DefKind::Const { .. } | DefKind::AssocConst { .. } | DefKind::AnonConst => true,
1340
1341        DefKind::Struct
1342        | DefKind::Union
1343        | DefKind::Enum
1344        | DefKind::Variant
1345        | DefKind::Ctor(..)
1346        | DefKind::Field
1347        | DefKind::Fn
1348        | DefKind::Static { .. }
1349        | DefKind::TyAlias
1350        | DefKind::OpaqueTy
1351        | DefKind::ForeignTy
1352        | DefKind::Impl { .. }
1353        | DefKind::AssocFn
1354        | DefKind::Closure
1355        | DefKind::ConstParam
1356        | DefKind::AssocTy
1357        | DefKind::TyParam
1358        | DefKind::Trait
1359        | DefKind::TraitAlias
1360        | DefKind::Mod
1361        | DefKind::ForeignMod
1362        | DefKind::Macro(..)
1363        | DefKind::Use
1364        | DefKind::LifetimeParam
1365        | DefKind::GlobalAsm
1366        | DefKind::ExternCrate
1367        | DefKind::SyntheticCoroutineBody => false,
1368    }
1369}
1370
1371fn should_encode_const_of_item<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, def_kind: DefKind) -> bool {
1372    // AssocConst ==> assoc item has value
1373    tcx.is_type_const(def_id)
1374        && (!#[allow(non_exhaustive_omitted_patterns)] match def_kind {
    DefKind::AssocConst { .. } => true,
    _ => false,
}matches!(def_kind, DefKind::AssocConst { .. }) || assoc_item_has_value(tcx, def_id))
1375}
1376
1377fn assoc_item_has_value<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool {
1378    let assoc_item = tcx.associated_item(def_id);
1379    match assoc_item.container {
1380        ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => true,
1381        ty::AssocContainer::Trait => assoc_item.defaultness(tcx).has_value(),
1382    }
1383}
1384
1385impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1386    fn encode_attrs(&mut self, def_id: LocalDefId) {
1387        let tcx = self.tcx;
1388        let mut state = AnalyzeAttrState {
1389            is_exported: tcx.effective_visibilities(()).is_exported(def_id),
1390            is_doc_hidden: false,
1391        };
1392        let attr_iter = tcx
1393            .hir_attrs(tcx.local_def_id_to_hir_id(def_id))
1394            .iter()
1395            .filter(|attr| analyze_attr(*attr, &mut state));
1396
1397        {
    {
        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);
1398
1399        let mut attr_flags = AttrFlags::empty();
1400        if state.is_doc_hidden {
1401            attr_flags |= AttrFlags::IS_DOC_HIDDEN;
1402        }
1403        self.tables.attr_flags.set(def_id.local_def_index, attr_flags);
1404    }
1405
1406    fn encode_def_ids(&mut self) {
1407        self.encode_info_for_mod(CRATE_DEF_ID);
1408
1409        // Proc-macro crates only export proc-macro items, which are looked
1410        // up using `proc_macro_data`
1411        if self.is_proc_macro {
1412            return;
1413        }
1414
1415        let tcx = self.tcx;
1416
1417        for local_id in tcx.iter_local_def_id() {
1418            let def_id = local_id.to_def_id();
1419            let def_kind = tcx.def_kind(local_id);
1420            self.tables.def_kind.set_some(def_id.index, def_kind);
1421
1422            // The `DefCollector` will sometimes create unnecessary `DefId`s
1423            // for trivial const arguments which are directly lowered to
1424            // `ConstArgKind::Path`. We never actually access this `DefId`
1425            // anywhere so we don't need to encode it for other crates.
1426            // FIXME(mgca): This probably isn't true, they probably are accessed, but, test case?
1427            if def_kind == DefKind::AnonConst
1428                && #[allow(non_exhaustive_omitted_patterns)] match tcx.hir_node_by_def_id(local_id)
    {
    hir::Node::ConstArg(_) => true,
    _ => false,
}matches!(tcx.hir_node_by_def_id(local_id), hir::Node::ConstArg(_))
1429            {
1430                continue;
1431            }
1432
1433            if def_kind == DefKind::Field
1434                && let hir::Node::Field(field) = tcx.hir_node_by_def_id(local_id)
1435                && let Some(anon) = field.default
1436            {
1437                {
    {
        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());
1438            }
1439
1440            if should_encode_span(def_kind) {
1441                let def_span = tcx.def_span(local_id);
1442                {
    {
        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);
1443            }
1444            if should_encode_attrs(def_kind) {
1445                self.encode_attrs(local_id);
1446            }
1447            if should_encode_expn_that_defined(def_kind) {
1448                {
    {
        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));
1449            }
1450            if should_encode_span(def_kind)
1451                && let Some(ident_span) = tcx.def_ident_span(def_id)
1452            {
1453                {
    {
        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);
1454            }
1455            if def_kind.has_codegen_attrs() {
1456                {
    {
        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));
1457            }
1458            if should_encode_visibility(def_kind) {
1459                let vis = self
1460                    .tcx
1461                    .local_visibility(local_id)
1462                    .map_id(|mod_id| mod_id.to_local_def_id().local_def_index);
1463                {
    {
        let value = vis;
        let lazy = self.lazy(value);
        self.tables.visibility.set_some(def_id.index, lazy);
    }
};record!(self.tables.visibility[def_id] <- vis);
1464            }
1465            if should_encode_stability(def_kind) {
1466                self.encode_stability(def_id);
1467                self.encode_const_stability(def_id);
1468                self.encode_default_body_stability(def_id);
1469                self.encode_deprecation(def_id);
1470            }
1471            if should_encode_variances(tcx, def_id, def_kind) {
1472                let v = self.tcx.variances_of(def_id);
1473                {
    {
        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);
1474            }
1475            if should_encode_fn_sig(def_kind) {
1476                {
    {
        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));
1477            }
1478            if should_encode_generics(def_kind) {
1479                let g = tcx.generics_of(def_id);
1480                {
    {
        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);
1481                {
    {
        let value = self.tcx.explicit_predicates_of(def_id);
        let lazy = self.lazy(value);
        self.tables.explicit_predicates_of.set_some(def_id.index, lazy);
    }
};record!(self.tables.explicit_predicates_of[def_id] <- self.tcx.explicit_predicates_of(def_id));
1482                let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
1483                {
    {
        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);
1484
1485                for param in &g.own_params {
1486                    if let ty::GenericParamDefKind::Const { has_default: true, .. } = param.kind {
1487                        let default = self.tcx.const_param_default(param.def_id);
1488                        {
    {
        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);
1489                    }
1490                }
1491            }
1492            if tcx.is_conditionally_const(def_id) {
1493                {
    {
        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));
1494            }
1495            if should_encode_type(tcx, local_id, def_kind) {
1496                {
    {
        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));
1497            }
1498            if should_encode_constness(def_kind) {
1499                let constness = self.tcx.constness(def_id);
1500                self.tables.constness.set(def_id.index, constness);
1501            }
1502            if let DefKind::Fn | DefKind::AssocFn = def_kind {
1503                let asyncness = tcx.asyncness(def_id);
1504                self.tables.asyncness.set(def_id.index, asyncness);
1505                {
    {
        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));
1506            }
1507            if let Some(name) = tcx.intrinsic(def_id) {
1508                {
    {
        let value = name;
        let lazy = self.lazy(value);
        self.tables.intrinsic.set_some(def_id.index, lazy);
    }
};record!(self.tables.intrinsic[def_id] <- name);
1509            }
1510            if let DefKind::TyParam | DefKind::Trait = def_kind {
1511                let default = self.tcx.object_lifetime_default(def_id);
1512                {
    {
        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);
1513            }
1514            if let DefKind::Trait = def_kind {
1515                {
    {
        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));
1516                {
    {
        let value =
            self.tcx.explicit_super_predicates_of(def_id).skip_binder();
        let lazy = self.lazy_array(value);
        self.tables.explicit_super_predicates_of.set(def_id.index, lazy);
    }
};record_defaulted_array!(self.tables.explicit_super_predicates_of[def_id] <-
1517                    self.tcx.explicit_super_predicates_of(def_id).skip_binder());
1518                {
    {
        let value =
            self.tcx.explicit_implied_predicates_of(def_id).skip_binder();
        let lazy = self.lazy_array(value);
        self.tables.explicit_implied_predicates_of.set(def_id.index, lazy);
    }
};record_defaulted_array!(self.tables.explicit_implied_predicates_of[def_id] <-
1519                    self.tcx.explicit_implied_predicates_of(def_id).skip_binder());
1520                let module_children = self.tcx.module_children_local(local_id);
1521                {
    {
        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] <-
1522                    module_children.iter().map(|child| child.res.def_id().index));
1523                if self.tcx.is_const_trait(def_id) {
1524                    {
    {
        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]
1525                        <- self.tcx.explicit_implied_const_bounds(def_id).skip_binder());
1526                }
1527            }
1528            if let DefKind::TraitAlias = def_kind {
1529                {
    {
        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));
1530                {
    {
        let value =
            self.tcx.explicit_super_predicates_of(def_id).skip_binder();
        let lazy = self.lazy_array(value);
        self.tables.explicit_super_predicates_of.set(def_id.index, lazy);
    }
};record_defaulted_array!(self.tables.explicit_super_predicates_of[def_id] <-
1531                    self.tcx.explicit_super_predicates_of(def_id).skip_binder());
1532                {
    {
        let value =
            self.tcx.explicit_implied_predicates_of(def_id).skip_binder();
        let lazy = self.lazy_array(value);
        self.tables.explicit_implied_predicates_of.set(def_id.index, lazy);
    }
};record_defaulted_array!(self.tables.explicit_implied_predicates_of[def_id] <-
1533                    self.tcx.explicit_implied_predicates_of(def_id).skip_binder());
1534            }
1535            if let DefKind::Trait | DefKind::Impl { .. } = def_kind {
1536                let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1537                {
    {
        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] <-
1538                    associated_item_def_ids.iter().map(|&def_id| {
1539                        assert!(def_id.is_local());
1540                        def_id.index
1541                    })
1542                );
1543                for &def_id in associated_item_def_ids {
1544                    self.encode_info_for_assoc_item(def_id);
1545                }
1546            }
1547            if let DefKind::Closure | DefKind::SyntheticCoroutineBody = def_kind
1548                && let Some(coroutine_kind) = self.tcx.coroutine_kind(def_id)
1549            {
1550                self.tables.coroutine_kind.set(def_id.index, Some(coroutine_kind))
1551            }
1552            if def_kind == DefKind::Closure
1553                && tcx.type_of(def_id).skip_binder().is_coroutine_closure()
1554            {
1555                let coroutine_for_closure = self.tcx.coroutine_for_closure(def_id);
1556                self.tables
1557                    .coroutine_for_closure
1558                    .set_some(def_id.index, coroutine_for_closure.into());
1559
1560                // If this async closure has a by-move body, record it too.
1561                if tcx.needs_coroutine_by_move_body_def_id(coroutine_for_closure) {
1562                    self.tables.coroutine_by_move_body_def_id.set_some(
1563                        coroutine_for_closure.index,
1564                        self.tcx.coroutine_by_move_body_def_id(coroutine_for_closure).into(),
1565                    );
1566                }
1567            }
1568            if let DefKind::Static { .. } = def_kind {
1569                if !self.tcx.is_foreign_item(def_id) {
1570                    let data = self.tcx.eval_static_initializer(def_id).unwrap();
1571                    {
    {
        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);
1572                }
1573            }
1574            if let DefKind::Enum | DefKind::Struct | DefKind::Union = def_kind {
1575                self.encode_info_for_adt(local_id);
1576            }
1577            if let DefKind::Mod = def_kind {
1578                self.encode_info_for_mod(local_id);
1579            }
1580            if let DefKind::Macro(_) = def_kind {
1581                self.encode_info_for_macro(local_id);
1582            }
1583            if let DefKind::TyAlias = def_kind {
1584                self.tables
1585                    .type_alias_is_checked
1586                    .set(def_id.index, self.tcx.type_alias_is_checked(def_id));
1587                if self.tcx.type_alias_is_checked(def_id) {
1588                    {
    {
        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));
1589                }
1590            }
1591            if let DefKind::OpaqueTy = def_kind {
1592                self.encode_explicit_item_bounds(def_id);
1593                self.encode_explicit_item_self_bounds(def_id);
1594                {
    {
        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));
1595                self.encode_precise_capturing_args(def_id);
1596                if tcx.is_conditionally_const(def_id) {
1597                    {
    {
        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]
1598                        <- tcx.explicit_implied_const_bounds(def_id).skip_binder());
1599                }
1600                {
    {
        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));
1601            }
1602            if let DefKind::AssocTy = def_kind {
1603                let assoc_item = tcx.associated_item(def_id);
1604                match assoc_item.container {
1605                    ty::AssocContainer::Trait => {
1606                        {
    {
        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));
1607                    }
1608                    ty::AssocContainer::InherentImpl => {
1609                        {
    {
        let value = tcx.args_known_to_outlive_alias_params(def_id);
        let lazy = self.lazy(value);
        self.tables.args_known_to_outlive_alias_params.set_some(def_id.index,
            lazy);
    }
};record!(self.tables.args_known_to_outlive_alias_params[def_id] <- tcx.args_known_to_outlive_alias_params(def_id));
1610                    }
1611                    ty::AssocContainer::TraitImpl(_) => {}
1612                }
1613            }
1614            if let DefKind::AnonConst = def_kind {
1615                {
    {
        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));
1616            }
1617            if should_encode_const_of_item(self.tcx, def_id, def_kind) {
1618                {
    {
        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));
1619            }
1620            if tcx.impl_method_has_trait_impl_trait_tys(def_id)
1621                && let Ok(table) = self.tcx.collect_return_position_impl_trait_in_trait_tys(def_id)
1622            {
1623                {
    {
        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);
1624            }
1625            if let DefKind::Impl { .. } | DefKind::Trait = def_kind {
1626                let table = tcx.associated_types_for_impl_traits_in_trait_or_impl(def_id);
1627                {
    {
        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);
1628            }
1629        }
1630
1631        for (def_id, impls) in &tcx.crate_inherent_impls(()).0.inherent_impls {
1632            {
    {
        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| {
1633                assert!(def_id.is_local());
1634                def_id.index
1635            }));
1636        }
1637
1638        for (def_id, res_map) in &tcx.resolutions(()).doc_link_resolutions {
1639            {
    {
        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);
1640        }
1641
1642        for (def_id, traits) in &tcx.resolutions(()).doc_link_traits_in_scope {
1643            {
    {
        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);
1644        }
1645    }
1646
1647    fn encode_externally_implementable_items(&mut self) -> LazyArray<EiiMapEncodedKeyValue> {
1648        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
1649        let externally_implementable_items = self.tcx.externally_implementable_items(LOCAL_CRATE);
1650
1651        self.lazy_array(externally_implementable_items.iter().map(
1652            |(foreign_item, (decl, impls))| {
1653                (
1654                    *foreign_item,
1655                    (decl.clone(), impls.iter().map(|(impl_did, i)| (*impl_did, *i)).collect()),
1656                )
1657            },
1658        ))
1659    }
1660
1661    #[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(1661u32),
                                    ::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);
                }
                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))]
1662    fn encode_info_for_adt(&mut self, local_def_id: LocalDefId) {
1663        let def_id = local_def_id.to_def_id();
1664        let tcx = self.tcx;
1665        let adt_def = tcx.adt_def(def_id);
1666        record!(self.tables.repr_options[def_id] <- adt_def.repr());
1667
1668        let params_in_repr = self.tcx.params_in_repr(def_id);
1669        record!(self.tables.params_in_repr[def_id] <- params_in_repr);
1670
1671        if adt_def.is_enum() {
1672            let module_children = tcx.module_children_local(local_def_id);
1673            record_array!(self.tables.module_children_non_reexports[def_id] <-
1674                module_children.iter().map(|child| child.res.def_id().index));
1675        } else {
1676            // For non-enum, there is only one variant, and its def_id is the adt's.
1677            debug_assert_eq!(adt_def.variants().len(), 1);
1678            debug_assert_eq!(adt_def.non_enum_variant().def_id, def_id);
1679            // Therefore, the loop over variants will encode its fields as the adt's children.
1680        }
1681
1682        for (idx, variant) in adt_def.variants().iter_enumerated() {
1683            let data = VariantData {
1684                discr: variant.discr,
1685                idx,
1686                ctor: variant.ctor.map(|(kind, def_id)| (kind, def_id.index)),
1687                is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1688            };
1689            record!(self.tables.variant_data[variant.def_id] <- data);
1690
1691            record_array!(self.tables.associated_item_or_field_def_ids[variant.def_id] <- variant.fields.iter().map(|f| {
1692                assert!(f.did.is_local());
1693                f.did.index
1694            }));
1695
1696            for field in &variant.fields {
1697                self.tables.safety.set(field.did.index, field.safety);
1698            }
1699
1700            if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor {
1701                let fn_sig = tcx.fn_sig(ctor_def_id);
1702                // FIXME only encode signature for ctor_def_id
1703                record!(self.tables.fn_sig[variant.def_id] <- fn_sig);
1704            }
1705        }
1706
1707        if let Some(destructor) = tcx.adt_destructor(local_def_id) {
1708            record!(self.tables.adt_destructor[def_id] <- destructor);
1709        }
1710
1711        if let Some(destructor) = tcx.adt_async_destructor(local_def_id) {
1712            record!(self.tables.adt_async_destructor[def_id] <- destructor);
1713        }
1714    }
1715
1716    #[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(1716u32),
                                    ::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))]
1717    fn encode_info_for_mod(&mut self, local_def_id: LocalDefId) {
1718        let tcx = self.tcx;
1719        let def_id = local_def_id.to_def_id();
1720
1721        // If we are encoding a proc-macro crates, `encode_info_for_mod` will
1722        // only ever get called for the crate root. We still want to encode
1723        // the crate root for consistency with other crates (some of the resolver
1724        // code uses it). However, we skip encoding anything relating to child
1725        // items - we encode information about proc-macros later on.
1726        if self.is_proc_macro {
1727            // Encode this here because we don't do it in encode_def_ids.
1728            record!(self.tables.expn_that_defined[def_id] <- tcx.expn_that_defined(local_def_id));
1729        } else {
1730            let module_children = tcx.module_children_local(local_def_id);
1731
1732            record_array!(self.tables.module_children_non_reexports[def_id] <-
1733                module_children.iter().filter(|child| child.reexport_chain.is_empty())
1734                    .map(|child| child.res.def_id().index));
1735
1736            record_defaulted_array!(self.tables.module_children_reexports[def_id] <-
1737                module_children.iter().filter(|child| !child.reexport_chain.is_empty()));
1738
1739            let ambig_module_children = tcx
1740                .resolutions(())
1741                .ambig_module_children
1742                .get(&local_def_id)
1743                .map_or_default(|v| &v[..]);
1744            record_defaulted_array!(self.tables.ambig_module_children[def_id] <-
1745                ambig_module_children);
1746        }
1747    }
1748
1749    fn encode_explicit_item_bounds(&mut self, def_id: DefId) {
1750        {
    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:1750",
                        "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(1750u32),
                        ::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);
1751        let bounds = self.tcx.explicit_item_bounds(def_id).skip_binder();
1752        {
    {
        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);
1753    }
1754
1755    fn encode_explicit_item_self_bounds(&mut self, def_id: DefId) {
1756        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/rmeta/encoder.rs:1756",
                        "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/encoder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1756u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("EncodeContext::encode_explicit_item_self_bounds({0:?})",
                                                    def_id) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("EncodeContext::encode_explicit_item_self_bounds({:?})", def_id);
1757        let bounds = self.tcx.explicit_item_self_bounds(def_id).skip_binder();
1758        {
    {
        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);
1759    }
1760
1761    #[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(1761u32),
                                    ::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))]
1762    fn encode_info_for_assoc_item(&mut self, def_id: DefId) {
1763        let tcx = self.tcx;
1764        let item = tcx.associated_item(def_id);
1765
1766        if matches!(item.container, AssocContainer::Trait | AssocContainer::TraitImpl(_)) {
1767            self.tables.defaultness.set(def_id.index, item.defaultness(tcx));
1768        }
1769
1770        record!(self.tables.assoc_container[def_id] <- item.container);
1771
1772        if let AssocContainer::Trait = item.container
1773            && item.is_type()
1774        {
1775            self.encode_explicit_item_bounds(def_id);
1776            self.encode_explicit_item_self_bounds(def_id);
1777            if tcx.is_conditionally_const(def_id) {
1778                record_defaulted_array!(self.tables.explicit_implied_const_bounds[def_id]
1779                    <- self.tcx.explicit_implied_const_bounds(def_id).skip_binder());
1780            }
1781        }
1782        if let ty::AssocKind::Type { data: ty::AssocTypeData::Rpitit(rpitit_info) } = item.kind {
1783            record!(self.tables.opt_rpitit_info[def_id] <- rpitit_info);
1784            if matches!(rpitit_info, ty::ImplTraitInTraitData::Trait { .. }) {
1785                record_array!(
1786                    self.tables.assumed_wf_types_for_rpitit[def_id]
1787                        <- self.tcx.assumed_wf_types_for_rpitit(def_id)
1788                );
1789                self.encode_precise_capturing_args(def_id);
1790            }
1791        }
1792    }
1793
1794    fn encode_precise_capturing_args(&mut self, def_id: DefId) {
1795        let Some(precise_capturing_args) = self.tcx.rendered_precise_capturing_args(def_id) else {
1796            return;
1797        };
1798
1799        {
    {
        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);
1800    }
1801
1802    fn encode_mir(&mut self) {
1803        if self.is_proc_macro {
1804            return;
1805        }
1806
1807        let tcx = self.tcx;
1808        let reachable_set = tcx.reachable_set(());
1809
1810        let keys_and_jobs = tcx.mir_keys(()).iter().filter_map(|&def_id| {
1811            let (encode_const, encode_opt) = should_encode_mir(tcx, reachable_set, def_id);
1812            if encode_const || encode_opt { Some((def_id, encode_const, encode_opt)) } else { None }
1813        });
1814        for (def_id, encode_const, encode_opt) in keys_and_jobs {
1815            if true {
    if !(encode_const || encode_opt) {
        ::core::panicking::panic("assertion failed: encode_const || encode_opt")
    };
};debug_assert!(encode_const || encode_opt);
1816
1817            {
    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:1817",
                        "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(1817u32),
                        ::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);
1818            if encode_opt {
1819                {
    {
        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));
1820                self.tables
1821                    .cross_crate_inlinable
1822                    .set(def_id.to_def_id().index, self.tcx.cross_crate_inlinable(def_id));
1823                {
    {
        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()]
1824                    <- tcx.closure_saved_names_of_captured_variables(def_id));
1825
1826                if self.tcx.is_coroutine(def_id.to_def_id())
1827                    && let Some(witnesses) = tcx.mir_coroutine_witnesses(def_id)
1828                {
1829                    {
    {
        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);
1830                }
1831            }
1832            let mut is_trivial = false;
1833            if encode_const {
1834                if let Some((val, ty)) = tcx.trivial_const(def_id) {
1835                    is_trivial = true;
1836                    {
    {
        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));
1837                } else {
1838                    is_trivial = false;
1839                    {
    {
        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));
1840                }
1841
1842                // FIXME(generic_const_exprs): this feels wrong to have in `encode_mir`
1843                let abstract_const = tcx.thir_abstract_const(def_id);
1844                if let Ok(Some(abstract_const)) = abstract_const {
1845                    {
    {
        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);
1846                }
1847
1848                if should_encode_const(tcx.def_kind(def_id)) {
1849                    let qualifs = tcx.mir_const_qualif(def_id);
1850                    {
    {
        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);
1851                    let body = tcx.hir_maybe_body_owned_by(def_id);
1852                    if let Some(body) = body {
1853                        let const_data = rendered_const(self.tcx, &body, def_id);
1854                        {
    {
        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);
1855                    }
1856                }
1857            }
1858            if !is_trivial {
1859                {
    {
        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));
1860            }
1861
1862            if self.tcx.is_coroutine(def_id.to_def_id())
1863                && let Some(witnesses) = tcx.mir_coroutine_witnesses(def_id)
1864            {
1865                {
    {
        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);
1866            }
1867        }
1868
1869        // Encode all the deduced parameter attributes for everything that has MIR, even for items
1870        // that can't be inlined. But don't if we aren't optimizing in non-incremental mode, to
1871        // save the query traffic.
1872        if tcx.sess.opts.output_types.should_codegen()
1873            && tcx.sess.opts.optimize != OptLevel::No
1874            && tcx.sess.opts.incremental.is_none()
1875        {
1876            for &local_def_id in tcx.mir_keys(()) {
1877                if let DefKind::AssocFn | DefKind::Fn = tcx.def_kind(local_def_id) {
1878                    {
    {
        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()] <-
1879                        self.tcx.deduced_param_attrs(local_def_id.to_def_id()));
1880                }
1881            }
1882        }
1883    }
1884
1885    #[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(1885u32),
                                    ::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))]
1886    fn encode_stability(&mut self, def_id: DefId) {
1887        // The query lookup can take a measurable amount of time in crates with many items. Check if
1888        // the stability attributes are even enabled before using their queries.
1889        if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1890            if let Some(stab) = self.tcx.lookup_stability(def_id) {
1891                record!(self.tables.lookup_stability[def_id] <- stab)
1892            }
1893        }
1894    }
1895
1896    #[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(1896u32),
                                    ::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))]
1897    fn encode_const_stability(&mut self, def_id: DefId) {
1898        // The query lookup can take a measurable amount of time in crates with many items. Check if
1899        // the stability attributes are even enabled before using their queries.
1900        if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1901            if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1902                record!(self.tables.lookup_const_stability[def_id] <- stab)
1903            }
1904        }
1905    }
1906
1907    #[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(1907u32),
                                    ::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))]
1908    fn encode_default_body_stability(&mut self, def_id: DefId) {
1909        // The query lookup can take a measurable amount of time in crates with many items. Check if
1910        // the stability attributes are even enabled before using their queries.
1911        if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1912            if let Some(stab) = self.tcx.lookup_default_body_stability(def_id) {
1913                record!(self.tables.lookup_default_body_stability[def_id] <- stab)
1914            }
1915        }
1916    }
1917
1918    #[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(1918u32),
                                    ::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))]
1919    fn encode_deprecation(&mut self, def_id: DefId) {
1920        if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1921            record!(self.tables.lookup_deprecation_entry[def_id] <- depr);
1922        }
1923    }
1924
1925    #[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(1925u32),
                                    ::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))]
1926    fn encode_info_for_macro(&mut self, def_id: LocalDefId) {
1927        let tcx = self.tcx;
1928
1929        let (_, macro_def, _) = tcx.hir_expect_item(def_id).expect_macro();
1930        self.tables.is_macro_rules.set(def_id.local_def_index, macro_def.macro_rules);
1931        record!(self.tables.macro_definition[def_id.to_def_id()] <- &*macro_def.body);
1932    }
1933
1934    fn encode_native_libraries(&mut self) -> LazyArray<NativeLib> {
1935        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
1936        let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1937        self.lazy_array(used_libraries.iter())
1938    }
1939
1940    fn encode_foreign_modules(&mut self) -> LazyArray<ForeignModule> {
1941        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
1942        let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1943        self.lazy_array(foreign_modules.iter().map(|(_, m)| m).cloned())
1944    }
1945
1946    fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) {
1947        let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1948        let mut expn_data_table: TableBuilder<_, _> = Default::default();
1949        let mut expn_hash_table: TableBuilder<_, _> = Default::default();
1950
1951        self.hygiene_ctxt.encode(
1952            &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table),
1953            |(this, syntax_contexts, _, _), index, ctxt_data| {
1954                syntax_contexts.set_some(index, this.lazy(ctxt_data));
1955            },
1956            |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| {
1957                if let Some(index) = index.as_local() {
1958                    expn_data_table.set_some(index.as_raw(), this.lazy(expn_data));
1959                    expn_hash_table.set_some(index.as_raw(), this.lazy(hash));
1960                }
1961            },
1962        );
1963
1964        (
1965            syntax_contexts.encode(&mut self.opaque),
1966            expn_data_table.encode(&mut self.opaque),
1967            expn_hash_table.encode(&mut self.opaque),
1968        )
1969    }
1970
1971    fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
1972        let is_proc_macro = self.tcx.crate_types().contains(&CrateType::ProcMacro);
1973        if is_proc_macro {
1974            let tcx = self.tcx;
1975            let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index;
1976            let stability = tcx.lookup_stability(CRATE_DEF_ID);
1977            for (i, span) in self.tcx.sess.proc_macro_quoted_spans() {
1978                let span = self.lazy(span);
1979                self.tables.proc_macro_quoted_spans.set_some(i, span);
1980            }
1981
1982            self.tables.def_kind.set_some(LOCAL_CRATE.as_def_id().index, DefKind::Mod);
1983            {
    {
        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()));
1984            self.encode_attrs(LOCAL_CRATE.as_def_id().expect_local());
1985            let vis = tcx
1986                .local_visibility(CRATE_DEF_ID)
1987                .map_id(|mod_id| mod_id.to_local_def_id().local_def_index);
1988            {
    {
        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);
1989            if let Some(stability) = stability {
1990                {
    {
        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);
1991            }
1992            self.encode_deprecation(LOCAL_CRATE.as_def_id());
1993            if let Some(res_map) = tcx.resolutions(()).doc_link_resolutions.get(&CRATE_MOD_ID) {
1994                {
    {
        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);
1995            }
1996            if let Some(traits) = tcx.resolutions(()).doc_link_traits_in_scope.get(&CRATE_MOD_ID) {
1997                {
    {
        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);
1998            }
1999
2000            let mut macros = ::alloc::vec::Vec::new()vec![];
2001
2002            // Normally, this information is encoded when we walk the items
2003            // defined in this crate. However, we skip doing that for proc-macro crates,
2004            // so we manually encode just the information that we need
2005            for &proc_macro in &tcx.resolutions(()).proc_macros {
2006                let id = proc_macro;
2007                let proc_macro = tcx.local_def_id_to_hir_id(proc_macro);
2008                let mut name = tcx.hir_name(proc_macro);
2009                let span = tcx.hir_span(proc_macro);
2010                // Proc-macros may have attributes like `#[allow_internal_unstable]`,
2011                // so downstream crates need access to them.
2012                let attrs = tcx.hir_attrs(proc_macro);
2013                let (macro_kind, kind) = if {
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(ProcMacro) => {
                            break 'done Some(());
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, ProcMacro) {
2014                    (MacroKind::Bang, ProcMacroKind::Bang { name: name.as_str().to_owned() })
2015                } else if {
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(ProcMacroAttribute) => {
                            break 'done Some(());
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, ProcMacroAttribute) {
2016                    (MacroKind::Attr, ProcMacroKind::Attr { name: name.as_str().to_owned() })
2017                } else if let Some((trait_name, helper_attrs)) = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(ProcMacroDerive {
                    trait_name, helper_attrs }) => {
                    break 'done Some((trait_name, helper_attrs));
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs,
2018                    ProcMacroDerive { trait_name, helper_attrs } => (trait_name, helper_attrs))
2019                {
2020                    name = *trait_name;
2021                    (
2022                        MacroKind::Derive,
2023                        ProcMacroKind::CustomDerive {
2024                            trait_name: name.as_str().to_owned(),
2025                            attributes: helper_attrs
2026                                .iter()
2027                                .map(|attr| attr.as_str().to_owned())
2028                                .collect(),
2029                        },
2030                    )
2031                } else {
2032                    ::rustc_middle::util::bug::bug_fmt(format_args!("Unknown proc-macro type for item {0:?}",
        id));bug!("Unknown proc-macro type for item {:?}", id);
2033                };
2034
2035                macros.push((id.local_def_index, self.lazy(kind)));
2036
2037                let mut def_key = self.tcx.hir_def_key(id);
2038                def_key.disambiguated_data.data = DefPathData::MacroNs(name);
2039
2040                let def_id = id.to_def_id();
2041                self.tables.def_kind.set_some(def_id.index, DefKind::Macro(macro_kind.into()));
2042                self.encode_attrs(id);
2043                {
    {
        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);
2044                {
    {
        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);
2045                {
    {
        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);
2046                {
    {
        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);
2047                if let Some(stability) = stability {
2048                    {
    {
        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);
2049                }
2050            }
2051
2052            let macros = self.lazy_array(macros);
2053
2054            Some(ProcMacroData { proc_macro_decls_static, stability, macros })
2055        } else {
2056            None
2057        }
2058    }
2059
2060    fn encode_debugger_visualizers(&mut self) -> LazyArray<DebuggerVisualizerFile> {
2061        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2062        self.lazy_array(
2063            self.tcx
2064                .debugger_visualizers(LOCAL_CRATE)
2065                .iter()
2066                // Erase the path since it may contain privacy sensitive data
2067                // that we don't want to end up in crate metadata.
2068                // The path is only needed for the local crate because of
2069                // `--emit dep-info`.
2070                .map(DebuggerVisualizerFile::path_erased),
2071        )
2072    }
2073
2074    fn encode_crate_deps(&mut self) -> LazyArray<CrateDep> {
2075        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2076
2077        let deps = self
2078            .tcx
2079            .crates(())
2080            .iter()
2081            .map(|&cnum| {
2082                let dep = CrateDep {
2083                    name: self.tcx.crate_name(cnum),
2084                    hash: self.tcx.crate_hash(cnum),
2085                    host_hash: self.tcx.crate_host_hash(cnum),
2086                    kind: self.tcx.crate_dep_kind(cnum),
2087                    extra_filename: self.tcx.extra_filename(cnum).clone(),
2088                    is_private: self.tcx.is_private_dep(cnum),
2089                };
2090                (cnum, dep)
2091            })
2092            .collect::<Vec<_>>();
2093
2094        {
2095            // Sanity-check the crate numbers
2096            let mut expected_cnum = 1;
2097            for &(n, _) in &deps {
2098                {
    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));
2099                expected_cnum += 1;
2100            }
2101        }
2102
2103        // We're just going to write a list of crate 'name-hash-version's, with
2104        // the assumption that they are numbered 1 to n.
2105        // FIXME (#2166): This is not nearly enough to support correct versioning
2106        // but is enough to get transitive crate dependencies working.
2107        self.lazy_array(deps.iter().map(|(_, dep)| dep))
2108    }
2109
2110    fn encode_target_modifiers(&mut self) -> LazyArray<TargetModifier> {
2111        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2112        let tcx = self.tcx;
2113        self.lazy_array(tcx.sess.opts.gather_target_modifiers())
2114    }
2115
2116    fn encode_enabled_denied_partial_mitigations(&mut self) -> LazyArray<DeniedPartialMitigation> {
2117        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2118        let tcx = self.tcx;
2119        self.lazy_array(tcx.sess.gather_enabled_denied_partial_mitigations())
2120    }
2121
2122    fn encode_lib_features(&mut self) -> LazyArray<(Symbol, FeatureStability)> {
2123        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2124        let tcx = self.tcx;
2125        let lib_features = tcx.lib_features(LOCAL_CRATE);
2126        self.lazy_array(lib_features.to_sorted_vec())
2127    }
2128
2129    fn encode_stability_implications(&mut self) -> LazyArray<(Symbol, Symbol)> {
2130        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2131        let tcx = self.tcx;
2132        let implications = tcx.stability_implications(LOCAL_CRATE);
2133        let sorted = implications.to_sorted_stable_ord();
2134        self.lazy_array(sorted.into_iter().map(|(k, v)| (*k, *v)))
2135    }
2136
2137    fn encode_diagnostic_items(&mut self) -> LazyArray<(Symbol, DefIndex)> {
2138        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2139        let tcx = self.tcx;
2140        let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id;
2141        self.lazy_array(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
2142    }
2143
2144    fn encode_lang_items(&mut self) -> LazyArray<(DefIndex, LangItem)> {
2145        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2146        let lang_items = self.tcx.lang_items().iter();
2147        self.lazy_array(lang_items.filter_map(|(lang_item, def_id)| {
2148            def_id.as_local().map(|id| (id.local_def_index, lang_item))
2149        }))
2150    }
2151
2152    fn encode_lang_items_missing(&mut self) -> LazyArray<LangItem> {
2153        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2154        let tcx = self.tcx;
2155        self.lazy_array(&tcx.lang_items().missing)
2156    }
2157
2158    fn encode_stripped_cfg_items(&mut self) -> LazyArray<StrippedCfgItem<DefIndex>> {
2159        self.lazy_array(
2160            self.tcx
2161                .stripped_cfg_items(LOCAL_CRATE)
2162                .into_iter()
2163                .map(|item| item.clone().map_scope_id(|def_id| def_id.index)),
2164        )
2165    }
2166
2167    fn encode_traits(&mut self) -> LazyArray<DefIndex> {
2168        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2169        self.lazy_array(self.tcx.traits(LOCAL_CRATE).iter().map(|def_id| def_id.index))
2170    }
2171
2172    /// Encodes an index, mapping each trait to its (local) implementations.
2173    #[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(2173u32),
                                    ::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);
                        }
                    };
                    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))]
2174    fn encode_impls(&mut self) -> LazyArray<TraitImpls> {
2175        empty_proc_macro!(self);
2176        let tcx = self.tcx;
2177        let mut trait_impls: FxIndexMap<DefId, Vec<(DefIndex, Option<SimplifiedType>)>> =
2178            FxIndexMap::default();
2179
2180        for id in tcx.hir_free_items() {
2181            let DefKind::Impl { of_trait } = tcx.def_kind(id.owner_id) else {
2182                continue;
2183            };
2184            let def_id = id.owner_id.to_def_id();
2185
2186            if of_trait {
2187                let header = tcx.impl_trait_header(def_id);
2188                record!(self.tables.impl_trait_header[def_id] <- header);
2189
2190                self.tables.defaultness.set(def_id.index, tcx.defaultness(def_id));
2191
2192                let trait_ref = header.trait_ref.instantiate_identity().skip_norm_wip();
2193                let simplified_self_ty = fast_reject::simplify_type(
2194                    self.tcx,
2195                    trait_ref.self_ty(),
2196                    TreatParams::InstantiateWithInfer,
2197                );
2198                trait_impls
2199                    .entry(trait_ref.def_id)
2200                    .or_default()
2201                    .push((id.owner_id.def_id.local_def_index, simplified_self_ty));
2202
2203                let trait_def = tcx.trait_def(trait_ref.def_id);
2204                if let Ok(mut an) = trait_def.ancestors(tcx, def_id)
2205                    && let Some(specialization_graph::Node::Impl(parent)) = an.nth(1)
2206                {
2207                    self.tables.impl_parent.set_some(def_id.index, parent.into());
2208                }
2209
2210                // if this is an impl of `CoerceUnsized`, create its
2211                // "unsized info", else just store None
2212                if tcx.is_lang_item(trait_ref.def_id, LangItem::CoerceUnsized) {
2213                    let coerce_unsized_info = tcx.coerce_unsized_info(def_id).unwrap();
2214                    record!(self.tables.coerce_unsized_info[def_id] <- coerce_unsized_info);
2215                }
2216            }
2217        }
2218
2219        let trait_impls: Vec<_> = trait_impls
2220            .into_iter()
2221            .map(|(trait_def_id, impls)| TraitImpls {
2222                trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
2223                impls: self.lazy_array(&impls),
2224            })
2225            .collect();
2226
2227        self.lazy_array(&trait_impls)
2228    }
2229
2230    #[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(2230u32),
                                    ::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))]
2231    fn encode_incoherent_impls(&mut self) -> LazyArray<IncoherentImpls> {
2232        empty_proc_macro!(self);
2233        let tcx = self.tcx;
2234
2235        let all_impls: Vec<_> = tcx
2236            .crate_inherent_impls(())
2237            .0
2238            .incoherent_impls
2239            .iter()
2240            .map(|(&simp, impls)| IncoherentImpls {
2241                self_ty: self.lazy(simp),
2242                impls: self.lazy_array(impls.iter().map(|def_id| def_id.local_def_index)),
2243            })
2244            .collect();
2245
2246        self.lazy_array(&all_impls)
2247    }
2248
2249    fn encode_exportable_items(&mut self) -> LazyArray<DefIndex> {
2250        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2251        self.lazy_array(self.tcx.exportable_items(LOCAL_CRATE).iter().map(|def_id| def_id.index))
2252    }
2253
2254    fn encode_stable_order_of_exportable_impls(&mut self) -> LazyArray<(DefIndex, usize)> {
2255        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2256        let stable_order_of_exportable_impls =
2257            self.tcx.stable_order_of_exportable_impls(LOCAL_CRATE);
2258        self.lazy_array(
2259            stable_order_of_exportable_impls.iter().map(|(def_id, idx)| (def_id.index, *idx)),
2260        )
2261    }
2262
2263    // Encodes all symbols exported from this crate into the metadata.
2264    //
2265    // This pass is seeded off the reachability list calculated in the
2266    // middle::reachable module but filters out items that either don't have a
2267    // symbol associated with them (they weren't translated) or if they're an FFI
2268    // definition (as that's not defined in this crate).
2269    fn encode_exported_symbols(
2270        &mut self,
2271        exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportInfo)],
2272    ) -> LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)> {
2273        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2274
2275        self.lazy_array(exported_symbols.iter().cloned())
2276    }
2277
2278    fn encode_dylib_dependency_formats(&mut self) -> LazyArray<Option<LinkagePreference>> {
2279        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2280        let formats = self.tcx.dependency_formats(());
2281        if let Some(arr) = formats.get(&CrateType::Dylib) {
2282            return self.lazy_array(arr.iter().skip(1 /* skip LOCAL_CRATE */).map(
2283                |slot| match *slot {
2284                    Linkage::NotLinked | Linkage::IncludedFromDylib => None,
2285
2286                    Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
2287                    Linkage::Static => Some(LinkagePreference::RequireStatic),
2288                },
2289            ));
2290        }
2291        LazyArray::default()
2292    }
2293}
2294
2295/// Used to prefetch queries which will be needed later by metadata encoding.
2296/// Only a subset of the queries are actually prefetched to keep this code smaller.
2297fn prefetch_mir(tcx: TyCtxt<'_>) {
2298    if !tcx.sess.opts.output_types.should_codegen() {
2299        // We won't emit MIR, so don't prefetch it.
2300        return;
2301    }
2302
2303    let reachable_set = tcx.reachable_set(());
2304    par_for_each_in(tcx.mir_keys(()), |&&def_id| {
2305        if tcx.is_trivial_const(def_id) {
2306            return;
2307        }
2308        let (encode_const, encode_opt) = should_encode_mir(tcx, reachable_set, def_id);
2309
2310        if encode_const {
2311            tcx.ensure_done().mir_for_ctfe(def_id);
2312        }
2313        if encode_opt {
2314            tcx.ensure_done().optimized_mir(def_id);
2315        }
2316        if encode_opt || encode_const {
2317            tcx.ensure_done().promoted_mir(def_id);
2318        }
2319    })
2320}
2321
2322// NOTE(eddyb) The following comment was preserved for posterity, even
2323// though it's no longer relevant as EBML (which uses nested & tagged
2324// "documents") was replaced with a scheme that can't go out of bounds.
2325//
2326// And here we run into yet another obscure archive bug: in which metadata
2327// loaded from archives may have trailing garbage bytes. Awhile back one of
2328// our tests was failing sporadically on the macOS 64-bit builders (both nopt
2329// and opt) by having ebml generate an out-of-bounds panic when looking at
2330// metadata.
2331//
2332// Upon investigation it turned out that the metadata file inside of an rlib
2333// (and ar archive) was being corrupted. Some compilations would generate a
2334// metadata file which would end in a few extra bytes, while other
2335// compilations would not have these extra bytes appended to the end. These
2336// extra bytes were interpreted by ebml as an extra tag, so they ended up
2337// being interpreted causing the out-of-bounds.
2338//
2339// The root cause of why these extra bytes were appearing was never
2340// discovered, and in the meantime the solution we're employing is to insert
2341// the length of the metadata to the start of the metadata. Later on this
2342// will allow us to slice the metadata to the precise length that we just
2343// generated regardless of trailing bytes that end up in it.
2344
2345pub struct EncodedMetadata {
2346    // The declaration order matters because `full_metadata` should be dropped
2347    // before `_temp_dir`.
2348    full_metadata: Option<Mmap>,
2349    // This is an optional stub metadata containing only the crate header.
2350    // The header should be very small, so we load it directly into memory.
2351    stub_metadata: Option<Vec<u8>>,
2352    // The path containing the metadata, to record as work product.
2353    path: Option<Box<Path>>,
2354    // We need to carry MaybeTempDir to avoid deleting the temporary
2355    // directory while accessing the Mmap.
2356    _temp_dir: Option<MaybeTempDir>,
2357}
2358
2359impl EncodedMetadata {
2360    #[inline]
2361    pub fn from_path(
2362        path: PathBuf,
2363        stub_path: Option<PathBuf>,
2364        temp_dir: Option<MaybeTempDir>,
2365    ) -> std::io::Result<Self> {
2366        let file = std::fs::File::open(&path)?;
2367        let file_metadata = file.metadata()?;
2368        if file_metadata.len() == 0 {
2369            return Ok(Self {
2370                full_metadata: None,
2371                stub_metadata: None,
2372                path: None,
2373                _temp_dir: None,
2374            });
2375        }
2376        let full_mmap = unsafe { Some(Mmap::map(file)?) };
2377
2378        let stub =
2379            if let Some(stub_path) = stub_path { Some(std::fs::read(stub_path)?) } else { None };
2380
2381        Ok(Self {
2382            full_metadata: full_mmap,
2383            stub_metadata: stub,
2384            path: Some(path.into()),
2385            _temp_dir: temp_dir,
2386        })
2387    }
2388
2389    #[inline]
2390    pub fn full(&self) -> &[u8] {
2391        &self.full_metadata.as_deref().unwrap_or_default()
2392    }
2393
2394    #[inline]
2395    pub fn stub_or_full(&self) -> &[u8] {
2396        self.stub_metadata.as_deref().unwrap_or(self.full())
2397    }
2398
2399    #[inline]
2400    pub fn path(&self) -> Option<&Path> {
2401        self.path.as_deref()
2402    }
2403}
2404
2405impl<S: Encoder> Encodable<S> for EncodedMetadata {
2406    fn encode(&self, s: &mut S) {
2407        self.stub_metadata.encode(s);
2408
2409        let slice = self.full();
2410        slice.encode(s)
2411    }
2412}
2413
2414impl<D: Decoder> Decodable<D> for EncodedMetadata {
2415    fn decode(d: &mut D) -> Self {
2416        let stub = <Option<Vec<u8>>>::decode(d);
2417
2418        let len = d.read_usize();
2419        let full_metadata = if len > 0 {
2420            let mut mmap = MmapMut::map_anon(len).unwrap();
2421            mmap.copy_from_slice(d.read_raw_bytes(len));
2422            Some(mmap.make_read_only().unwrap())
2423        } else {
2424            None
2425        };
2426
2427        Self { full_metadata, stub_metadata: stub, path: None, _temp_dir: None }
2428    }
2429}
2430
2431#[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(2431u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("path")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("path");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ref_path")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ref_path");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ref_path)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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