Skip to main content

rustc_metadata/rmeta/
encoder.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let def_id = local_def_id.to_def_id();
            let tcx = self.tcx;
            let adt_def = tcx.adt_def(def_id);
            self.table_writer().repr_options(local_def_id, adt_def.repr());
            let params_in_repr = tcx.params_in_repr(def_id);
            self.table_writer().params_in_repr(local_def_id, params_in_repr);
            if adt_def.is_enum() {
                let module_children = tcx.module_children_local(local_def_id);
                self.table_writer().module_children_non_reexports(local_def_id,
                    module_children.iter().map(|child|
                            child.res.def_id().expect_local()));
            } 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 variant_id = variant.def_id.expect_local();
                let data =
                    VariantData {
                        discr: variant.discr,
                        idx,
                        ctor: variant.ctor.map(|(kind, def_id)|
                                (kind, def_id.expect_local())),
                        is_non_exhaustive: variant.is_field_list_non_exhaustive(),
                    };
                self.table_writer().variant_data(variant_id, data);
                self.table_writer().associated_item_or_field_def_ids(variant_id,
                    variant.fields.iter().map(|f| f.did.expect_local()));
                for field in &variant.fields {
                    let field_id = field.did.expect_local();
                    self.table_writer().safety(field_id, field.safety);
                    self.table_writer().mut_restriction(field_id,
                        field.mut_restriction);
                }
                if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor {
                    let fn_sig = tcx.fn_sig(ctor_def_id);
                    self.table_writer().fn_sig(variant_id, fn_sig);
                }
            }
            if let Some(destructor) = tcx.adt_destructor(local_def_id) {
                self.table_writer().adt_destructor(local_def_id, destructor);
            }
            if let Some(destructor) = tcx.adt_async_destructor(local_def_id) {
                self.table_writer().adt_async_destructor(local_def_id,
                    destructor);
            }
        }
    }
}#[instrument(level = "trace", skip(self))]
1784    fn encode_info_for_adt(&mut self, local_def_id: LocalDefId) {
1785        let def_id = local_def_id.to_def_id();
1786        let tcx = self.tcx;
1787        let adt_def = tcx.adt_def(def_id);
1788        self.table_writer().repr_options(local_def_id, adt_def.repr());
1789
1790        let params_in_repr = tcx.params_in_repr(def_id);
1791        self.table_writer().params_in_repr(local_def_id, params_in_repr);
1792
1793        if adt_def.is_enum() {
1794            let module_children = tcx.module_children_local(local_def_id);
1795            self.table_writer().module_children_non_reexports(
1796                local_def_id,
1797                module_children.iter().map(|child| child.res.def_id().expect_local()),
1798            );
1799        } else {
1800            // For non-enum, there is only one variant, and its def_id is the adt's.
1801            debug_assert_eq!(adt_def.variants().len(), 1);
1802            debug_assert_eq!(adt_def.non_enum_variant().def_id, def_id);
1803            // Therefore, the loop over variants will encode its fields as the adt's children.
1804        }
1805
1806        for (idx, variant) in adt_def.variants().iter_enumerated() {
1807            let variant_id = variant.def_id.expect_local();
1808
1809            let data = VariantData {
1810                discr: variant.discr,
1811                idx,
1812                ctor: variant.ctor.map(|(kind, def_id)| (kind, def_id.expect_local())),
1813                is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1814            };
1815            self.table_writer().variant_data(variant_id, data);
1816
1817            self.table_writer().associated_item_or_field_def_ids(
1818                variant_id,
1819                variant.fields.iter().map(|f| f.did.expect_local()),
1820            );
1821
1822            for field in &variant.fields {
1823                let field_id = field.did.expect_local();
1824                self.table_writer().safety(field_id, field.safety);
1825                self.table_writer().mut_restriction(field_id, field.mut_restriction);
1826            }
1827
1828            if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor {
1829                let fn_sig = tcx.fn_sig(ctor_def_id);
1830                // FIXME only encode signature for ctor_def_id
1831                self.table_writer().fn_sig(variant_id, fn_sig);
1832            }
1833        }
1834
1835        if let Some(destructor) = tcx.adt_destructor(local_def_id) {
1836            self.table_writer().adt_destructor(local_def_id, destructor);
1837        }
1838
1839        if let Some(destructor) = tcx.adt_async_destructor(local_def_id) {
1840            self.table_writer().adt_async_destructor(local_def_id, destructor);
1841        }
1842    }
1843
1844    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("encode_info_for_mod",
                                    "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1844u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("local_def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("local_def_id");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&local_def_id)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx;
            if self.is_proc_macro {
                self.table_writer().expn_that_defined(local_def_id,
                    tcx.expn_that_defined(local_def_id));
            } else {
                let module_children = tcx.module_children_local(local_def_id);
                self.table_writer().module_children_non_reexports(local_def_id,
                    module_children.iter().filter(|child|
                                child.reexport_chain.is_empty()).map(|child|
                            child.res.def_id().expect_local()));
                self.table_writer().module_children_reexports(local_def_id,
                    module_children.iter().filter(|child|
                            !child.reexport_chain.is_empty()));
                let ambig_module_children =
                    tcx.resolutions(()).ambig_module_children.get(&local_def_id).map_or_default(|v|
                            &v[..]);
                self.table_writer().ambig_module_children(local_def_id,
                    ambig_module_children);
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1845    fn encode_info_for_mod(&mut self, local_def_id: LocalDefId) {
1846        let tcx = self.tcx;
1847
1848        // If we are encoding a proc-macro crates, `encode_info_for_mod` will
1849        // only ever get called for the crate root. We still want to encode
1850        // the crate root for consistency with other crates (some of the resolver
1851        // code uses it). However, we skip encoding anything relating to child
1852        // items - we encode information about proc-macros later on.
1853        if self.is_proc_macro {
1854            // Encode this here because we don't do it in encode_def_ids.
1855            self.table_writer()
1856                .expn_that_defined(local_def_id, tcx.expn_that_defined(local_def_id));
1857        } else {
1858            let module_children = tcx.module_children_local(local_def_id);
1859
1860            self.table_writer().module_children_non_reexports(
1861                local_def_id,
1862                module_children
1863                    .iter()
1864                    .filter(|child| child.reexport_chain.is_empty())
1865                    .map(|child| child.res.def_id().expect_local()),
1866            );
1867
1868            self.table_writer().module_children_reexports(
1869                local_def_id,
1870                module_children.iter().filter(|child| !child.reexport_chain.is_empty()),
1871            );
1872
1873            let ambig_module_children = tcx
1874                .resolutions(())
1875                .ambig_module_children
1876                .get(&local_def_id)
1877                .map_or_default(|v| &v[..]);
1878            self.table_writer().ambig_module_children(local_def_id, ambig_module_children);
1879        }
1880    }
1881
1882    fn encode_explicit_item_bounds(&mut self, def_id: LocalDefId) {
1883        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_metadata/src/rmeta/encoder.rs:1883",
                        "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1883u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("EncodeContext::encode_explicit_item_bounds({0:?})",
                                                    def_id) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id);
1884        let bounds = self.tcx.explicit_item_bounds(def_id).skip_binder();
1885        self.table_writer().explicit_item_bounds(def_id, bounds);
1886    }
1887
1888    fn encode_explicit_item_self_bounds(&mut self, def_id: LocalDefId) {
1889        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_metadata/src/rmeta/encoder.rs:1889",
                        "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1889u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("EncodeContext::encode_explicit_item_self_bounds({0:?})",
                                                    def_id) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("EncodeContext::encode_explicit_item_self_bounds({:?})", def_id);
1890        let bounds = self.tcx.explicit_item_self_bounds(def_id).skip_binder();
1891        self.table_writer().explicit_item_self_bounds(def_id, bounds);
1892    }
1893
1894    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("encode_info_for_assoc_item",
                                    "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1894u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx;
            let item = tcx.associated_item(def_id);
            if #[allow(non_exhaustive_omitted_patterns)] match item.container
                    {
                    AssocContainer::Trait | AssocContainer::TraitImpl(_) =>
                        true,
                    _ => false,
                } {
                self.table_writer().defaultness(def_id,
                    item.defaultness(tcx));
            }
            self.table_writer().assoc_container(def_id, item.container);
            if let Some(item_name) = item.opt_name() {
                self.table_writer().opt_item_name(def_id, Some(item_name));
            }
            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) {
                    self.table_writer().explicit_implied_const_bounds(def_id,
                        tcx.explicit_implied_const_bounds(def_id).skip_binder());
                }
            }
            if let ty::AssocKind::Type {
                    data: ty::AssocTypeData::Rpitit(rpitit_info) } = item.kind {
                self.table_writer().opt_rpitit_info(def_id, rpitit_info);
                if #[allow(non_exhaustive_omitted_patterns)] match rpitit_info
                        {
                        ty::ImplTraitInTraitData::Trait { .. } => true,
                        _ => false,
                    } {
                    self.table_writer().assumed_wf_types_for_rpitit(def_id,
                        tcx.assumed_wf_types_for_rpitit(def_id));
                    self.encode_precise_capturing_args(def_id);
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1895    fn encode_info_for_assoc_item(&mut self, def_id: LocalDefId) {
1896        let tcx = self.tcx;
1897        let item = tcx.associated_item(def_id);
1898
1899        if matches!(item.container, AssocContainer::Trait | AssocContainer::TraitImpl(_)) {
1900            self.table_writer().defaultness(def_id, item.defaultness(tcx));
1901        }
1902
1903        self.table_writer().assoc_container(def_id, item.container);
1904
1905        if let Some(item_name) = item.opt_name() {
1906            self.table_writer().opt_item_name(def_id, Some(item_name));
1907        }
1908
1909        if let AssocContainer::Trait = item.container
1910            && item.is_type()
1911        {
1912            self.encode_explicit_item_bounds(def_id);
1913            self.encode_explicit_item_self_bounds(def_id);
1914            if tcx.is_conditionally_const(def_id) {
1915                self.table_writer().explicit_implied_const_bounds(
1916                    def_id,
1917                    tcx.explicit_implied_const_bounds(def_id).skip_binder(),
1918                );
1919            }
1920        }
1921        if let ty::AssocKind::Type { data: ty::AssocTypeData::Rpitit(rpitit_info) } = item.kind {
1922            self.table_writer().opt_rpitit_info(def_id, rpitit_info);
1923            if matches!(rpitit_info, ty::ImplTraitInTraitData::Trait { .. }) {
1924                self.table_writer()
1925                    .assumed_wf_types_for_rpitit(def_id, tcx.assumed_wf_types_for_rpitit(def_id));
1926                self.encode_precise_capturing_args(def_id);
1927            }
1928        }
1929    }
1930
1931    fn encode_precise_capturing_args(&mut self, def_id: LocalDefId) {
1932        let Some(precise_capturing_args) = self.tcx.rendered_precise_capturing_args(def_id) else {
1933            return;
1934        };
1935
1936        self.table_writer().rendered_precise_capturing_args(def_id, precise_capturing_args);
1937    }
1938
1939    fn encode_mir(&mut self) {
1940        if self.is_proc_macro {
1941            return;
1942        }
1943
1944        let tcx = self.tcx;
1945        // skip reachable_set calculation when not doing codegen. It is only used when checking
1946        // whether something could be monomorphized downstream
1947        let reachable_set =
1948            tcx.sess.opts.output_types.should_codegen().then(|| tcx.reachable_set(()));
1949
1950        let keys_and_jobs = tcx.mir_keys(()).iter().filter_map(|&def_id| {
1951            let (encode_const, encode_opt) = should_encode_mir(tcx, reachable_set, def_id);
1952            if encode_const || encode_opt { Some((def_id, encode_const, encode_opt)) } else { None }
1953        });
1954        for (def_id, encode_const, encode_opt) in keys_and_jobs {
1955            if true {
    if !(encode_const || encode_opt) {
        ::core::panicking::panic("assertion failed: encode_const || encode_opt")
    };
};debug_assert!(encode_const || encode_opt);
1956
1957            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_metadata/src/rmeta/encoder.rs:1957",
                        "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                        ::tracing_core::__macro_support::Option::Some(1957u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("EntryBuilder::encode_mir({0:?})",
                                                    def_id) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("EntryBuilder::encode_mir({:?})", def_id);
1958            if encode_opt {
1959                self.table_writer().optimized_mir(def_id, tcx.optimized_mir(def_id));
1960
1961                self.table_writer()
1962                    .cross_crate_inlinable(def_id, tcx.cross_crate_inlinable(def_id));
1963
1964                self.table_writer().closure_saved_names_of_captured_variables(
1965                    def_id,
1966                    tcx.closure_saved_names_of_captured_variables(def_id),
1967                );
1968
1969                if tcx.is_coroutine(def_id.to_def_id())
1970                    && let Some(witnesses) = tcx.mir_coroutine_witnesses(def_id)
1971                {
1972                    self.table_writer().mir_coroutine_witnesses(def_id, witnesses);
1973                }
1974            }
1975            let mut is_trivial = false;
1976            if encode_const {
1977                if let Some((val, ty)) = tcx.trivial_const(def_id) {
1978                    is_trivial = true;
1979                    self.table_writer().trivial_const(def_id, (val, ty));
1980                } else {
1981                    is_trivial = false;
1982                    self.table_writer().mir_for_ctfe(def_id, tcx.mir_for_ctfe(def_id));
1983                }
1984
1985                // FIXME(generic_const_exprs): this feels wrong to have in `encode_mir`
1986                let abstract_const = tcx.thir_abstract_const(def_id);
1987                if let Ok(Some(abstract_const)) = abstract_const {
1988                    self.table_writer().thir_abstract_const(def_id, abstract_const);
1989                }
1990
1991                if should_encode_const(tcx.def_kind(def_id)) {
1992                    let qualifs = tcx.mir_const_qualif(def_id);
1993                    self.table_writer().mir_const_qualif(def_id, qualifs);
1994                    let body = tcx.hir_maybe_body_owned_by(def_id);
1995                    if let Some(body) = body {
1996                        let const_data = rendered_const(tcx, &body, def_id);
1997                        self.table_writer().rendered_const(def_id, const_data);
1998                    }
1999                }
2000            }
2001            if !is_trivial {
2002                self.table_writer().promoted_mir(def_id, tcx.promoted_mir(def_id));
2003            }
2004
2005            if tcx.is_coroutine(def_id.to_def_id())
2006                && let Some(witnesses) = tcx.mir_coroutine_witnesses(def_id)
2007            {
2008                self.table_writer().mir_coroutine_witnesses(def_id, witnesses);
2009            }
2010        }
2011
2012        // Encode all the deduced parameter attributes for everything that has MIR, even for items
2013        // that can't be inlined. But don't if we aren't optimizing in non-incremental mode, to
2014        // save the query traffic.
2015        if tcx.sess.opts.output_types.should_codegen()
2016            && tcx.sess.opts.optimize != OptLevel::No
2017            && tcx.sess.opts.incremental.is_none()
2018        {
2019            for &local_def_id in tcx.mir_keys(()) {
2020                if let DefKind::AssocFn | DefKind::Fn = tcx.def_kind(local_def_id) {
2021                    self.table_writer().deduced_param_attrs(
2022                        local_def_id,
2023                        tcx.deduced_param_attrs(local_def_id.to_def_id()),
2024                    );
2025                }
2026            }
2027        }
2028    }
2029
2030    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("encode_stability",
                                    "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2030u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let tcx = self.tcx;
            let (_, macro_def, _) =
                tcx.hir_expect_item(def_id).expect_macro();
            self.table_writer().is_macro_rules(def_id, macro_def.macro_rules);
            self.table_writer().macro_definition(def_id, &*macro_def.body);
        }
    }
}#[instrument(level = "debug", skip(self))]
2071    fn encode_info_for_macro(&mut self, def_id: LocalDefId) {
2072        let tcx = self.tcx;
2073
2074        let (_, macro_def, _) = tcx.hir_expect_item(def_id).expect_macro();
2075        self.table_writer().is_macro_rules(def_id, macro_def.macro_rules);
2076        self.table_writer().macro_definition(def_id, &*macro_def.body);
2077    }
2078
2079    fn encode_native_libraries(&mut self) -> LazyArray<NativeLib> {
2080        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2081        let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
2082        self.lazy_array(used_libraries.iter())
2083    }
2084
2085    fn encode_foreign_modules(&mut self) -> LazyArray<ForeignModule> {
2086        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2087        let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
2088        self.lazy_array(foreign_modules.iter().map(|(_, m)| m).cloned())
2089    }
2090
2091    fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) {
2092        let mut syntax_contexts: TableBuilder<_, _, _> = Default::default();
2093        let mut expn_data_table: TableBuilder<_, _, _> = Default::default();
2094        let mut expn_hash_table: TableBuilder<_, _, _> = Default::default();
2095
2096        HygieneEncodeContext::encode(
2097            &Rc::clone(&self.hygiene_ctxt),
2098            &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table),
2099            |(this, syntax_contexts, _, _), ctxt, ctxt_data| {
2100                let ctxt = this.syntax_context_remapping.map_id(ctxt);
2101                syntax_contexts.set_some(ctxt, this.lazy(ctxt_data));
2102            },
2103            |(this, _, expn_data_table, expn_hash_table), expn_id, expn_data, hash| {
2104                if let Some(expn_id) = expn_id.as_local() {
2105                    let expn_index = this.local_expn_id_remapping.map_id(expn_id);
2106
2107                    expn_data_table.set_some(expn_index, this.lazy(expn_data.expect("local expn")));
2108                    expn_hash_table.set_some(expn_index, this.lazy(hash));
2109                }
2110            },
2111        );
2112
2113        (
2114            syntax_contexts.encode(&mut self.opaque),
2115            expn_data_table.encode(&mut self.opaque),
2116            expn_hash_table.encode(&mut self.opaque),
2117        )
2118    }
2119
2120    fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
2121        let is_proc_macro = self.tcx.crate_types().contains(&CrateType::ProcMacro);
2122        if is_proc_macro {
2123            let tcx = self.tcx;
2124            let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap();
2125            let proc_macro_decls_static = self.lazy(proc_macro_decls_static);
2126
2127            let stability = tcx.lookup_stability(CRATE_DEF_ID);
2128
2129            self.table_writer().def_kind(CRATE_DEF_ID, DefKind::Mod);
2130            self.table_writer().def_span(CRATE_DEF_ID, tcx.def_span(CRATE_DEF_ID.to_def_id()));
2131            self.encode_attrs(CRATE_DEF_ID);
2132            let vis = tcx.local_visibility(CRATE_DEF_ID).map_id(|mod_id| mod_id.to_local_def_id());
2133            self.table_writer().visibility(CRATE_DEF_ID, vis);
2134            if let Some(stability) = stability {
2135                self.table_writer().lookup_stability(CRATE_DEF_ID, stability);
2136            }
2137            self.encode_deprecation(CRATE_DEF_ID);
2138            if let Some(res_map) = tcx.resolutions(()).doc_link_resolutions.get(&CRATE_MOD_ID) {
2139                self.table_writer().doc_link_resolutions(CRATE_DEF_ID, res_map);
2140            }
2141            if let Some(traits) = tcx.resolutions(()).doc_link_traits_in_scope.get(&CRATE_MOD_ID) {
2142                self.table_writer().doc_link_traits_in_scope(CRATE_DEF_ID, traits);
2143            }
2144
2145            let mut macros = ::alloc::vec::Vec::new()vec![];
2146
2147            // Normally, this information is encoded when we walk the items
2148            // defined in this crate. However, we skip doing that for proc-macro crates,
2149            // so we manually encode just the information that we need
2150            for &proc_macro in &tcx.resolutions(()).proc_macros {
2151                let id = proc_macro;
2152                let proc_macro = tcx.local_def_id_to_hir_id(proc_macro);
2153                let mut name = tcx.hir_name(proc_macro);
2154                let span = tcx.hir_span(proc_macro);
2155                // Proc-macros may have attributes like `#[allow_internal_unstable]`,
2156                // so downstream crates need access to them.
2157                let attrs = tcx.hir_attrs(proc_macro);
2158                let (macro_kind, kind) = if {
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(ProcMacro) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Tool { .. } |
                            ::rustc_attr_ir::Attribute::DeriveHelper(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, ProcMacro) {
2159                    (MacroKind::Bang, ProcMacroKind::Bang { name: name.as_str().to_owned() })
2160                } else if {
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use ::rustc_attr_ir::AttributeKind::*;
                    let i: &::rustc_attr_ir::Attribute = i;
                    match i {
                        ::rustc_attr_ir::Attribute::Parsed(ProcMacroAttribute) => {
                            break 'done Some(());
                        }
                        ::rustc_attr_ir::Attribute::Tool { .. } |
                            ::rustc_attr_ir::Attribute::DeriveHelper(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, ProcMacroAttribute) {
2161                    (MacroKind::Attr, ProcMacroKind::Attr { name: name.as_str().to_owned() })
2162                } else if let Some((trait_name, helper_attrs)) = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use ::rustc_attr_ir::AttributeKind::*;
            let i: &::rustc_attr_ir::Attribute = i;
            match i {
                ::rustc_attr_ir::Attribute::Parsed(ProcMacroDerive {
                    trait_name, helper_attrs }) => {
                    break 'done Some((trait_name, helper_attrs));
                }
                ::rustc_attr_ir::Attribute::Tool { .. } |
                    ::rustc_attr_ir::Attribute::DeriveHelper(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs,
2163                    ProcMacroDerive { trait_name, helper_attrs } => (trait_name, helper_attrs))
2164                {
2165                    name = *trait_name;
2166                    (
2167                        MacroKind::Derive,
2168                        ProcMacroKind::CustomDerive {
2169                            trait_name: name.as_str().to_owned(),
2170                            attributes: helper_attrs
2171                                .iter()
2172                                .map(|attr| attr.as_str().to_owned())
2173                                .collect(),
2174                        },
2175                    )
2176                } else {
2177                    ::rustc_span::macros::bug_impl(None,
    format_args!("Unknown proc-macro type for item {0:?}", id),
    Location::caller());bug!("Unknown proc-macro type for item {:?}", id);
2178                };
2179
2180                macros.push((id, self.lazy(kind)));
2181
2182                let mut def_key = tcx.hir_def_key(id);
2183                def_key.disambiguated_data.data = DefPathData::MacroNs(name);
2184
2185                self.table_writer().def_kind(id, DefKind::Macro(macro_kind.into()));
2186
2187                self.encode_attrs(id);
2188                self.table_writer().def_keys(id, def_key);
2189                self.table_writer().def_ident_span(id, span);
2190                self.table_writer().def_span(id, span);
2191                self.table_writer().visibility(id, ty::Visibility::Public);
2192                if let Some(stability) = stability {
2193                    self.table_writer().lookup_stability(id, stability);
2194                }
2195            }
2196
2197            let macros = self.lazy_array(macros);
2198
2199            let mut proc_macro_quoted_spans = TableBuilder::default();
2200            for (i, span) in tcx.sess.proc_macro_quoted_spans() {
2201                proc_macro_quoted_spans.set_some(i, self.lazy(span));
2202            }
2203
2204            let proc_macro_quoted_spans = proc_macro_quoted_spans.encode(&mut self.opaque);
2205
2206            Some(ProcMacroData {
2207                proc_macro_decls_static,
2208                stability,
2209                macros,
2210                proc_macro_quoted_spans,
2211            })
2212        } else {
2213            None
2214        }
2215    }
2216
2217    fn encode_debugger_visualizers(&mut self) -> LazyArray<DebuggerVisualizerFile> {
2218        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2219        self.lazy_array(
2220            self.tcx
2221                .debugger_visualizers(LOCAL_CRATE)
2222                .iter()
2223                // Erase the path since it may contain privacy sensitive data
2224                // that we don't want to end up in crate metadata.
2225                // The path is only needed for the local crate because of
2226                // `--emit dep-info`.
2227                .map(DebuggerVisualizerFile::path_erased),
2228        )
2229    }
2230
2231    fn encode_crate_deps(&mut self) -> LazyArray<CrateDep> {
2232        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2233
2234        let deps = self
2235            .tcx
2236            .crates(())
2237            .iter()
2238            .map(|&cnum| {
2239                let dep = CrateDep {
2240                    name: self.tcx.crate_name(cnum),
2241                    hash: self.tcx.crate_hash(cnum),
2242                    host_hash: self.tcx.crate_host_hash(cnum),
2243                    kind: self.tcx.crate_dep_kind(cnum),
2244                    is_private: self.tcx.is_private_dep(cnum),
2245                };
2246                (cnum, dep)
2247            })
2248            .collect::<Vec<_>>();
2249
2250        {
2251            // Sanity-check the crate numbers
2252            let mut expected_cnum = 1;
2253            for &(n, _) in &deps {
2254                {
    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));
2255                expected_cnum += 1;
2256            }
2257        }
2258
2259        // We're just going to write a list of crate 'name-hash-version's, with
2260        // the assumption that they are numbered 1 to n.
2261        // FIXME (#2166): This is not nearly enough to support correct versioning
2262        // but is enough to get transitive crate dependencies working.
2263        self.lazy_array(deps.iter().map(|(_, dep)| dep))
2264    }
2265
2266    fn encode_target_modifiers(&mut self) -> LazyArray<TargetModifier> {
2267        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2268        let tcx = self.tcx;
2269        self.lazy_array(tcx.sess.opts.gather_target_modifiers())
2270    }
2271
2272    fn encode_enabled_denied_partial_mitigations(&mut self) -> LazyArray<DeniedPartialMitigation> {
2273        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2274        let tcx = self.tcx;
2275        self.lazy_array(tcx.sess.gather_enabled_denied_partial_mitigations())
2276    }
2277
2278    fn encode_lib_features(&mut self) -> LazyArray<(Symbol, FeatureStability)> {
2279        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2280        let tcx = self.tcx;
2281        let lib_features = tcx.lib_features(LOCAL_CRATE);
2282        self.lazy_array(lib_features.to_sorted_vec())
2283    }
2284
2285    fn encode_stability_implications(&mut self) -> LazyArray<(Symbol, Symbol)> {
2286        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2287        let tcx = self.tcx;
2288        let implications = tcx.stability_implications(LOCAL_CRATE);
2289        let sorted = implications.to_sorted_stable_ord();
2290        self.lazy_array(sorted.into_iter().map(|(k, v)| (*k, *v)))
2291    }
2292
2293    fn encode_canonical_symbols(&mut self) -> LazyArray<(Symbol, LocalDefId)> {
2294        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2295        let tcx = self.tcx;
2296        let canonical_symbols = &tcx.canonical_symbols(LOCAL_CRATE);
2297        self.lazy_array(canonical_symbols.iter().map(|cs| (cs.symbol, cs.def_id.expect_local())))
2298    }
2299
2300    fn encode_diagnostic_items(&mut self) -> LazyArray<(Symbol, LocalDefId)> {
2301        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2302        let tcx = self.tcx;
2303        let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id;
2304        self.lazy_array(
2305            diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.expect_local())),
2306        )
2307    }
2308
2309    fn encode_fake_doc_items(&mut self) -> LazyArray<LocalDefId> {
2310        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2311        let tcx = self.tcx;
2312        let fake_doc_items = &tcx.fake_doc_items(LOCAL_CRATE);
2313        self.lazy_array(fake_doc_items.iter().map(|cs| cs.expect_local()))
2314    }
2315
2316    fn encode_lang_items(&mut self) -> LazyArray<(LocalDefId, LangItem)> {
2317        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2318        let lang_items = self.tcx.lang_items().iter();
2319        self.lazy_array(
2320            lang_items
2321                .filter_map(|(lang_item, def_id)| def_id.as_local().map(|id| (id, lang_item))),
2322        )
2323    }
2324
2325    fn encode_lang_items_missing(&mut self) -> LazyArray<LangItem> {
2326        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2327        let tcx = self.tcx;
2328        self.lazy_array(&tcx.lang_items().missing)
2329    }
2330
2331    fn encode_stripped_cfg_items(&mut self) -> LazyArray<StrippedCfgItem<LocalDefId>> {
2332        self.lazy_array(
2333            self.tcx
2334                .stripped_cfg_items(LOCAL_CRATE)
2335                .into_iter()
2336                .map(|item| item.clone().map_scope_id(|def_id| def_id.expect_local())),
2337        )
2338    }
2339
2340    fn encode_traits(&mut self) -> LazyArray<LocalDefId> {
2341        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2342        self.lazy_array(self.tcx.traits(LOCAL_CRATE).iter().map(|def_id| def_id.expect_local()))
2343    }
2344
2345    /// Encodes an index, mapping each trait to its (local) implementations.
2346    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("encode_impls",
                                    "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2346u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: LazyArray<TraitImpls> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if self.is_proc_macro { return LazyArray::default(); };
            let tcx = self.tcx;
            let mut trait_impls:
                    FxIndexMap<DefId,
                    Vec<(LocalDefId, 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 local_id = id.owner_id.def_id;
                if of_trait {
                    let header = tcx.impl_trait_header(local_id);
                    self.table_writer().impl_trait_header(local_id, header);
                    let impl_is_fully_generic_for_reflection =
                        tcx.impl_is_fully_generic_for_reflection(local_id);
                    self.table_writer().impl_is_fully_generic_for_reflection(local_id,
                        impl_is_fully_generic_for_reflection);
                    self.table_writer().defaultness(local_id,
                        tcx.defaultness(local_id));
                    let trait_ref =
                        header.trait_ref.instantiate_identity().skip_norm_wip();
                    let simplified_self_ty =
                        fast_reject::simplify_type(tcx, trait_ref.self_ty(),
                            TreatParams::InstantiateWithInfer);
                    trait_impls.entry(trait_ref.def_id).or_default().push((local_id,
                            simplified_self_ty));
                    let trait_def = tcx.trait_def(trait_ref.def_id);
                    if let Ok(mut an) =
                                trait_def.ancestors(tcx, local_id.to_def_id()) &&
                            let Some(specialization_graph::Node::Impl(parent)) =
                                an.nth(1) {
                        let parent =
                            RemappedRawDefId::create(parent,
                                &self.local_defs_remapping);
                        self.table_writer().impl_parent(local_id, parent);
                    }
                    if tcx.is_lang_item(trait_ref.def_id,
                            LangItem::CoerceUnsized) {
                        let coerce_unsized_info =
                            tcx.coerce_unsized_info(local_id).unwrap();
                        self.table_writer().coerce_unsized_info(local_id,
                            coerce_unsized_info);
                    }
                }
            }
            let trait_impls: Vec<_> =
                trait_impls.into_iter().map(|(trait_def_id, impls)|
                            TraitImpls {
                                trait_id: RemappedRawDefId::create(trait_def_id,
                                    &self.local_defs_remapping),
                                impls: self.lazy_array(&impls),
                            }).collect();
            self.lazy_array(&trait_impls)
        }
    }
}#[instrument(level = "debug", skip(self))]
2347    fn encode_impls(&mut self) -> LazyArray<TraitImpls> {
2348        empty_proc_macro!(self);
2349        let tcx = self.tcx;
2350        let mut trait_impls: FxIndexMap<DefId, Vec<(LocalDefId, Option<SimplifiedType>)>> =
2351            FxIndexMap::default();
2352
2353        for id in tcx.hir_free_items() {
2354            let DefKind::Impl { of_trait } = tcx.def_kind(id.owner_id) else {
2355                continue;
2356            };
2357            let local_id = id.owner_id.def_id;
2358
2359            if of_trait {
2360                let header = tcx.impl_trait_header(local_id);
2361                self.table_writer().impl_trait_header(local_id, header);
2362
2363                let impl_is_fully_generic_for_reflection =
2364                    tcx.impl_is_fully_generic_for_reflection(local_id);
2365
2366                self.table_writer().impl_is_fully_generic_for_reflection(
2367                    local_id,
2368                    impl_is_fully_generic_for_reflection,
2369                );
2370                self.table_writer().defaultness(local_id, tcx.defaultness(local_id));
2371
2372                let trait_ref = header.trait_ref.instantiate_identity().skip_norm_wip();
2373                let simplified_self_ty = fast_reject::simplify_type(
2374                    tcx,
2375                    trait_ref.self_ty(),
2376                    TreatParams::InstantiateWithInfer,
2377                );
2378                trait_impls
2379                    .entry(trait_ref.def_id)
2380                    .or_default()
2381                    .push((local_id, simplified_self_ty));
2382
2383                let trait_def = tcx.trait_def(trait_ref.def_id);
2384                if let Ok(mut an) = trait_def.ancestors(tcx, local_id.to_def_id())
2385                    && let Some(specialization_graph::Node::Impl(parent)) = an.nth(1)
2386                {
2387                    let parent = RemappedRawDefId::create(parent, &self.local_defs_remapping);
2388                    self.table_writer().impl_parent(local_id, parent);
2389                }
2390
2391                // if this is an impl of `CoerceUnsized`, create its
2392                // "unsized info", else just store None
2393                if tcx.is_lang_item(trait_ref.def_id, LangItem::CoerceUnsized) {
2394                    let coerce_unsized_info = tcx.coerce_unsized_info(local_id).unwrap();
2395                    self.table_writer().coerce_unsized_info(local_id, coerce_unsized_info);
2396                }
2397            }
2398        }
2399
2400        let trait_impls: Vec<_> = trait_impls
2401            .into_iter()
2402            .map(|(trait_def_id, impls)| TraitImpls {
2403                trait_id: RemappedRawDefId::create(trait_def_id, &self.local_defs_remapping),
2404                impls: self.lazy_array(&impls),
2405            })
2406            .collect();
2407
2408        self.lazy_array(&trait_impls)
2409    }
2410
2411    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("encode_incoherent_impls",
                                    "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2411u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: LazyArray<IncoherentImpls> =
                loop {};
            return __tracing_attr_fake_return;
        }
        {
            if self.is_proc_macro { return LazyArray::default(); };
            let tcx = self.tcx;
            let all_impls: Vec<_> =
                tcx.crate_inherent_impls(()).0.incoherent_impls.iter().map(|(&simp,
                                impls)|
                            IncoherentImpls {
                                self_ty: self.lazy(simp),
                                impls: self.lazy_array(impls.iter().map(|def_id| *def_id)),
                            }).collect();
            self.lazy_array(&all_impls)
        }
    }
}#[instrument(level = "debug", skip(self))]
2412    fn encode_incoherent_impls(&mut self) -> LazyArray<IncoherentImpls> {
2413        empty_proc_macro!(self);
2414        let tcx = self.tcx;
2415
2416        let all_impls: Vec<_> = tcx
2417            .crate_inherent_impls(())
2418            .0
2419            .incoherent_impls
2420            .iter()
2421            .map(|(&simp, impls)| IncoherentImpls {
2422                self_ty: self.lazy(simp),
2423                impls: self.lazy_array(impls.iter().map(|def_id| *def_id)),
2424            })
2425            .collect();
2426
2427        self.lazy_array(&all_impls)
2428    }
2429
2430    fn encode_exportable_items(&mut self) -> LazyArray<LocalDefId> {
2431        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2432        self.lazy_array(
2433            self.tcx.exportable_items(LOCAL_CRATE).iter().map(|def_id| def_id.expect_local()),
2434        )
2435    }
2436
2437    fn encode_stable_order_of_exportable_impls(&mut self) -> LazyArray<(LocalDefId, usize)> {
2438        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2439        let stable_order_of_exportable_impls =
2440            self.tcx.stable_order_of_exportable_impls(LOCAL_CRATE);
2441        self.lazy_array(
2442            stable_order_of_exportable_impls
2443                .iter()
2444                .map(|(def_id, idx)| (def_id.expect_local(), *idx)),
2445        )
2446    }
2447
2448    // Encodes all symbols exported from this crate into the metadata.
2449    //
2450    // This pass is seeded off the reachability list calculated in the
2451    // middle::reachable module but filters out items that either don't have a
2452    // symbol associated with them (they weren't translated) or if they're an FFI
2453    // definition (as that's not defined in this crate).
2454    fn encode_exported_symbols(
2455        &mut self,
2456        exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportInfo)],
2457    ) -> LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)> {
2458        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2459
2460        self.lazy_array(exported_symbols.iter().cloned())
2461    }
2462
2463    fn encode_dylib_dependency_formats(&mut self) -> LazyArray<Option<LinkagePreference>> {
2464        if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2465        let formats = self.tcx.dependency_formats(());
2466        if let Some(arr) = formats.get(&CrateType::Dylib) {
2467            return self.lazy_array(arr.iter().skip(1 /* skip LOCAL_CRATE */).map(
2468                |slot| match *slot {
2469                    Linkage::NotLinked | Linkage::IncludedFromDylib => None,
2470
2471                    Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
2472                    Linkage::Static => Some(LinkagePreference::RequireStatic),
2473                },
2474            ));
2475        }
2476        LazyArray::default()
2477    }
2478}
2479
2480/// Used to prefetch queries which will be needed later by metadata encoding.
2481/// Only a subset of the queries are actually prefetched to keep this code smaller.
2482fn prefetch_mir(tcx: TyCtxt<'_>) {
2483    if !tcx.sess.opts.output_types.should_codegen() {
2484        // We won't emit MIR, so don't prefetch it.
2485        return;
2486    }
2487
2488    let reachable_set = tcx.reachable_set(());
2489    par_for_each_in(tcx.mir_keys(()).as_slice(), |&def_id| {
2490        if tcx.is_trivial_const(def_id) {
2491            return;
2492        }
2493        let (encode_const, encode_opt) = should_encode_mir(tcx, Some(reachable_set), def_id);
2494
2495        if encode_const {
2496            tcx.ensure_done().mir_for_ctfe(def_id);
2497        }
2498        if encode_opt {
2499            tcx.ensure_done().optimized_mir(def_id);
2500        }
2501        if encode_opt || encode_const {
2502            tcx.ensure_done().promoted_mir(def_id);
2503        }
2504    })
2505}
2506
2507// NOTE(eddyb) The following comment was preserved for posterity, even
2508// though it's no longer relevant as EBML (which uses nested & tagged
2509// "documents") was replaced with a scheme that can't go out of bounds.
2510//
2511// And here we run into yet another obscure archive bug: in which metadata
2512// loaded from archives may have trailing garbage bytes. Awhile back one of
2513// our tests was failing sporadically on the macOS 64-bit builders (both nopt
2514// and opt) by having ebml generate an out-of-bounds panic when looking at
2515// metadata.
2516//
2517// Upon investigation it turned out that the metadata file inside of an rlib
2518// (and ar archive) was being corrupted. Some compilations would generate a
2519// metadata file which would end in a few extra bytes, while other
2520// compilations would not have these extra bytes appended to the end. These
2521// extra bytes were interpreted by ebml as an extra tag, so they ended up
2522// being interpreted causing the out-of-bounds.
2523//
2524// The root cause of why these extra bytes were appearing was never
2525// discovered, and in the meantime the solution we're employing is to insert
2526// the length of the metadata to the start of the metadata. Later on this
2527// will allow us to slice the metadata to the precise length that we just
2528// generated regardless of trailing bytes that end up in it.
2529
2530pub struct EncodedMetadata {
2531    // The declaration order matters because `full_metadata` should be dropped
2532    // before `_temp_dir`.
2533    full_metadata: Option<Mmap>,
2534    // This is an optional stub metadata containing only the crate header.
2535    // The header should be very small, so we load it directly into memory.
2536    stub_metadata: Option<Vec<u8>>,
2537    // The path containing the metadata, to record as work product.
2538    path: Option<Box<Path>>,
2539    // We need to carry MaybeTempDir to avoid deleting the temporary
2540    // directory while accessing the Mmap.
2541    _temp_dir: Option<MaybeTempDir>,
2542}
2543
2544impl EncodedMetadata {
2545    #[inline]
2546    pub fn from_path(
2547        path: PathBuf,
2548        stub_path: Option<PathBuf>,
2549        temp_dir: Option<MaybeTempDir>,
2550    ) -> std::io::Result<Self> {
2551        let file = std::fs::File::open(&path)?;
2552        let file_metadata = file.metadata()?;
2553        if file_metadata.len() == 0 {
2554            return Ok(Self {
2555                full_metadata: None,
2556                stub_metadata: None,
2557                path: None,
2558                _temp_dir: None,
2559            });
2560        }
2561        let full_mmap = unsafe { Some(Mmap::map(file)?) };
2562
2563        let stub =
2564            if let Some(stub_path) = stub_path { Some(std::fs::read(stub_path)?) } else { None };
2565
2566        Ok(Self {
2567            full_metadata: full_mmap,
2568            stub_metadata: stub,
2569            path: Some(path.into()),
2570            _temp_dir: temp_dir,
2571        })
2572    }
2573
2574    #[inline]
2575    pub fn full(&self) -> &[u8] {
2576        &self.full_metadata.as_deref().unwrap_or_default()
2577    }
2578
2579    #[inline]
2580    pub fn stub_or_full(&self) -> &[u8] {
2581        self.stub_metadata.as_deref().unwrap_or(self.full())
2582    }
2583
2584    #[inline]
2585    pub fn path(&self) -> Option<&Path> {
2586        self.path.as_deref()
2587    }
2588}
2589
2590impl<S: Encoder> Encodable<S> for EncodedMetadata {
2591    fn encode(&self, s: &mut S) {
2592        self.stub_metadata.encode(s);
2593
2594        let slice = self.full();
2595        slice.encode(s)
2596    }
2597}
2598
2599impl<D: Decoder> Decodable<D> for EncodedMetadata {
2600    fn decode(d: &mut D) -> Self {
2601        let stub = <Option<Vec<u8>>>::decode(d);
2602
2603        let len = d.read_usize();
2604        let full_metadata = if len > 0 {
2605            let mut mmap = MmapMut::map_anon(len).unwrap();
2606            mmap.copy_from_slice(d.read_raw_bytes(len));
2607            Some(mmap.make_read_only().unwrap())
2608        } else {
2609            None
2610        };
2611
2612        Self { full_metadata, stub_metadata: stub, path: None, _temp_dir: None }
2613    }
2614}
2615
2616{}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("encode_metadata",
                                    "rustc_metadata::rmeta::encoder", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2616u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("path")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("path");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("ref_path")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("ref_path");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ref_path)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            tcx.dep_graph.assert_ignored();
            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 incr_comp_session = tcx.incr_comp_session.unwrap() &&
                                let Some(old_incr_comp_session_dir) =
                                    &incr_comp_session.old_session_directory &&
                            let work_product_id =
                                WorkProductId::from_cgu_name(WorkProduct::METADATA_WORKPRODUCT_CGU_NAME)
                        &&
                        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[OutputType::Metadata.extension()];
                let source_file_in_incr_dir =
                    &old_incr_comp_session_dir.join(saved_path);
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_metadata/src/rmeta/encoder.rs:2637",
                                        "rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/739adecd444342128b4ef32cbbd8352856cb1651/compiler/rustc_metadata/src/rmeta/encoder.rs"),
                                        ::tracing_core::__macro_support::Option::Some(2637u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("copying preexisting metadata from {0:?} to {1:?}",
                                                                    source_file_in_incr_dir, path) as
                                                            &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                match rustc_fs_util::link_or_copy(&source_file_in_incr_dir,
                        path) {
                    Ok(_) => {}
                    Err(err) =>
                        tcx.dcx().emit_fatal(FailCreateFileEncoder { err }),
                };
                let file =
                    std::fs::File::open(&source_file_in_incr_dir).unwrap();
                let mmap = unsafe { Mmap::map(file) }.unwrap();
                let owned = slice_owned(mmap, Deref::deref);
                let blob = MetadataBlob::new(owned);
                let hash =
                    blob.expect("file already created").get_crate_hash();
                tcx.untracked().local_crate_hash.set(hash).expect("local_crate_hash set twice");
                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(),
                                            is_proc_macro_crate: false,
                                            is_stub: true,
                                        });
                                (header.position.get(), 0)
                            })
                }
                return;
            };
            if tcx.sess.opts.jobs.frontend.is_parallel() {
                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, unhashed) = ecx.encode_crate_root();
                                    ecx.opaque.flush();
                                    tcx.prof.artifact_size("crate_metadata", "crate_metadata",
                                        ecx.opaque.file().metadata().unwrap().len());
                                    (root.position.get(), unhashed.position.get())
                                })
                    }, None);
            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(),
                                        is_proc_macro_crate: false,
                                        is_stub: true,
                                    });
                            (header.position.get(), 0)
                        })
            }
        }
    }
}#[instrument(level = "trace", skip(tcx))]
2617pub fn encode_metadata(tcx: TyCtxt<'_>, path: &Path, ref_path: Option<&Path>) {
2618    // Since encoding metadata is not in a query, and nothing is cached,
2619    // there's no need to do dep-graph tracking for any of it.
2620    tcx.dep_graph.assert_ignored();
2621
2622    let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata");
2623
2624    let dep_node = tcx.metadata_dep_node();
2625
2626    // If the metadata dep-node is green, try to reuse the saved work product.
2627    if tcx.dep_graph.is_fully_enabled()
2628        && let incr_comp_session = tcx.incr_comp_session.unwrap()
2629        && let Some(old_incr_comp_session_dir) = &incr_comp_session.old_session_directory
2630        && let work_product_id =
2631            WorkProductId::from_cgu_name(WorkProduct::METADATA_WORKPRODUCT_CGU_NAME)
2632        && let Some(work_product) = tcx.dep_graph.previous_work_product(&work_product_id)
2633        && tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some()
2634    {
2635        let saved_path = &work_product.saved_files[OutputType::Metadata.extension()];
2636        let source_file_in_incr_dir = &old_incr_comp_session_dir.join(saved_path);
2637        debug!("copying preexisting metadata from {source_file_in_incr_dir:?} to {path:?}");
2638        match rustc_fs_util::link_or_copy(&source_file_in_incr_dir, path) {
2639            Ok(_) => {}
2640            Err(err) => tcx.dcx().emit_fatal(FailCreateFileEncoder { err }),
2641        };
2642
2643        // Read the SVH from the old metadata header.
2644        let file = std::fs::File::open(&source_file_in_incr_dir).unwrap();
2645        let mmap = unsafe { Mmap::map(file) }.unwrap();
2646        let owned = slice_owned(mmap, Deref::deref);
2647        let blob = MetadataBlob::new(owned);
2648        let hash = blob.expect("file already created").get_crate_hash();
2649        tcx.untracked().local_crate_hash.set(hash).expect("local_crate_hash set twice");
2650
2651        // Generate the metadata stub manually, as that is a small file compared to full metadata.
2652        if let Some(ref_path) = ref_path {
2653            let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata_stub");
2654
2655            with_encode_metadata_header(tcx, ref_path, |ecx| {
2656                let header: LazyValue<CrateHeader> = ecx.lazy(CrateHeader {
2657                    name: tcx.crate_name(LOCAL_CRATE),
2658                    triple: tcx.sess.opts.target_triple.clone(),
2659                    is_proc_macro_crate: false,
2660                    is_stub: true,
2661                });
2662                (header.position.get(), 0)
2663            })
2664        }
2665
2666        return;
2667    };
2668
2669    if tcx.sess.opts.jobs.frontend.is_parallel() {
2670        // Prefetch some queries used by metadata encoding.
2671        // This is not necessary for correctness, but is only done for performance reasons.
2672        // It can be removed if it turns out to cause trouble or be detrimental to performance.
2673        par_join(
2674            || prefetch_mir(tcx),
2675            || {
2676                let _ = tcx.exported_non_generic_symbols(LOCAL_CRATE);
2677                let _ = tcx.exported_generic_symbols(LOCAL_CRATE);
2678            },
2679        );
2680    }
2681
2682    // Perform metadata encoding inside a task, so the dep-graph can check if any encoded
2683    // information changes, and maybe reuse the work product.
2684    tcx.dep_graph.with_task(
2685        dep_node,
2686        tcx,
2687        || {
2688            with_encode_metadata_header(tcx, path, |ecx| {
2689                // Encode all the entries and extra information in the crate,
2690                // culminating in the `CrateRoot` which points to all of it.
2691                let (root, unhashed) = ecx.encode_crate_root();
2692
2693                // Flush buffer to ensure backing file has the correct size.
2694                ecx.opaque.flush();
2695                // Record metadata size for self-profiling
2696                tcx.prof.artifact_size(
2697                    "crate_metadata",
2698                    "crate_metadata",
2699                    ecx.opaque.file().metadata().unwrap().len(),
2700                );
2701
2702                (root.position.get(), unhashed.position.get())
2703            })
2704        },
2705        None,
2706    );
2707
2708    // Generate the metadata stub manually, as that is a small file compared to full metadata.
2709    if let Some(ref_path) = ref_path {
2710        let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata_stub");
2711
2712        with_encode_metadata_header(tcx, ref_path, |ecx| {
2713            let header: LazyValue<CrateHeader> = ecx.lazy(CrateHeader {
2714                name: tcx.crate_name(LOCAL_CRATE),
2715                triple: tcx.sess.opts.target_triple.clone(),
2716                is_proc_macro_crate: false,
2717                is_stub: true,
2718            });
2719            (header.position.get(), 0)
2720        })
2721    }
2722}
2723
2724fn with_encode_metadata_header(
2725    tcx: TyCtxt<'_>,
2726    path: &Path,
2727    f: impl FnOnce(&mut EncodeContext<'_, '_>) -> (usize, usize),
2728) {
2729    // By default the crate hash (SVH) is computed from the bytes of the encoded metadata,
2730    // Under `-Z metadata-crate-hash=no` the SVH comes from the legacy `crate_hash` query instead and
2731    // this hasher is never consulted, so we skip seeding it and feeding metadata bytes into it.
2732    let metadata_crate_hash = tcx.sess.opts.unstable_opts.metadata_crate_hash;
2733    // The SVH is an XXH3-128 digest of the encoded metadata bytes. XXH3 is a fast, non-cryptographic
2734    // hash; that is sufficient here because the SVH is only a change detector, is never keyed
2735    // secretly (it must be reproducible), and compiling a crate already runs its build scripts and
2736    // proc-macros, so the crate author is trusted regardless.
2737    let metadata_hasher = Arc::new(Mutex::new(XxHash3_128::new()));
2738    if metadata_crate_hash {
2739        // Fold in inputs that are not part of the encoded metadata bytes, reduced to a single
2740        // fingerprint via the stable hasher and then mixed into the byte digest.
2741        let hir_body_hash = compute_hir_hash(tcx);
2742        let supplement: Fingerprint = tcx.with_stable_hashing_context(|mut hcx| {
2743            let mut hasher = StableHasher::new();
2744            // Add dep_tracking_hash to ensure the SVH changes when any tracked flag changes.
2745            tcx.sess.opts.dep_tracking_hash(true).stable_hash(&mut hcx, &mut hasher);
2746            // Add HIR hash for untracked elements, e.g. DefKind::GlobalAsm.
2747            hir_body_hash.stable_hash(&mut hcx, &mut hasher);
2748            hasher.finish()
2749        });
2750        metadata_hasher.lock().unwrap().write(&supplement.to_le_bytes());
2751    }
2752
2753    // Feed every flushed byte into `metadata_hasher` so the SVH covers the entire encoded metadata.
2754    let mut flush_strategy = {
2755        let metadata_hasher = Arc::clone(&metadata_hasher);
2756        move |bytes: &[u8]| metadata_hasher.lock().unwrap().write(bytes)
2757    };
2758
2759    let mut encoder = if metadata_crate_hash {
2760        FileEncoder::with_flush_strategy(path, &mut flush_strategy)
2761    } else {
2762        FileEncoder::new(path)
2763    }
2764    .unwrap_or_else(|err| tcx.dcx().emit_fatal(FailCreateFileEncoder { err }));
2765    encoder.emit_raw_bytes(METADATA_HEADER);
2766
2767    // Will be filled with the root position after encoding everything.
2768    encoder.emit_raw_bytes(&0u64.to_le_bytes());
2769
2770    // Same with unhashed_position.
2771    encoder.emit_raw_bytes(&0u64.to_le_bytes());
2772
2773    // Same with crate_hash.
2774    encoder.emit_raw_bytes(&Fingerprint::ZERO.to_le_bytes());
2775
2776    let source_map_files = tcx.sess.source_map().files();
2777    let source_file_cache = (Arc::clone(&source_map_files[0]), 0);
2778    let required_source_files = Some(FxIndexSet::default());
2779    drop(source_map_files);
2780
2781    let mut ecx = EncodeContext {
2782        opaque: encoder,
2783        metadata_hasher: Arc::clone(&metadata_hasher),
2784        tcx,
2785        feat: tcx.features(),
2786        tables: Default::default(),
2787        lazy_state: LazyState::NoNode,
2788        span_shorthands: Default::default(),
2789        type_shorthands: Default::default(),
2790        predicate_shorthands: Default::default(),
2791        source_file_cache,
2792        interpret_allocs: Default::default(),
2793        required_source_files,
2794        is_proc_macro: tcx.crate_types().contains(&CrateType::ProcMacro),
2795        hygiene_ctxt: Default::default(),
2796        symbol_index_table: Default::default(),
2797        local_defs_remapping: Default::default(),
2798        syntax_context_remapping: Default::default(),
2799        local_expn_id_remapping: Default::default(),
2800    };
2801
2802    // Encode the rustc version string in a predictable location.
2803    rustc_version(tcx.sess.cfg_version).encode(&mut ecx);
2804
2805    let (root_position, unhashed_position) = f(&mut ecx);
2806
2807    // Make sure we report any errors from writing to the file.
2808    // If we forget this, compilation can succeed with an incomplete rmeta file,
2809    // causing an ICE when the rmeta file is read by another compilation.
2810    if let Err((path, err)) = ecx.opaque.finish() {
2811        tcx.dcx().emit_fatal(FailWriteFile { path: &path, err });
2812    }
2813
2814    let mut file = ecx.opaque.file();
2815    // We will return to this position after writing the root position and crate hash.
2816    let pos_before_seek = file.stream_position().unwrap();
2817
2818    if let Err(err) = encode_root_position(file, root_position) {
2819        tcx.dcx().emit_fatal(FailWriteFile { path: ecx.opaque.path(), err });
2820    }
2821
2822    if let Err(err) = encode_unhashed_position(file, unhashed_position) {
2823        tcx.dcx().emit_fatal(FailWriteFile { path: ecx.opaque.path(), err });
2824    }
2825
2826    let hash = tcx
2827        .untracked()
2828        .local_crate_hash
2829        .get()
2830        .copied()
2831        .expect("local_crate_hash set during encoding");
2832    if let Err(err) = encode_crate_hash(file, hash) {
2833        tcx.dcx().emit_fatal(FailWriteFile { path: ecx.opaque.path(), err });
2834    }
2835
2836    if let Err(err) = file.seek(SeekFrom::Start(pos_before_seek)) {
2837        tcx.dcx().emit_fatal(FailWriteFile { path: ecx.opaque.path(), err });
2838    }
2839}
2840
2841fn encode_root_position(mut file: &File, pos: usize) -> Result<(), std::io::Error> {
2842    file.seek(SeekFrom::Start(ROOT_POS_OFFSET as u64))?;
2843    file.write_all(&pos.to_le_bytes())?;
2844    Ok(())
2845}
2846
2847fn encode_unhashed_position(mut file: &File, pos: usize) -> Result<(), std::io::Error> {
2848    file.seek(SeekFrom::Start(UNHASHED_POS_OFFSET as u64))?;
2849    file.write_all(&pos.to_le_bytes())?;
2850    Ok(())
2851}
2852
2853fn encode_crate_hash(mut file: &File, hash: Svh) -> Result<(), std::io::Error> {
2854    file.seek(SeekFrom::Start(CRATE_HASH_OFFSET as u64))?;
2855    file.write_all(&hash.as_fingerprint().to_le_bytes())?;
2856    Ok(())
2857}
2858
2859pub(crate) fn provide(providers: &mut Providers) {
2860    *providers = Providers {
2861        doc_link_resolutions: |tcx, def_id| {
2862            tcx.resolutions(())
2863                .doc_link_resolutions
2864                .get(&def_id)
2865                .unwrap_or_else(|| ::rustc_span::macros::bug_impl(Some(tcx.def_span(def_id)),
    format_args!("no resolutions for a doc link"), Location::caller())span_bug!(tcx.def_span(def_id), "no resolutions for a doc link"))
2866        },
2867        doc_link_traits_in_scope: |tcx, def_id| {
2868            tcx.resolutions(()).doc_link_traits_in_scope.get(&def_id).unwrap_or_else(|| {
2869                ::rustc_span::macros::bug_impl(Some(tcx.def_span(def_id)),
    format_args!("no traits in scope for a doc link"), Location::caller())span_bug!(tcx.def_span(def_id), "no traits in scope for a doc link")
2870            })
2871        },
2872
2873        ..*providers
2874    }
2875}
2876
2877/// Build a textual representation of an unevaluated constant expression.
2878///
2879/// If the const expression is too complex, an underscore `_` is returned.
2880/// For const arguments, it's `{ _ }` to be precise.
2881/// This means that the output is not necessarily valid Rust code.
2882///
2883/// Currently, only
2884///
2885/// * literals (optionally with a leading `-`)
2886/// * unit `()`
2887/// * blocks (`{ … }`) around simple expressions and
2888/// * paths without arguments
2889///
2890/// are considered simple enough. Simple blocks are included since they are
2891/// necessary to disambiguate unit from the unit type.
2892/// This list might get extended in the future.
2893///
2894/// Without this censoring, in a lot of cases the output would get too large
2895/// and verbose. Consider `match` expressions, blocks and deeply nested ADTs.
2896/// Further, private and `doc(hidden)` fields of structs would get leaked
2897/// since HIR datatypes like the `body` parameter do not contain enough
2898/// semantic information for this function to be able to hide them –
2899/// at least not without significant performance overhead.
2900///
2901/// Whenever possible, prefer to evaluate the constant first and try to
2902/// use a different method for pretty-printing. Ideally this function
2903/// should only ever be used as a fallback.
2904pub fn rendered_const<'tcx>(tcx: TyCtxt<'tcx>, body: &hir::Body<'_>, def_id: LocalDefId) -> String {
2905    let value = body.value;
2906
2907    #[derive(#[automatically_derived]impl ::core::marker::StructuralPartialEq for
    Classification {
}
#[automatically_derived]impl ::core::cmp::PartialEq for Classification {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for Classification { }Eq)]
2908    enum Classification {
2909        Literal,
2910        Simple,
2911        Complex,
2912    }
2913
2914    use Classification::*;
2915
2916    fn classify(expr: &hir::Expr<'_>) -> Classification {
2917        match &expr.kind {
2918            hir::ExprKind::Unary(hir::UnOp::Neg, expr) => {
2919                if #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
    hir::ExprKind::Lit(_) => true,
    _ => false,
}matches!(expr.kind, hir::ExprKind::Lit(_)) { Literal } else { Complex }
2920            }
2921            hir::ExprKind::Lit(_) => Literal,
2922            hir::ExprKind::Tup([]) => Simple,
2923            hir::ExprKind::Block(hir::Block { stmts: [], expr: Some(expr), .. }, _) => {
2924                if classify(expr) == Complex { Complex } else { Simple }
2925            }
2926            // Paths with a self-type or arguments are too “complex” following our measure since
2927            // they may leak private fields of structs (with feature `adt_const_params`).
2928            // Consider: `<Self as Trait<{ Struct { private: () } }>>::CONSTANT`.
2929            // Paths without arguments are definitely harmless though.
2930            hir::ExprKind::Path(hir::QPath::Resolved(_, hir::Path { segments, .. })) => {
2931                if segments.iter().all(|segment| segment.args.is_none()) { Simple } else { Complex }
2932            }
2933            // FIXME: Claiming that those kinds of QPaths are simple is probably not true if the Ty
2934            //        contains const arguments. Is there a *concise* way to check for this?
2935            hir::ExprKind::Path(hir::QPath::TypeRelative(..)) => Simple,
2936            _ => Complex,
2937        }
2938    }
2939
2940    match classify(value) {
2941        // For non-macro literals, we avoid invoking the pretty-printer and use the source snippet
2942        // instead to preserve certain stylistic choices the user likely made for the sake of
2943        // legibility, like:
2944        //
2945        // * hexadecimal notation
2946        // * underscores
2947        // * character escapes
2948        //
2949        // FIXME: This passes through `-/*spacer*/0` verbatim.
2950        Literal
2951            if !value.span.from_expansion()
2952                && let Ok(snippet) = tcx.sess.source_map().span_to_snippet(value.span) =>
2953        {
2954            snippet
2955        }
2956
2957        // Otherwise we prefer pretty-printing to get rid of extraneous whitespace, comments and
2958        // other formatting artifacts.
2959        Literal | Simple => id_to_string(&tcx, body.id().hir_id),
2960
2961        // FIXME: Omit the curly braces if the enclosing expression is an array literal
2962        //        with a repeated element (an `ExprKind::Repeat`) as in such case it
2963        //        would not actually need any disambiguation.
2964        Complex => {
2965            if tcx.def_kind(def_id) == DefKind::AnonConst {
2966                "{ _ }".to_owned()
2967            } else {
2968                "_".to_owned()
2969            }
2970        }
2971    }
2972}