rustc_metadata/rmeta/
encoder.rs

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