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