]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_metadata/src/rmeta/encoder.rs
Provide a better diagnostic on failure to meet send bound on futures in a foreign...
[rust.git] / compiler / rustc_metadata / src / rmeta / encoder.rs
1 use crate::rmeta::def_path_hash_map::DefPathHashMapRef;
2 use crate::rmeta::table::{FixedSizeEncoding, TableBuilder};
3 use crate::rmeta::*;
4
5 use rustc_data_structures::fingerprint::Fingerprint;
6 use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
7 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
8 use rustc_data_structures::sync::{join, par_iter, Lrc, ParallelIterator};
9 use rustc_hir as hir;
10 use rustc_hir::def::DefKind;
11 use rustc_hir::def_id::{
12     CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE,
13 };
14 use rustc_hir::definitions::DefPathData;
15 use rustc_hir::intravisit::{self, Visitor};
16 use rustc_hir::itemlikevisit::ItemLikeVisitor;
17 use rustc_hir::lang_items;
18 use rustc_hir::{AnonConst, GenericParamKind};
19 use rustc_index::bit_set::GrowableBitSet;
20 use rustc_index::vec::Idx;
21 use rustc_middle::hir::nested_filter;
22 use rustc_middle::middle::dependency_format::Linkage;
23 use rustc_middle::middle::exported_symbols::{
24     metadata_symbol_name, ExportedSymbol, SymbolExportLevel,
25 };
26 use rustc_middle::mir::interpret;
27 use rustc_middle::thir;
28 use rustc_middle::traits::specialization_graph;
29 use rustc_middle::ty::codec::TyEncoder;
30 use rustc_middle::ty::fast_reject::{self, SimplifiedType, TreatParams};
31 use rustc_middle::ty::query::Providers;
32 use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt};
33 use rustc_serialize::{opaque, Encodable, Encoder};
34 use rustc_session::config::CrateType;
35 use rustc_session::cstore::{ForeignModule, LinkagePreference, NativeLib};
36 use rustc_span::symbol::{sym, Ident, Symbol};
37 use rustc_span::{self, ExternalSource, FileName, SourceFile, Span, SyntaxContext};
38 use rustc_span::{
39     hygiene::{ExpnIndex, HygieneEncodeContext, MacroKind},
40     RealFileName,
41 };
42 use rustc_target::abi::VariantIdx;
43 use std::hash::Hash;
44 use std::num::NonZeroUsize;
45 use std::path::Path;
46 use tracing::{debug, trace};
47
48 pub(super) struct EncodeContext<'a, 'tcx> {
49     opaque: opaque::Encoder,
50     tcx: TyCtxt<'tcx>,
51     feat: &'tcx rustc_feature::Features,
52
53     tables: TableBuilders<'tcx>,
54
55     lazy_state: LazyState,
56     type_shorthands: FxHashMap<Ty<'tcx>, usize>,
57     predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
58
59     interpret_allocs: FxIndexSet<interpret::AllocId>,
60
61     // This is used to speed up Span encoding.
62     // The `usize` is an index into the `MonotonicVec`
63     // that stores the `SourceFile`
64     source_file_cache: (Lrc<SourceFile>, usize),
65     // The indices (into the `SourceMap`'s `MonotonicVec`)
66     // of all of the `SourceFiles` that we need to serialize.
67     // When we serialize a `Span`, we insert the index of its
68     // `SourceFile` into the `GrowableBitSet`.
69     //
70     // This needs to be a `GrowableBitSet` and not a
71     // regular `BitSet` because we may actually import new `SourceFiles`
72     // during metadata encoding, due to executing a query
73     // with a result containing a foreign `Span`.
74     required_source_files: Option<GrowableBitSet<usize>>,
75     is_proc_macro: bool,
76     hygiene_ctxt: &'a HygieneEncodeContext,
77 }
78
79 /// If the current crate is a proc-macro, returns early with `Lazy:empty()`.
80 /// This is useful for skipping the encoding of things that aren't needed
81 /// for proc-macro crates.
82 macro_rules! empty_proc_macro {
83     ($self:ident) => {
84         if $self.is_proc_macro {
85             return Lazy::empty();
86         }
87     };
88 }
89
90 macro_rules! encoder_methods {
91     ($($name:ident($ty:ty);)*) => {
92         $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
93             self.opaque.$name(value)
94         })*
95     }
96 }
97
98 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
99     type Error = <opaque::Encoder as Encoder>::Error;
100
101     #[inline]
102     fn emit_unit(&mut self) -> Result<(), Self::Error> {
103         Ok(())
104     }
105
106     encoder_methods! {
107         emit_usize(usize);
108         emit_u128(u128);
109         emit_u64(u64);
110         emit_u32(u32);
111         emit_u16(u16);
112         emit_u8(u8);
113
114         emit_isize(isize);
115         emit_i128(i128);
116         emit_i64(i64);
117         emit_i32(i32);
118         emit_i16(i16);
119         emit_i8(i8);
120
121         emit_bool(bool);
122         emit_f64(f64);
123         emit_f32(f32);
124         emit_char(char);
125         emit_str(&str);
126         emit_raw_bytes(&[u8]);
127     }
128 }
129
130 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
131     for Lazy<T>
132 {
133     fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
134         e.emit_lazy_distance(*self)
135     }
136 }
137
138 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
139     for Lazy<[T]>
140 {
141     fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
142         e.emit_usize(self.meta)?;
143         if self.meta == 0 {
144             return Ok(());
145         }
146         e.emit_lazy_distance(*self)
147     }
148 }
149
150 impl<'a, 'tcx, I: Idx, T> Encodable<EncodeContext<'a, 'tcx>> for Lazy<Table<I, T>>
151 where
152     Option<T>: FixedSizeEncoding,
153 {
154     fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
155         e.emit_usize(self.meta)?;
156         e.emit_lazy_distance(*self)
157     }
158 }
159
160 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for CrateNum {
161     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
162         if *self != LOCAL_CRATE && s.is_proc_macro {
163             panic!("Attempted to encode non-local CrateNum {:?} for proc-macro crate", self);
164         }
165         s.emit_u32(self.as_u32())
166     }
167 }
168
169 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for DefIndex {
170     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
171         s.emit_u32(self.as_u32())
172     }
173 }
174
175 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnIndex {
176     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
177         s.emit_u32(self.as_u32())
178     }
179 }
180
181 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for SyntaxContext {
182     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
183         rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s)
184     }
185 }
186
187 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnId {
188     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
189         if self.krate == LOCAL_CRATE {
190             // We will only write details for local expansions.  Non-local expansions will fetch
191             // data from the corresponding crate's metadata.
192             // FIXME(#43047) FIXME(#74731) We may eventually want to avoid relying on external
193             // metadata from proc-macro crates.
194             s.hygiene_ctxt.schedule_expn_data_for_encoding(*self);
195         }
196         self.krate.encode(s)?;
197         self.local_id.encode(s)
198     }
199 }
200
201 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Span {
202     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
203         let span = self.data();
204
205         // Don't serialize any `SyntaxContext`s from a proc-macro crate,
206         // since we don't load proc-macro dependencies during serialization.
207         // This means that any hygiene information from macros used *within*
208         // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro
209         // definition) will be lost.
210         //
211         // This can show up in two ways:
212         //
213         // 1. Any hygiene information associated with identifier of
214         // a proc macro (e.g. `#[proc_macro] pub fn $name`) will be lost.
215         // Since proc-macros can only be invoked from a different crate,
216         // real code should never need to care about this.
217         //
218         // 2. Using `Span::def_site` or `Span::mixed_site` will not
219         // include any hygiene information associated with the definition
220         // site. This means that a proc-macro cannot emit a `$crate`
221         // identifier which resolves to one of its dependencies,
222         // which also should never come up in practice.
223         //
224         // Additionally, this affects `Span::parent`, and any other
225         // span inspection APIs that would otherwise allow traversing
226         // the `SyntaxContexts` associated with a span.
227         //
228         // None of these user-visible effects should result in any
229         // cross-crate inconsistencies (getting one behavior in the same
230         // crate, and a different behavior in another crate) due to the
231         // limited surface that proc-macros can expose.
232         //
233         // IMPORTANT: If this is ever changed, be sure to update
234         // `rustc_span::hygiene::raw_encode_expn_id` to handle
235         // encoding `ExpnData` for proc-macro crates.
236         if s.is_proc_macro {
237             SyntaxContext::root().encode(s)?;
238         } else {
239             span.ctxt.encode(s)?;
240         }
241
242         if self.is_dummy() {
243             return TAG_PARTIAL_SPAN.encode(s);
244         }
245
246         // The Span infrastructure should make sure that this invariant holds:
247         debug_assert!(span.lo <= span.hi);
248
249         if !s.source_file_cache.0.contains(span.lo) {
250             let source_map = s.tcx.sess.source_map();
251             let source_file_index = source_map.lookup_source_file_idx(span.lo);
252             s.source_file_cache =
253                 (source_map.files()[source_file_index].clone(), source_file_index);
254         }
255
256         if !s.source_file_cache.0.contains(span.hi) {
257             // Unfortunately, macro expansion still sometimes generates Spans
258             // that malformed in this way.
259             return TAG_PARTIAL_SPAN.encode(s);
260         }
261
262         let source_files = s.required_source_files.as_mut().expect("Already encoded SourceMap!");
263         // Record the fact that we need to encode the data for this `SourceFile`
264         source_files.insert(s.source_file_cache.1);
265
266         // There are two possible cases here:
267         // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the
268         // crate we are writing metadata for. When the metadata for *this* crate gets
269         // deserialized, the deserializer will need to know which crate it originally came
270         // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should
271         // be deserialized after the rest of the span data, which tells the deserializer
272         // which crate contains the source map information.
273         // 2. This span comes from our own crate. No special handling is needed - we just
274         // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use
275         // our own source map information.
276         //
277         // If we're a proc-macro crate, we always treat this as a local `Span`.
278         // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata
279         // if we're a proc-macro crate.
280         // This allows us to avoid loading the dependencies of proc-macro crates: all of
281         // the information we need to decode `Span`s is stored in the proc-macro crate.
282         let (tag, lo, hi) = if s.source_file_cache.0.is_imported() && !s.is_proc_macro {
283             // To simplify deserialization, we 'rebase' this span onto the crate it originally came from
284             // (the crate that 'owns' the file it references. These rebased 'lo' and 'hi' values
285             // are relative to the source map information for the 'foreign' crate whose CrateNum
286             // we write into the metadata. This allows `imported_source_files` to binary
287             // search through the 'foreign' crate's source map information, using the
288             // deserialized 'lo' and 'hi' values directly.
289             //
290             // All of this logic ensures that the final result of deserialization is a 'normal'
291             // Span that can be used without any additional trouble.
292             let external_start_pos = {
293                 // Introduce a new scope so that we drop the 'lock()' temporary
294                 match &*s.source_file_cache.0.external_src.lock() {
295                     ExternalSource::Foreign { original_start_pos, .. } => *original_start_pos,
296                     src => panic!("Unexpected external source {:?}", src),
297                 }
298             };
299             let lo = (span.lo - s.source_file_cache.0.start_pos) + external_start_pos;
300             let hi = (span.hi - s.source_file_cache.0.start_pos) + external_start_pos;
301
302             (TAG_VALID_SPAN_FOREIGN, lo, hi)
303         } else {
304             (TAG_VALID_SPAN_LOCAL, span.lo, span.hi)
305         };
306
307         tag.encode(s)?;
308         lo.encode(s)?;
309
310         // Encode length which is usually less than span.hi and profits more
311         // from the variable-length integer encoding that we use.
312         let len = hi - lo;
313         len.encode(s)?;
314
315         if tag == TAG_VALID_SPAN_FOREIGN {
316             // This needs to be two lines to avoid holding the `s.source_file_cache`
317             // while calling `cnum.encode(s)`
318             let cnum = s.source_file_cache.0.cnum;
319             cnum.encode(s)?;
320         }
321
322         Ok(())
323     }
324 }
325
326 impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> {
327     const CLEAR_CROSS_CRATE: bool = true;
328
329     fn position(&self) -> usize {
330         self.opaque.position()
331     }
332
333     fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
334         &mut self.type_shorthands
335     }
336
337     fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
338         &mut self.predicate_shorthands
339     }
340
341     fn encode_alloc_id(
342         &mut self,
343         alloc_id: &rustc_middle::mir::interpret::AllocId,
344     ) -> Result<(), Self::Error> {
345         let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
346
347         index.encode(self)
348     }
349 }
350
351 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for &'tcx [thir::abstract_const::Node<'tcx>] {
352     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
353         (**self).encode(s)
354     }
355 }
356
357 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for &'tcx [(ty::Predicate<'tcx>, Span)] {
358     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
359         (**self).encode(s)
360     }
361 }
362
363 /// Helper trait to allow overloading `EncodeContext::lazy` for iterators.
364 trait EncodeContentsForLazy<'a, 'tcx, T: ?Sized + LazyMeta> {
365     fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> T::Meta;
366 }
367
368 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, T> for &T {
369     fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) {
370         self.encode(ecx).unwrap()
371     }
372 }
373
374 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, T> for T {
375     fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) {
376         self.encode(ecx).unwrap()
377     }
378 }
379
380 impl<'a, 'tcx, I, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, [T]> for I
381 where
382     I: IntoIterator,
383     I::Item: EncodeContentsForLazy<'a, 'tcx, T>,
384 {
385     fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> usize {
386         self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count()
387     }
388 }
389
390 // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy($value))`, which would
391 // normally need extra variables to avoid errors about multiple mutable borrows.
392 macro_rules! record {
393     ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
394         {
395             let value = $value;
396             let lazy = $self.lazy(value);
397             $self.$tables.$table.set($def_id.index, lazy);
398         }
399     }};
400 }
401
402 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
403     fn emit_lazy_distance<T: ?Sized + LazyMeta>(
404         &mut self,
405         lazy: Lazy<T>,
406     ) -> Result<(), <Self as Encoder>::Error> {
407         let pos = lazy.position.get();
408         let distance = match self.lazy_state {
409             LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
410             LazyState::NodeStart(start) => {
411                 let start = start.get();
412                 assert!(pos <= start);
413                 start - pos
414             }
415             LazyState::Previous(last_pos) => {
416                 assert!(
417                     last_pos <= lazy.position,
418                     "make sure that the calls to `lazy*` \
419                      are in the same order as the metadata fields",
420                 );
421                 lazy.position.get() - last_pos.get()
422             }
423         };
424         self.lazy_state = LazyState::Previous(NonZeroUsize::new(pos).unwrap());
425         self.emit_usize(distance)
426     }
427
428     fn lazy<T: ?Sized + LazyMeta>(
429         &mut self,
430         value: impl EncodeContentsForLazy<'a, 'tcx, T>,
431     ) -> Lazy<T> {
432         let pos = NonZeroUsize::new(self.position()).unwrap();
433
434         assert_eq!(self.lazy_state, LazyState::NoNode);
435         self.lazy_state = LazyState::NodeStart(pos);
436         let meta = value.encode_contents_for_lazy(self);
437         self.lazy_state = LazyState::NoNode;
438
439         assert!(pos.get() <= self.position());
440
441         Lazy::from_position_and_meta(pos, meta)
442     }
443
444     fn encode_info_for_items(&mut self) {
445         self.encode_info_for_mod(CRATE_DEF_ID, self.tcx.hir().root_module());
446
447         // Proc-macro crates only export proc-macro items, which are looked
448         // up using `proc_macro_data`
449         if self.is_proc_macro {
450             return;
451         }
452
453         self.tcx.hir().visit_all_item_likes(&mut self.as_deep_visitor());
454     }
455
456     fn encode_def_path_table(&mut self) {
457         let table = self.tcx.resolutions(()).definitions.def_path_table();
458         if self.is_proc_macro {
459             for def_index in std::iter::once(CRATE_DEF_INDEX)
460                 .chain(self.tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index))
461             {
462                 let def_key = self.lazy(table.def_key(def_index));
463                 let def_path_hash = table.def_path_hash(def_index);
464                 self.tables.def_keys.set(def_index, def_key);
465                 self.tables.def_path_hashes.set(def_index, def_path_hash);
466             }
467         } else {
468             for (def_index, def_key, def_path_hash) in table.enumerated_keys_and_path_hashes() {
469                 let def_key = self.lazy(def_key);
470                 self.tables.def_keys.set(def_index, def_key);
471                 self.tables.def_path_hashes.set(def_index, *def_path_hash);
472             }
473         }
474     }
475
476     fn encode_def_path_hash_map(&mut self) -> Lazy<DefPathHashMapRef<'tcx>> {
477         self.lazy(DefPathHashMapRef::BorrowedFromTcx(
478             self.tcx.resolutions(()).definitions.def_path_hash_to_def_index_map(),
479         ))
480     }
481
482     fn encode_source_map(&mut self) -> Lazy<[rustc_span::SourceFile]> {
483         let source_map = self.tcx.sess.source_map();
484         let all_source_files = source_map.files();
485
486         // By replacing the `Option` with `None`, we ensure that we can't
487         // accidentally serialize any more `Span`s after the source map encoding
488         // is done.
489         let required_source_files = self.required_source_files.take().unwrap();
490
491         let adapted = all_source_files
492             .iter()
493             .enumerate()
494             .filter(|(idx, source_file)| {
495                 // Only serialize `SourceFile`s that were used
496                 // during the encoding of a `Span`
497                 required_source_files.contains(*idx) &&
498                 // Don't serialize imported `SourceFile`s, unless
499                 // we're in a proc-macro crate.
500                 (!source_file.is_imported() || self.is_proc_macro)
501             })
502             .map(|(_, source_file)| {
503                 let mut adapted = match source_file.name {
504                     FileName::Real(ref realname) => {
505                         let mut adapted = (**source_file).clone();
506                         adapted.name = FileName::Real(match realname {
507                             RealFileName::LocalPath(path_to_file) => {
508                                 // Prepend path of working directory onto potentially
509                                 // relative paths, because they could become relative
510                                 // to a wrong directory.
511                                 // We include `working_dir` as part of the crate hash,
512                                 // so it's okay for us to use it as part of the encoded
513                                 // metadata.
514                                 let working_dir = &self.tcx.sess.opts.working_dir;
515                                 match working_dir {
516                                     RealFileName::LocalPath(absolute) => {
517                                         // Although neither working_dir or the file name were subject
518                                         // to path remapping, the concatenation between the two may
519                                         // be. Hence we need to do a remapping here.
520                                         let joined = Path::new(absolute).join(path_to_file);
521                                         let (joined, remapped) =
522                                             source_map.path_mapping().map_prefix(joined);
523                                         if remapped {
524                                             RealFileName::Remapped {
525                                                 local_path: None,
526                                                 virtual_name: joined,
527                                             }
528                                         } else {
529                                             RealFileName::LocalPath(joined)
530                                         }
531                                     }
532                                     RealFileName::Remapped { local_path: _, virtual_name } => {
533                                         // If working_dir has been remapped, then we emit
534                                         // Remapped variant as the expanded path won't be valid
535                                         RealFileName::Remapped {
536                                             local_path: None,
537                                             virtual_name: Path::new(virtual_name)
538                                                 .join(path_to_file),
539                                         }
540                                     }
541                                 }
542                             }
543                             RealFileName::Remapped { local_path: _, virtual_name } => {
544                                 RealFileName::Remapped {
545                                     // We do not want any local path to be exported into metadata
546                                     local_path: None,
547                                     virtual_name: virtual_name.clone(),
548                                 }
549                             }
550                         });
551                         adapted.name_hash = {
552                             let mut hasher: StableHasher = StableHasher::new();
553                             adapted.name.hash(&mut hasher);
554                             hasher.finish::<u128>()
555                         };
556                         Lrc::new(adapted)
557                     }
558
559                     // expanded code, not from a file
560                     _ => source_file.clone(),
561                 };
562
563                 // We're serializing this `SourceFile` into our crate metadata,
564                 // so mark it as coming from this crate.
565                 // This also ensures that we don't try to deserialize the
566                 // `CrateNum` for a proc-macro dependency - since proc macro
567                 // dependencies aren't loaded when we deserialize a proc-macro,
568                 // trying to remap the `CrateNum` would fail.
569                 if self.is_proc_macro {
570                     Lrc::make_mut(&mut adapted).cnum = LOCAL_CRATE;
571                 }
572                 adapted
573             })
574             .collect::<Vec<_>>();
575
576         self.lazy(adapted.iter().map(|rc| &**rc))
577     }
578
579     fn encode_crate_root(&mut self) -> Lazy<CrateRoot<'tcx>> {
580         let tcx = self.tcx;
581         let mut i = self.position();
582
583         // Encode the crate deps
584         let crate_deps = self.encode_crate_deps();
585         let dylib_dependency_formats = self.encode_dylib_dependency_formats();
586         let dep_bytes = self.position() - i;
587
588         // Encode the lib features.
589         i = self.position();
590         let lib_features = self.encode_lib_features();
591         let lib_feature_bytes = self.position() - i;
592
593         // Encode the language items.
594         i = self.position();
595         let lang_items = self.encode_lang_items();
596         let lang_items_missing = self.encode_lang_items_missing();
597         let lang_item_bytes = self.position() - i;
598
599         // Encode the diagnostic items.
600         i = self.position();
601         let diagnostic_items = self.encode_diagnostic_items();
602         let diagnostic_item_bytes = self.position() - i;
603
604         // Encode the native libraries used
605         i = self.position();
606         let native_libraries = self.encode_native_libraries();
607         let native_lib_bytes = self.position() - i;
608
609         let foreign_modules = self.encode_foreign_modules();
610
611         // Encode DefPathTable
612         i = self.position();
613         self.encode_def_path_table();
614         let def_path_table_bytes = self.position() - i;
615
616         // Encode the def IDs of traits, for rustdoc and diagnostics.
617         i = self.position();
618         let traits = self.encode_traits();
619         let traits_bytes = self.position() - i;
620
621         // Encode the def IDs of impls, for coherence checking.
622         i = self.position();
623         let impls = self.encode_impls();
624         let impls_bytes = self.position() - i;
625
626         i = self.position();
627         let incoherent_impls = self.encode_incoherent_impls();
628         let incoherent_impls_bytes = self.position() - i;
629         // Encode MIR.
630         i = self.position();
631         self.encode_mir();
632         let mir_bytes = self.position() - i;
633
634         // Encode the items.
635         i = self.position();
636         self.encode_def_ids();
637         self.encode_info_for_items();
638         let item_bytes = self.position() - i;
639
640         // Encode the allocation index
641         let 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 u32;
656                     interpret_alloc_index.push(pos);
657                     interpret::specialized_encode_alloc_id(self, tcx, id).unwrap();
658                 }
659                 n = new_n;
660             }
661             self.lazy(interpret_alloc_index)
662         };
663
664         // Encode the proc macro data. This affects 'tables',
665         // so we need to do this before we encode the tables
666         i = self.position();
667         let proc_macro_data = self.encode_proc_macros();
668         let proc_macro_data_bytes = self.position() - i;
669
670         i = self.position();
671         let tables = self.tables.encode(&mut self.opaque);
672         let tables_bytes = self.position() - i;
673
674         // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode
675         // this as late as possible to give the prefetching as much time as possible to complete.
676         i = self.position();
677         let exported_symbols = tcx.exported_symbols(LOCAL_CRATE);
678         let exported_symbols = self.encode_exported_symbols(&exported_symbols);
679         let exported_symbols_bytes = self.position() - i;
680
681         // Encode the hygiene data,
682         // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The process
683         // of encoding other items (e.g. `optimized_mir`) may cause us to load
684         // data from the incremental cache. If this causes us to deserialize a `Span`,
685         // then we may load additional `SyntaxContext`s into the global `HygieneData`.
686         // Therefore, we need to encode the hygiene data last to ensure that we encode
687         // any `SyntaxContext`s that might be used.
688         i = self.position();
689         let (syntax_contexts, expn_data, expn_hashes) = self.encode_hygiene();
690         let hygiene_bytes = self.position() - i;
691
692         i = self.position();
693         let def_path_hash_map = self.encode_def_path_hash_map();
694         let def_path_hash_map_bytes = self.position() - i;
695
696         // Encode source_map. This needs to be done last,
697         // since encoding `Span`s tells us which `SourceFiles` we actually
698         // need to encode.
699         i = self.position();
700         let source_map = self.encode_source_map();
701         let source_map_bytes = self.position() - i;
702
703         let attrs = tcx.hir().krate_attrs();
704         let has_default_lib_allocator = tcx.sess.contains_name(&attrs, sym::default_lib_allocator);
705
706         let root = self.lazy(CrateRoot {
707             name: tcx.crate_name(LOCAL_CRATE),
708             extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
709             triple: tcx.sess.opts.target_triple.clone(),
710             hash: tcx.crate_hash(LOCAL_CRATE),
711             stable_crate_id: tcx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(),
712             panic_strategy: tcx.sess.panic_strategy(),
713             panic_in_drop_strategy: tcx.sess.opts.debugging_opts.panic_in_drop,
714             edition: tcx.sess.edition(),
715             has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
716             has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
717             has_default_lib_allocator,
718             proc_macro_data,
719             compiler_builtins: tcx.sess.contains_name(&attrs, sym::compiler_builtins),
720             needs_allocator: tcx.sess.contains_name(&attrs, sym::needs_allocator),
721             needs_panic_runtime: tcx.sess.contains_name(&attrs, sym::needs_panic_runtime),
722             no_builtins: tcx.sess.contains_name(&attrs, sym::no_builtins),
723             panic_runtime: tcx.sess.contains_name(&attrs, sym::panic_runtime),
724             profiler_runtime: tcx.sess.contains_name(&attrs, sym::profiler_runtime),
725             symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(),
726
727             crate_deps,
728             dylib_dependency_formats,
729             lib_features,
730             lang_items,
731             diagnostic_items,
732             lang_items_missing,
733             native_libraries,
734             foreign_modules,
735             source_map,
736             traits,
737             impls,
738             incoherent_impls,
739             exported_symbols,
740             interpret_alloc_index,
741             tables,
742             syntax_contexts,
743             expn_data,
744             expn_hashes,
745             def_path_hash_map,
746         });
747
748         let total_bytes = self.position();
749
750         if tcx.sess.meta_stats() {
751             let mut zero_bytes = 0;
752             for e in self.opaque.data.iter() {
753                 if *e == 0 {
754                     zero_bytes += 1;
755                 }
756             }
757
758             eprintln!("metadata stats:");
759             eprintln!("             dep bytes: {}", dep_bytes);
760             eprintln!("     lib feature bytes: {}", lib_feature_bytes);
761             eprintln!("       lang item bytes: {}", lang_item_bytes);
762             eprintln!(" diagnostic item bytes: {}", diagnostic_item_bytes);
763             eprintln!("          native bytes: {}", native_lib_bytes);
764             eprintln!("      source_map bytes: {}", source_map_bytes);
765             eprintln!("          traits bytes: {}", traits_bytes);
766             eprintln!("           impls bytes: {}", impls_bytes);
767             eprintln!("incoherent_impls bytes: {}", incoherent_impls_bytes);
768             eprintln!("    exp. symbols bytes: {}", exported_symbols_bytes);
769             eprintln!("  def-path table bytes: {}", def_path_table_bytes);
770             eprintln!(" def-path hashes bytes: {}", def_path_hash_map_bytes);
771             eprintln!(" proc-macro-data-bytes: {}", proc_macro_data_bytes);
772             eprintln!("             mir bytes: {}", mir_bytes);
773             eprintln!("            item bytes: {}", item_bytes);
774             eprintln!("           table bytes: {}", tables_bytes);
775             eprintln!("         hygiene bytes: {}", hygiene_bytes);
776             eprintln!("            zero bytes: {}", zero_bytes);
777             eprintln!("           total bytes: {}", total_bytes);
778         }
779
780         root
781     }
782 }
783
784 fn should_encode_visibility(def_kind: DefKind) -> bool {
785     match def_kind {
786         DefKind::Mod
787         | DefKind::Struct
788         | DefKind::Union
789         | DefKind::Enum
790         | DefKind::Variant
791         | DefKind::Trait
792         | DefKind::TyAlias
793         | DefKind::ForeignTy
794         | DefKind::TraitAlias
795         | DefKind::AssocTy
796         | DefKind::Fn
797         | DefKind::Const
798         | DefKind::Static(..)
799         | DefKind::Ctor(..)
800         | DefKind::AssocFn
801         | DefKind::AssocConst
802         | DefKind::Macro(..)
803         | DefKind::Use
804         | DefKind::ForeignMod
805         | DefKind::OpaqueTy
806         | DefKind::Impl
807         | DefKind::Field => true,
808         DefKind::TyParam
809         | DefKind::ConstParam
810         | DefKind::LifetimeParam
811         | DefKind::AnonConst
812         | DefKind::InlineConst
813         | DefKind::GlobalAsm
814         | DefKind::Closure
815         | DefKind::Generator
816         | DefKind::ExternCrate => false,
817     }
818 }
819
820 fn should_encode_stability(def_kind: DefKind) -> bool {
821     match def_kind {
822         DefKind::Mod
823         | DefKind::Ctor(..)
824         | DefKind::Variant
825         | DefKind::Field
826         | DefKind::Struct
827         | DefKind::AssocTy
828         | DefKind::AssocFn
829         | DefKind::AssocConst
830         | DefKind::TyParam
831         | DefKind::ConstParam
832         | DefKind::Static(..)
833         | DefKind::Const
834         | DefKind::Fn
835         | DefKind::ForeignMod
836         | DefKind::TyAlias
837         | DefKind::OpaqueTy
838         | DefKind::Enum
839         | DefKind::Union
840         | DefKind::Impl
841         | DefKind::Trait
842         | DefKind::TraitAlias
843         | DefKind::Macro(..)
844         | DefKind::ForeignTy => true,
845         DefKind::Use
846         | DefKind::LifetimeParam
847         | DefKind::AnonConst
848         | DefKind::InlineConst
849         | DefKind::GlobalAsm
850         | DefKind::Closure
851         | DefKind::Generator
852         | DefKind::ExternCrate => false,
853     }
854 }
855
856 /// Whether we should encode MIR.
857 ///
858 /// Computing, optimizing and encoding the MIR is a relatively expensive operation.
859 /// We want to avoid this work when not required. Therefore:
860 /// - we only compute `mir_for_ctfe` on items with const-eval semantics;
861 /// - we skip `optimized_mir` for check runs.
862 ///
863 /// Return a pair, resp. for CTFE and for LLVM.
864 fn should_encode_mir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> (bool, bool) {
865     match tcx.def_kind(def_id) {
866         // Constructors
867         DefKind::Ctor(_, _) => {
868             let mir_opt_base = tcx.sess.opts.output_types.should_codegen()
869                 || tcx.sess.opts.debugging_opts.always_encode_mir;
870             (true, mir_opt_base)
871         }
872         // Constants
873         DefKind::AnonConst
874         | DefKind::InlineConst
875         | DefKind::AssocConst
876         | DefKind::Static(..)
877         | DefKind::Const => (true, false),
878         // Full-fledged functions
879         DefKind::AssocFn | DefKind::Fn => {
880             let generics = tcx.generics_of(def_id);
881             let needs_inline = (generics.requires_monomorphization(tcx)
882                 || tcx.codegen_fn_attrs(def_id).requests_inline())
883                 && tcx.sess.opts.output_types.should_codegen();
884             // The function has a `const` modifier or is annotated with `default_method_body_is_const`.
885             let is_const_fn = tcx.is_const_fn_raw(def_id.to_def_id())
886                 || tcx.has_attr(def_id.to_def_id(), sym::default_method_body_is_const);
887             let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir;
888             (is_const_fn, needs_inline || always_encode_mir)
889         }
890         // Closures can't be const fn.
891         DefKind::Closure => {
892             let generics = tcx.generics_of(def_id);
893             let needs_inline = (generics.requires_monomorphization(tcx)
894                 || tcx.codegen_fn_attrs(def_id).requests_inline())
895                 && tcx.sess.opts.output_types.should_codegen();
896             let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir;
897             (false, needs_inline || always_encode_mir)
898         }
899         // Generators require optimized MIR to compute layout.
900         DefKind::Generator => (false, true),
901         // The others don't have MIR.
902         _ => (false, false),
903     }
904 }
905
906 fn should_encode_variances(def_kind: DefKind) -> bool {
907     match def_kind {
908         DefKind::Struct
909         | DefKind::Union
910         | DefKind::Enum
911         | DefKind::Variant
912         | DefKind::Fn
913         | DefKind::Ctor(..)
914         | DefKind::AssocFn => true,
915         DefKind::Mod
916         | DefKind::Field
917         | DefKind::AssocTy
918         | DefKind::AssocConst
919         | DefKind::TyParam
920         | DefKind::ConstParam
921         | DefKind::Static(..)
922         | DefKind::Const
923         | DefKind::ForeignMod
924         | DefKind::TyAlias
925         | DefKind::OpaqueTy
926         | DefKind::Impl
927         | DefKind::Trait
928         | DefKind::TraitAlias
929         | DefKind::Macro(..)
930         | DefKind::ForeignTy
931         | DefKind::Use
932         | DefKind::LifetimeParam
933         | DefKind::AnonConst
934         | DefKind::InlineConst
935         | DefKind::GlobalAsm
936         | DefKind::Closure
937         | DefKind::Generator
938         | DefKind::ExternCrate => false,
939     }
940 }
941
942 fn should_encode_generics(def_kind: DefKind) -> bool {
943     match def_kind {
944         DefKind::Struct
945         | DefKind::Union
946         | DefKind::Enum
947         | DefKind::Variant
948         | DefKind::Trait
949         | DefKind::TyAlias
950         | DefKind::ForeignTy
951         | DefKind::TraitAlias
952         | DefKind::AssocTy
953         | DefKind::Fn
954         | DefKind::Const
955         | DefKind::Static(..)
956         | DefKind::Ctor(..)
957         | DefKind::AssocFn
958         | DefKind::AssocConst
959         | DefKind::AnonConst
960         | DefKind::InlineConst
961         | DefKind::OpaqueTy
962         | DefKind::Impl
963         | DefKind::Field
964         | DefKind::TyParam
965         | DefKind::Closure
966         | DefKind::Generator => true,
967         DefKind::Mod
968         | DefKind::ForeignMod
969         | DefKind::ConstParam
970         | DefKind::Macro(..)
971         | DefKind::Use
972         | DefKind::LifetimeParam
973         | DefKind::GlobalAsm
974         | DefKind::ExternCrate => false,
975     }
976 }
977
978 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
979     fn encode_def_ids(&mut self) {
980         if self.is_proc_macro {
981             return;
982         }
983         let tcx = self.tcx;
984         let hir = tcx.hir();
985         for local_id in hir.iter_local_def_id() {
986             let def_id = local_id.to_def_id();
987             let def_kind = tcx.opt_def_kind(local_id);
988             let Some(def_kind) = def_kind else { continue };
989             self.tables.opt_def_kind.set(def_id.index, def_kind);
990             record!(self.tables.def_span[def_id] <- tcx.def_span(def_id));
991             record!(self.tables.attributes[def_id] <- tcx.get_attrs(def_id));
992             record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id));
993             if should_encode_visibility(def_kind) {
994                 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
995             }
996             if should_encode_stability(def_kind) {
997                 self.encode_stability(def_id);
998                 self.encode_const_stability(def_id);
999                 self.encode_deprecation(def_id);
1000             }
1001             if should_encode_variances(def_kind) {
1002                 let v = self.tcx.variances_of(def_id);
1003                 record!(self.tables.variances_of[def_id] <- v);
1004             }
1005             if should_encode_generics(def_kind) {
1006                 let g = tcx.generics_of(def_id);
1007                 record!(self.tables.generics_of[def_id] <- g);
1008                 record!(self.tables.explicit_predicates_of[def_id] <- self.tcx.explicit_predicates_of(def_id));
1009                 let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
1010                 if !inferred_outlives.is_empty() {
1011                     record!(self.tables.inferred_outlives_of[def_id] <- inferred_outlives);
1012                 }
1013             }
1014             if let DefKind::Trait | DefKind::TraitAlias = def_kind {
1015                 record!(self.tables.super_predicates_of[def_id] <- self.tcx.super_predicates_of(def_id));
1016             }
1017         }
1018         let inherent_impls = tcx.crate_inherent_impls(());
1019         for (def_id, implementations) in inherent_impls.inherent_impls.iter() {
1020             if implementations.is_empty() {
1021                 continue;
1022             }
1023             record!(self.tables.inherent_impls[def_id.to_def_id()] <- implementations.iter().map(|&def_id| {
1024                 assert!(def_id.is_local());
1025                 def_id.index
1026             }));
1027         }
1028     }
1029
1030     fn encode_item_type(&mut self, def_id: DefId) {
1031         debug!("EncodeContext::encode_item_type({:?})", def_id);
1032         record!(self.tables.type_of[def_id] <- self.tcx.type_of(def_id));
1033     }
1034
1035     fn encode_enum_variant_info(&mut self, def: ty::AdtDef<'tcx>, index: VariantIdx) {
1036         let tcx = self.tcx;
1037         let variant = &def.variant(index);
1038         let def_id = variant.def_id;
1039         debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
1040
1041         let data = VariantData {
1042             ctor_kind: variant.ctor_kind,
1043             discr: variant.discr,
1044             ctor: variant.ctor_def_id.map(|did| did.index),
1045             is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1046         };
1047
1048         record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
1049         self.tables.impl_constness.set(def_id.index, hir::Constness::Const);
1050         record!(self.tables.children[def_id] <- variant.fields.iter().map(|f| {
1051             assert!(f.did.is_local());
1052             f.did.index
1053         }));
1054         self.encode_ident_span(def_id, variant.ident(tcx));
1055         self.encode_item_type(def_id);
1056         if variant.ctor_kind == CtorKind::Fn {
1057             // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`.
1058             if let Some(ctor_def_id) = variant.ctor_def_id {
1059                 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id));
1060             }
1061         }
1062     }
1063
1064     fn encode_enum_variant_ctor(&mut self, def: ty::AdtDef<'tcx>, index: VariantIdx) {
1065         let tcx = self.tcx;
1066         let variant = &def.variant(index);
1067         let def_id = variant.ctor_def_id.unwrap();
1068         debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
1069
1070         // FIXME(eddyb) encode only the `CtorKind` for constructors.
1071         let data = VariantData {
1072             ctor_kind: variant.ctor_kind,
1073             discr: variant.discr,
1074             ctor: Some(def_id.index),
1075             is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1076         };
1077
1078         record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
1079         self.tables.impl_constness.set(def_id.index, hir::Constness::Const);
1080         self.encode_item_type(def_id);
1081         if variant.ctor_kind == CtorKind::Fn {
1082             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1083         }
1084     }
1085
1086     fn encode_info_for_mod(&mut self, local_def_id: LocalDefId, md: &hir::Mod<'_>) {
1087         let tcx = self.tcx;
1088         let def_id = local_def_id.to_def_id();
1089         debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
1090
1091         // If we are encoding a proc-macro crates, `encode_info_for_mod` will
1092         // only ever get called for the crate root. We still want to encode
1093         // the crate root for consistency with other crates (some of the resolver
1094         // code uses it). However, we skip encoding anything relating to child
1095         // items - we encode information about proc-macros later on.
1096         let reexports = if !self.is_proc_macro {
1097             match tcx.module_reexports(local_def_id) {
1098                 Some(exports) => self.lazy(exports),
1099                 _ => Lazy::empty(),
1100             }
1101         } else {
1102             Lazy::empty()
1103         };
1104
1105         record!(self.tables.kind[def_id] <- EntryKind::Mod(reexports));
1106         if self.is_proc_macro {
1107             // Encode this here because we don't do it in encode_def_ids.
1108             record!(self.tables.expn_that_defined[def_id] <- tcx.expn_that_defined(local_def_id));
1109         } else {
1110             let direct_children = md.item_ids.iter().map(|item_id| item_id.def_id.local_def_index);
1111             // Foreign items are planted into their parent modules from name resolution point of view.
1112             let tcx = self.tcx;
1113             let foreign_item_children = md
1114                 .item_ids
1115                 .iter()
1116                 .filter_map(|item_id| match tcx.hir().item(*item_id).kind {
1117                     hir::ItemKind::ForeignMod { items, .. } => {
1118                         Some(items.iter().map(|fi_ref| fi_ref.id.def_id.local_def_index))
1119                     }
1120                     _ => None,
1121                 })
1122                 .flatten();
1123
1124             record!(self.tables.children[def_id] <- direct_children.chain(foreign_item_children));
1125         }
1126     }
1127
1128     fn encode_field(
1129         &mut self,
1130         adt_def: ty::AdtDef<'tcx>,
1131         variant_index: VariantIdx,
1132         field_index: usize,
1133     ) {
1134         let variant = &adt_def.variant(variant_index);
1135         let field = &variant.fields[field_index];
1136
1137         let def_id = field.did;
1138         debug!("EncodeContext::encode_field({:?})", def_id);
1139
1140         record!(self.tables.kind[def_id] <- EntryKind::Field);
1141         self.encode_ident_span(def_id, field.ident(self.tcx));
1142         self.encode_item_type(def_id);
1143     }
1144
1145     fn encode_struct_ctor(&mut self, adt_def: ty::AdtDef<'tcx>, def_id: DefId) {
1146         debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
1147         let tcx = self.tcx;
1148         let variant = adt_def.non_enum_variant();
1149
1150         let data = VariantData {
1151             ctor_kind: variant.ctor_kind,
1152             discr: variant.discr,
1153             ctor: Some(def_id.index),
1154             is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1155         };
1156
1157         record!(self.tables.repr_options[def_id] <- adt_def.repr());
1158         self.tables.impl_constness.set(def_id.index, hir::Constness::Const);
1159         record!(self.tables.kind[def_id] <- EntryKind::Struct(self.lazy(data)));
1160         self.encode_item_type(def_id);
1161         if variant.ctor_kind == CtorKind::Fn {
1162             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1163         }
1164     }
1165
1166     fn encode_explicit_item_bounds(&mut self, def_id: DefId) {
1167         debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id);
1168         let bounds = self.tcx.explicit_item_bounds(def_id);
1169         if !bounds.is_empty() {
1170             record!(self.tables.explicit_item_bounds[def_id] <- bounds);
1171         }
1172     }
1173
1174     fn encode_info_for_trait_item(&mut self, def_id: DefId) {
1175         debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
1176         let tcx = self.tcx;
1177
1178         let ast_item = tcx.hir().expect_trait_item(def_id.expect_local());
1179         let trait_item = tcx.associated_item(def_id);
1180
1181         let container = match trait_item.defaultness {
1182             hir::Defaultness::Default { has_value: true } => AssocContainer::TraitWithDefault,
1183             hir::Defaultness::Default { has_value: false } => AssocContainer::TraitRequired,
1184             hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"),
1185         };
1186
1187         match trait_item.kind {
1188             ty::AssocKind::Const => {
1189                 let rendered = rustc_hir_pretty::to_string(
1190                     &(&self.tcx.hir() as &dyn intravisit::Map<'_>),
1191                     |s| s.print_trait_item(ast_item),
1192                 );
1193
1194                 record!(self.tables.kind[def_id] <- EntryKind::AssocConst(container));
1195                 record!(self.tables.mir_const_qualif[def_id] <- mir::ConstQualifs::default());
1196                 record!(self.tables.rendered_const[def_id] <- rendered);
1197             }
1198             ty::AssocKind::Fn => {
1199                 let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind else { bug!() };
1200                 match *m {
1201                     hir::TraitFn::Required(ref names) => {
1202                         record!(self.tables.fn_arg_names[def_id] <- *names)
1203                     }
1204                     hir::TraitFn::Provided(body) => {
1205                         record!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body))
1206                     }
1207                 };
1208                 self.tables.asyncness.set(def_id.index, m_sig.header.asyncness);
1209                 self.tables.impl_constness.set(def_id.index, hir::Constness::NotConst);
1210                 record!(self.tables.kind[def_id] <- EntryKind::AssocFn(self.lazy(AssocFnData {
1211                     container,
1212                     has_self: trait_item.fn_has_self_parameter,
1213                 })));
1214             }
1215             ty::AssocKind::Type => {
1216                 self.encode_explicit_item_bounds(def_id);
1217                 record!(self.tables.kind[def_id] <- EntryKind::AssocType(container));
1218             }
1219         }
1220         self.encode_ident_span(def_id, ast_item.ident);
1221         match trait_item.kind {
1222             ty::AssocKind::Const | ty::AssocKind::Fn => {
1223                 self.encode_item_type(def_id);
1224             }
1225             ty::AssocKind::Type => {
1226                 if trait_item.defaultness.has_value() {
1227                     self.encode_item_type(def_id);
1228                 }
1229             }
1230         }
1231         if trait_item.kind == ty::AssocKind::Fn {
1232             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1233         }
1234     }
1235
1236     fn encode_info_for_impl_item(&mut self, def_id: DefId) {
1237         debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
1238         let tcx = self.tcx;
1239
1240         let ast_item = self.tcx.hir().expect_impl_item(def_id.expect_local());
1241         let impl_item = self.tcx.associated_item(def_id);
1242
1243         let container = match impl_item.defaultness {
1244             hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault,
1245             hir::Defaultness::Final => AssocContainer::ImplFinal,
1246             hir::Defaultness::Default { has_value: false } => {
1247                 span_bug!(ast_item.span, "impl items always have values (currently)")
1248             }
1249         };
1250
1251         match impl_item.kind {
1252             ty::AssocKind::Const => {
1253                 if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind {
1254                     let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id);
1255                     let const_data = self.encode_rendered_const_for_body(body_id);
1256
1257                     record!(self.tables.kind[def_id] <- EntryKind::AssocConst(container));
1258                     record!(self.tables.mir_const_qualif[def_id] <- qualifs);
1259                     record!(self.tables.rendered_const[def_id] <- const_data);
1260                 } else {
1261                     bug!()
1262                 }
1263             }
1264             ty::AssocKind::Fn => {
1265                 let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind else { bug!() };
1266                 self.tables.asyncness.set(def_id.index, sig.header.asyncness);
1267                 record!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body));
1268                 // Can be inside `impl const Trait`, so using sig.header.constness is not reliable
1269                 let constness = if self.tcx.is_const_fn_raw(def_id) {
1270                     hir::Constness::Const
1271                 } else {
1272                     hir::Constness::NotConst
1273                 };
1274                 self.tables.impl_constness.set(def_id.index, constness);
1275                 record!(self.tables.kind[def_id] <- EntryKind::AssocFn(self.lazy(AssocFnData {
1276                     container,
1277                     has_self: impl_item.fn_has_self_parameter,
1278                 })));
1279             }
1280             ty::AssocKind::Type => {
1281                 record!(self.tables.kind[def_id] <- EntryKind::AssocType(container));
1282             }
1283         }
1284         self.encode_ident_span(def_id, impl_item.ident(self.tcx));
1285         self.encode_item_type(def_id);
1286         if let Some(trait_item_def_id) = impl_item.trait_item_def_id {
1287             self.tables.trait_item_def_id.set(def_id.index, trait_item_def_id.into());
1288         }
1289         if impl_item.kind == ty::AssocKind::Fn {
1290             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1291         }
1292     }
1293
1294     fn encode_mir(&mut self) {
1295         if self.is_proc_macro {
1296             return;
1297         }
1298
1299         let keys_and_jobs = self
1300             .tcx
1301             .mir_keys(())
1302             .iter()
1303             .filter_map(|&def_id| {
1304                 let (encode_const, encode_opt) = should_encode_mir(self.tcx, def_id);
1305                 if encode_const || encode_opt {
1306                     Some((def_id, encode_const, encode_opt))
1307                 } else {
1308                     None
1309                 }
1310             })
1311             .collect::<Vec<_>>();
1312         for (def_id, encode_const, encode_opt) in keys_and_jobs.into_iter() {
1313             debug_assert!(encode_const || encode_opt);
1314
1315             debug!("EntryBuilder::encode_mir({:?})", def_id);
1316             if encode_opt {
1317                 record!(self.tables.optimized_mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id));
1318             }
1319             if encode_const {
1320                 record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- self.tcx.mir_for_ctfe(def_id));
1321
1322                 // FIXME(generic_const_exprs): this feels wrong to have in `encode_mir`
1323                 let abstract_const = self.tcx.thir_abstract_const(def_id);
1324                 if let Ok(Some(abstract_const)) = abstract_const {
1325                     record!(self.tables.thir_abstract_const[def_id.to_def_id()] <- abstract_const);
1326                 }
1327             }
1328             record!(self.tables.promoted_mir[def_id.to_def_id()] <- self.tcx.promoted_mir(def_id));
1329
1330             let instance =
1331                 ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id()));
1332             let unused = self.tcx.unused_generic_params(instance);
1333             if !unused.is_empty() {
1334                 record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused);
1335             }
1336         }
1337     }
1338
1339     fn encode_stability(&mut self, def_id: DefId) {
1340         debug!("EncodeContext::encode_stability({:?})", def_id);
1341
1342         // The query lookup can take a measurable amount of time in crates with many items. Check if
1343         // the stability attributes are even enabled before using their queries.
1344         if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
1345             if let Some(stab) = self.tcx.lookup_stability(def_id) {
1346                 record!(self.tables.lookup_stability[def_id] <- stab)
1347             }
1348         }
1349     }
1350
1351     fn encode_const_stability(&mut self, def_id: DefId) {
1352         debug!("EncodeContext::encode_const_stability({:?})", def_id);
1353
1354         // The query lookup can take a measurable amount of time in crates with many items. Check if
1355         // the stability attributes are even enabled before using their queries.
1356         if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
1357             if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1358                 record!(self.tables.lookup_const_stability[def_id] <- stab)
1359             }
1360         }
1361     }
1362
1363     fn encode_deprecation(&mut self, def_id: DefId) {
1364         debug!("EncodeContext::encode_deprecation({:?})", def_id);
1365         if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1366             record!(self.tables.lookup_deprecation_entry[def_id] <- depr);
1367         }
1368     }
1369
1370     fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> String {
1371         let hir = self.tcx.hir();
1372         let body = hir.body(body_id);
1373         rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| {
1374             s.print_expr(&body.value)
1375         })
1376     }
1377
1378     fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) {
1379         let tcx = self.tcx;
1380
1381         debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1382
1383         self.encode_ident_span(def_id, item.ident);
1384
1385         let entry_kind = match item.kind {
1386             hir::ItemKind::Static(..) => EntryKind::Static,
1387             hir::ItemKind::Const(_, body_id) => {
1388                 let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id);
1389                 let const_data = self.encode_rendered_const_for_body(body_id);
1390                 record!(self.tables.mir_const_qualif[def_id] <- qualifs);
1391                 record!(self.tables.rendered_const[def_id] <- const_data);
1392                 EntryKind::Const
1393             }
1394             hir::ItemKind::Fn(ref sig, .., body) => {
1395                 self.tables.asyncness.set(def_id.index, sig.header.asyncness);
1396                 record!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body));
1397                 self.tables.impl_constness.set(def_id.index, sig.header.constness);
1398                 EntryKind::Fn
1399             }
1400             hir::ItemKind::Macro(ref macro_def, _) => {
1401                 EntryKind::MacroDef(self.lazy(&*macro_def.body), macro_def.macro_rules)
1402             }
1403             hir::ItemKind::Mod(ref m) => {
1404                 return self.encode_info_for_mod(item.def_id, m);
1405             }
1406             hir::ItemKind::ForeignMod { .. } => EntryKind::ForeignMod,
1407             hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1408             hir::ItemKind::TyAlias(..) => EntryKind::Type,
1409             hir::ItemKind::OpaqueTy(..) => {
1410                 self.encode_explicit_item_bounds(def_id);
1411                 EntryKind::OpaqueTy
1412             }
1413             hir::ItemKind::Enum(..) => {
1414                 let adt_def = self.tcx.adt_def(def_id);
1415                 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1416                 EntryKind::Enum
1417             }
1418             hir::ItemKind::Struct(ref struct_def, _) => {
1419                 let adt_def = self.tcx.adt_def(def_id);
1420                 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1421                 self.tables.impl_constness.set(def_id.index, hir::Constness::Const);
1422
1423                 // Encode def_ids for each field and method
1424                 // for methods, write all the stuff get_trait_method
1425                 // needs to know
1426                 let ctor = struct_def
1427                     .ctor_hir_id()
1428                     .map(|ctor_hir_id| self.tcx.hir().local_def_id(ctor_hir_id).local_def_index);
1429
1430                 let variant = adt_def.non_enum_variant();
1431                 EntryKind::Struct(self.lazy(VariantData {
1432                     ctor_kind: variant.ctor_kind,
1433                     discr: variant.discr,
1434                     ctor,
1435                     is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1436                 }))
1437             }
1438             hir::ItemKind::Union(..) => {
1439                 let adt_def = self.tcx.adt_def(def_id);
1440                 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1441
1442                 let variant = adt_def.non_enum_variant();
1443                 EntryKind::Union(self.lazy(VariantData {
1444                     ctor_kind: variant.ctor_kind,
1445                     discr: variant.discr,
1446                     ctor: None,
1447                     is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1448                 }))
1449             }
1450             hir::ItemKind::Impl(hir::Impl { defaultness, constness, .. }) => {
1451                 self.tables.impl_defaultness.set(def_id.index, defaultness);
1452                 self.tables.impl_constness.set(def_id.index, constness);
1453
1454                 let trait_ref = self.tcx.impl_trait_ref(def_id);
1455                 if let Some(trait_ref) = trait_ref {
1456                     let trait_def = self.tcx.trait_def(trait_ref.def_id);
1457                     if let Some(mut an) = trait_def.ancestors(self.tcx, def_id).ok() {
1458                         if let Some(specialization_graph::Node::Impl(parent)) = an.nth(1) {
1459                             self.tables.impl_parent.set(def_id.index, parent.into());
1460                         }
1461                     }
1462
1463                     // if this is an impl of `CoerceUnsized`, create its
1464                     // "unsized info", else just store None
1465                     if Some(trait_ref.def_id) == self.tcx.lang_items().coerce_unsized_trait() {
1466                         let coerce_unsized_info =
1467                             self.tcx.at(item.span).coerce_unsized_info(def_id);
1468                         record!(self.tables.coerce_unsized_info[def_id] <- coerce_unsized_info);
1469                     }
1470                 }
1471
1472                 let polarity = self.tcx.impl_polarity(def_id);
1473                 self.tables.impl_polarity.set(def_id.index, polarity);
1474
1475                 EntryKind::Impl
1476             }
1477             hir::ItemKind::Trait(..) => {
1478                 let trait_def = self.tcx.trait_def(def_id);
1479                 record!(self.tables.trait_def[def_id] <- trait_def);
1480
1481                 EntryKind::Trait
1482             }
1483             hir::ItemKind::TraitAlias(..) => {
1484                 let trait_def = self.tcx.trait_def(def_id);
1485                 record!(self.tables.trait_def[def_id] <- trait_def);
1486
1487                 EntryKind::TraitAlias
1488             }
1489             hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {
1490                 bug!("cannot encode info for item {:?}", item)
1491             }
1492         };
1493         record!(self.tables.kind[def_id] <- entry_kind);
1494         // FIXME(eddyb) there should be a nicer way to do this.
1495         match item.kind {
1496             hir::ItemKind::Enum(..) => record!(self.tables.children[def_id] <-
1497                 self.tcx.adt_def(def_id).variants().iter().map(|v| {
1498                     assert!(v.def_id.is_local());
1499                     v.def_id.index
1500                 })
1501             ),
1502             hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
1503                 record!(self.tables.children[def_id] <-
1504                     self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| {
1505                         assert!(f.did.is_local());
1506                         f.did.index
1507                     })
1508                 )
1509             }
1510             hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => {
1511                 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1512                 record!(self.tables.children[def_id] <-
1513                     associated_item_def_ids.iter().map(|&def_id| {
1514                         assert!(def_id.is_local());
1515                         def_id.index
1516                     })
1517                 );
1518             }
1519             _ => {}
1520         }
1521         match item.kind {
1522             hir::ItemKind::Static(..)
1523             | hir::ItemKind::Const(..)
1524             | hir::ItemKind::Fn(..)
1525             | hir::ItemKind::TyAlias(..)
1526             | hir::ItemKind::OpaqueTy(..)
1527             | hir::ItemKind::Enum(..)
1528             | hir::ItemKind::Struct(..)
1529             | hir::ItemKind::Union(..)
1530             | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id),
1531             _ => {}
1532         }
1533         if let hir::ItemKind::Fn(..) = item.kind {
1534             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1535         }
1536         if let hir::ItemKind::Impl { .. } = item.kind {
1537             if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) {
1538                 record!(self.tables.impl_trait_ref[def_id] <- trait_ref);
1539             }
1540         }
1541     }
1542
1543     fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) {
1544         record!(self.tables.kind[def_id] <- kind);
1545         if encode_type {
1546             self.encode_item_type(def_id);
1547         }
1548     }
1549
1550     fn encode_info_for_closure(&mut self, hir_id: hir::HirId) {
1551         let def_id = self.tcx.hir().local_def_id(hir_id);
1552         debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1553         // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic,
1554         // including on the signature, which is inferred in `typeck.
1555         let typeck_result: &'tcx ty::TypeckResults<'tcx> = self.tcx.typeck(def_id);
1556         let ty = typeck_result.node_type(hir_id);
1557         match ty.kind() {
1558             ty::Generator(..) => {
1559                 let data = self.tcx.generator_kind(def_id).unwrap();
1560                 let generator_diagnostic_data = typeck_result.get_generator_diagnostic_data();
1561                 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Generator);
1562                 record!(self.tables.generator_kind[def_id.to_def_id()] <- data);
1563                 record!(self.tables.generator_diagnostic_data[def_id.to_def_id()]  <- generator_diagnostic_data);
1564             }
1565
1566             ty::Closure(..) => {
1567                 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Closure);
1568             }
1569
1570             _ => bug!("closure that is neither generator nor closure"),
1571         }
1572         self.encode_item_type(def_id.to_def_id());
1573         if let ty::Closure(def_id, substs) = *ty.kind() {
1574             record!(self.tables.fn_sig[def_id] <- substs.as_closure().sig());
1575         }
1576     }
1577
1578     fn encode_info_for_anon_const(&mut self, id: hir::HirId) {
1579         let def_id = self.tcx.hir().local_def_id(id);
1580         debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1581         let body_id = self.tcx.hir().body_owned_by(id);
1582         let const_data = self.encode_rendered_const_for_body(body_id);
1583         let qualifs = self.tcx.mir_const_qualif(def_id);
1584
1585         record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::AnonConst);
1586         record!(self.tables.mir_const_qualif[def_id.to_def_id()] <- qualifs);
1587         record!(self.tables.rendered_const[def_id.to_def_id()] <- const_data);
1588         self.encode_item_type(def_id.to_def_id());
1589     }
1590
1591     fn encode_native_libraries(&mut self) -> Lazy<[NativeLib]> {
1592         empty_proc_macro!(self);
1593         let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1594         self.lazy(used_libraries.iter())
1595     }
1596
1597     fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> {
1598         empty_proc_macro!(self);
1599         let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1600         self.lazy(foreign_modules.iter().map(|(_, m)| m).cloned())
1601     }
1602
1603     fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) {
1604         let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1605         let mut expn_data_table: TableBuilder<_, _> = Default::default();
1606         let mut expn_hash_table: TableBuilder<_, _> = Default::default();
1607
1608         let _: Result<(), !> = self.hygiene_ctxt.encode(
1609             &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table),
1610             |(this, syntax_contexts, _, _), index, ctxt_data| {
1611                 syntax_contexts.set(index, this.lazy(ctxt_data));
1612                 Ok(())
1613             },
1614             |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| {
1615                 if let Some(index) = index.as_local() {
1616                     expn_data_table.set(index.as_raw(), this.lazy(expn_data));
1617                     expn_hash_table.set(index.as_raw(), this.lazy(hash));
1618                 }
1619                 Ok(())
1620             },
1621         );
1622
1623         (
1624             syntax_contexts.encode(&mut self.opaque),
1625             expn_data_table.encode(&mut self.opaque),
1626             expn_hash_table.encode(&mut self.opaque),
1627         )
1628     }
1629
1630     fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
1631         let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro);
1632         if is_proc_macro {
1633             let tcx = self.tcx;
1634             let hir = tcx.hir();
1635
1636             let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index;
1637             let stability = tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX));
1638             let macros =
1639                 self.lazy(tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index));
1640             let spans = self.tcx.sess.parse_sess.proc_macro_quoted_spans();
1641             for (i, span) in spans.into_iter().enumerate() {
1642                 let span = self.lazy(span);
1643                 self.tables.proc_macro_quoted_spans.set(i, span);
1644             }
1645
1646             self.tables.opt_def_kind.set(LOCAL_CRATE.as_def_id().index, DefKind::Mod);
1647             record!(self.tables.def_span[LOCAL_CRATE.as_def_id()] <- tcx.def_span(LOCAL_CRATE.as_def_id()));
1648             record!(self.tables.attributes[LOCAL_CRATE.as_def_id()] <- tcx.get_attrs(LOCAL_CRATE.as_def_id()));
1649             record!(self.tables.visibility[LOCAL_CRATE.as_def_id()] <- tcx.visibility(LOCAL_CRATE.as_def_id()));
1650             if let Some(stability) = stability {
1651                 record!(self.tables.lookup_stability[LOCAL_CRATE.as_def_id()] <- stability);
1652             }
1653             self.encode_deprecation(LOCAL_CRATE.as_def_id());
1654
1655             // Normally, this information is encoded when we walk the items
1656             // defined in this crate. However, we skip doing that for proc-macro crates,
1657             // so we manually encode just the information that we need
1658             for &proc_macro in &tcx.resolutions(()).proc_macros {
1659                 let id = proc_macro;
1660                 let proc_macro = hir.local_def_id_to_hir_id(proc_macro);
1661                 let mut name = hir.name(proc_macro);
1662                 let span = hir.span(proc_macro);
1663                 // Proc-macros may have attributes like `#[allow_internal_unstable]`,
1664                 // so downstream crates need access to them.
1665                 let attrs = hir.attrs(proc_macro);
1666                 let macro_kind = if tcx.sess.contains_name(attrs, sym::proc_macro) {
1667                     MacroKind::Bang
1668                 } else if tcx.sess.contains_name(attrs, sym::proc_macro_attribute) {
1669                     MacroKind::Attr
1670                 } else if let Some(attr) = tcx.sess.find_by_name(attrs, sym::proc_macro_derive) {
1671                     // This unwrap chain should have been checked by the proc-macro harness.
1672                     name = attr.meta_item_list().unwrap()[0]
1673                         .meta_item()
1674                         .unwrap()
1675                         .ident()
1676                         .unwrap()
1677                         .name;
1678                     MacroKind::Derive
1679                 } else {
1680                     bug!("Unknown proc-macro type for item {:?}", id);
1681                 };
1682
1683                 let mut def_key = self.tcx.hir().def_key(id);
1684                 def_key.disambiguated_data.data = DefPathData::MacroNs(name);
1685
1686                 let def_id = id.to_def_id();
1687                 self.tables.opt_def_kind.set(def_id.index, DefKind::Macro(macro_kind));
1688                 record!(self.tables.kind[def_id] <- EntryKind::ProcMacro(macro_kind));
1689                 record!(self.tables.attributes[def_id] <- attrs);
1690                 record!(self.tables.def_keys[def_id] <- def_key);
1691                 record!(self.tables.def_ident_span[def_id] <- span);
1692                 record!(self.tables.def_span[def_id] <- span);
1693                 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1694                 if let Some(stability) = stability {
1695                     record!(self.tables.lookup_stability[def_id] <- stability);
1696                 }
1697             }
1698
1699             Some(ProcMacroData { proc_macro_decls_static, stability, macros })
1700         } else {
1701             None
1702         }
1703     }
1704
1705     fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> {
1706         empty_proc_macro!(self);
1707
1708         let deps = self
1709             .tcx
1710             .crates(())
1711             .iter()
1712             .map(|&cnum| {
1713                 let dep = CrateDep {
1714                     name: self.tcx.crate_name(cnum),
1715                     hash: self.tcx.crate_hash(cnum),
1716                     host_hash: self.tcx.crate_host_hash(cnum),
1717                     kind: self.tcx.dep_kind(cnum),
1718                     extra_filename: self.tcx.extra_filename(cnum).clone(),
1719                 };
1720                 (cnum, dep)
1721             })
1722             .collect::<Vec<_>>();
1723
1724         {
1725             // Sanity-check the crate numbers
1726             let mut expected_cnum = 1;
1727             for &(n, _) in &deps {
1728                 assert_eq!(n, CrateNum::new(expected_cnum));
1729                 expected_cnum += 1;
1730             }
1731         }
1732
1733         // We're just going to write a list of crate 'name-hash-version's, with
1734         // the assumption that they are numbered 1 to n.
1735         // FIXME (#2166): This is not nearly enough to support correct versioning
1736         // but is enough to get transitive crate dependencies working.
1737         self.lazy(deps.iter().map(|&(_, ref dep)| dep))
1738     }
1739
1740     fn encode_lib_features(&mut self) -> Lazy<[(Symbol, Option<Symbol>)]> {
1741         empty_proc_macro!(self);
1742         let tcx = self.tcx;
1743         let lib_features = tcx.lib_features(());
1744         self.lazy(lib_features.to_vec())
1745     }
1746
1747     fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> {
1748         empty_proc_macro!(self);
1749         let tcx = self.tcx;
1750         let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id;
1751         self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1752     }
1753
1754     fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> {
1755         empty_proc_macro!(self);
1756         let tcx = self.tcx;
1757         let lang_items = tcx.lang_items();
1758         let lang_items = lang_items.items().iter();
1759         self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1760             if let Some(def_id) = opt_def_id {
1761                 if def_id.is_local() {
1762                     return Some((def_id.index, i));
1763                 }
1764             }
1765             None
1766         }))
1767     }
1768
1769     fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> {
1770         empty_proc_macro!(self);
1771         let tcx = self.tcx;
1772         self.lazy(&tcx.lang_items().missing)
1773     }
1774
1775     fn encode_traits(&mut self) -> Lazy<[DefIndex]> {
1776         empty_proc_macro!(self);
1777         self.lazy(self.tcx.traits_in_crate(LOCAL_CRATE).iter().map(|def_id| def_id.index))
1778     }
1779
1780     /// Encodes an index, mapping each trait to its (local) implementations.
1781     fn encode_impls(&mut self) -> Lazy<[TraitImpls]> {
1782         debug!("EncodeContext::encode_traits_and_impls()");
1783         empty_proc_macro!(self);
1784         let tcx = self.tcx;
1785         let mut visitor = ImplsVisitor { tcx, impls: FxHashMap::default() };
1786         tcx.hir().visit_all_item_likes(&mut visitor);
1787
1788         let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1789
1790         // Bring everything into deterministic order for hashing
1791         all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id));
1792
1793         let all_impls: Vec<_> = all_impls
1794             .into_iter()
1795             .map(|(trait_def_id, mut impls)| {
1796                 // Bring everything into deterministic order for hashing
1797                 impls.sort_by_cached_key(|&(index, _)| {
1798                     tcx.hir().def_path_hash(LocalDefId { local_def_index: index })
1799                 });
1800
1801                 TraitImpls {
1802                     trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1803                     impls: self.lazy(&impls),
1804                 }
1805             })
1806             .collect();
1807
1808         self.lazy(&all_impls)
1809     }
1810
1811     fn encode_incoherent_impls(&mut self) -> Lazy<[IncoherentImpls]> {
1812         debug!("EncodeContext::encode_traits_and_impls()");
1813         empty_proc_macro!(self);
1814         let tcx = self.tcx;
1815         let mut ctx = tcx.create_stable_hashing_context();
1816         let mut all_impls: Vec<_> = tcx.crate_inherent_impls(()).incoherent_impls.iter().collect();
1817         all_impls.sort_by_cached_key(|&(&simp, _)| {
1818             let mut hasher = StableHasher::new();
1819             simp.hash_stable(&mut ctx, &mut hasher);
1820             hasher.finish::<Fingerprint>();
1821         });
1822         let all_impls: Vec<_> = all_impls
1823             .into_iter()
1824             .map(|(&simp, impls)| {
1825                 let mut impls: Vec<_> =
1826                     impls.into_iter().map(|def_id| def_id.local_def_index).collect();
1827                 impls.sort_by_cached_key(|&local_def_index| {
1828                     tcx.hir().def_path_hash(LocalDefId { local_def_index })
1829                 });
1830
1831                 IncoherentImpls { self_ty: simp, impls: self.lazy(impls) }
1832             })
1833             .collect();
1834
1835         self.lazy(&all_impls)
1836     }
1837
1838     // Encodes all symbols exported from this crate into the metadata.
1839     //
1840     // This pass is seeded off the reachability list calculated in the
1841     // middle::reachable module but filters out items that either don't have a
1842     // symbol associated with them (they weren't translated) or if they're an FFI
1843     // definition (as that's not defined in this crate).
1844     fn encode_exported_symbols(
1845         &mut self,
1846         exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)],
1847     ) -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> {
1848         empty_proc_macro!(self);
1849         // The metadata symbol name is special. It should not show up in
1850         // downstream crates.
1851         let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx));
1852
1853         self.lazy(
1854             exported_symbols
1855                 .iter()
1856                 .filter(|&&(ref exported_symbol, _)| match *exported_symbol {
1857                     ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
1858                     _ => true,
1859                 })
1860                 .cloned(),
1861         )
1862     }
1863
1864     fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option<LinkagePreference>]> {
1865         empty_proc_macro!(self);
1866         let formats = self.tcx.dependency_formats(());
1867         for (ty, arr) in formats.iter() {
1868             if *ty != CrateType::Dylib {
1869                 continue;
1870             }
1871             return self.lazy(arr.iter().map(|slot| match *slot {
1872                 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
1873
1874                 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1875                 Linkage::Static => Some(LinkagePreference::RequireStatic),
1876             }));
1877         }
1878         Lazy::empty()
1879     }
1880
1881     fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) {
1882         let tcx = self.tcx;
1883
1884         debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1885
1886         match nitem.kind {
1887             hir::ForeignItemKind::Fn(_, ref names, _) => {
1888                 self.tables.asyncness.set(def_id.index, hir::IsAsync::NotAsync);
1889                 record!(self.tables.fn_arg_names[def_id] <- *names);
1890                 let constness = if self.tcx.is_const_fn_raw(def_id) {
1891                     hir::Constness::Const
1892                 } else {
1893                     hir::Constness::NotConst
1894                 };
1895                 self.tables.impl_constness.set(def_id.index, constness);
1896                 record!(self.tables.kind[def_id] <- EntryKind::ForeignFn);
1897             }
1898             hir::ForeignItemKind::Static(..) => {
1899                 record!(self.tables.kind[def_id] <- EntryKind::ForeignStatic);
1900             }
1901             hir::ForeignItemKind::Type => {
1902                 record!(self.tables.kind[def_id] <- EntryKind::ForeignType);
1903             }
1904         }
1905         self.encode_ident_span(def_id, nitem.ident);
1906         self.encode_item_type(def_id);
1907         if let hir::ForeignItemKind::Fn(..) = nitem.kind {
1908             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1909         }
1910     }
1911 }
1912
1913 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
1914 impl<'a, 'tcx> Visitor<'tcx> for EncodeContext<'a, 'tcx> {
1915     type NestedFilter = nested_filter::OnlyBodies;
1916
1917     fn nested_visit_map(&mut self) -> Self::Map {
1918         self.tcx.hir()
1919     }
1920     fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
1921         intravisit::walk_expr(self, ex);
1922         self.encode_info_for_expr(ex);
1923     }
1924     fn visit_anon_const(&mut self, c: &'tcx AnonConst) {
1925         intravisit::walk_anon_const(self, c);
1926         self.encode_info_for_anon_const(c.hir_id);
1927     }
1928     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1929         intravisit::walk_item(self, item);
1930         match item.kind {
1931             hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these
1932             _ => self.encode_info_for_item(item.def_id.to_def_id(), item),
1933         }
1934         self.encode_addl_info_for_item(item);
1935     }
1936     fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) {
1937         intravisit::walk_foreign_item(self, ni);
1938         self.encode_info_for_foreign_item(ni.def_id.to_def_id(), ni);
1939     }
1940     fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1941         intravisit::walk_generics(self, generics);
1942         self.encode_info_for_generics(generics);
1943     }
1944 }
1945
1946 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1947     fn encode_fields(&mut self, adt_def: ty::AdtDef<'tcx>) {
1948         for (variant_index, variant) in adt_def.variants().iter_enumerated() {
1949             for (field_index, _field) in variant.fields.iter().enumerate() {
1950                 self.encode_field(adt_def, variant_index, field_index);
1951             }
1952         }
1953     }
1954
1955     fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) {
1956         for param in generics.params {
1957             let def_id = self.tcx.hir().local_def_id(param.hir_id);
1958             match param.kind {
1959                 GenericParamKind::Lifetime { .. } => continue,
1960                 GenericParamKind::Type { default, .. } => {
1961                     self.encode_info_for_generic_param(
1962                         def_id.to_def_id(),
1963                         EntryKind::TypeParam,
1964                         default.is_some(),
1965                     );
1966                 }
1967                 GenericParamKind::Const { ref default, .. } => {
1968                     let def_id = def_id.to_def_id();
1969                     self.encode_info_for_generic_param(def_id, EntryKind::ConstParam, true);
1970                     if default.is_some() {
1971                         record!(self.tables.const_param_default[def_id] <- self.tcx.const_param_default(def_id))
1972                     }
1973                 }
1974             }
1975         }
1976     }
1977
1978     fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) {
1979         if let hir::ExprKind::Closure(..) = expr.kind {
1980             self.encode_info_for_closure(expr.hir_id);
1981         }
1982     }
1983
1984     fn encode_ident_span(&mut self, def_id: DefId, ident: Ident) {
1985         record!(self.tables.def_ident_span[def_id] <- ident.span);
1986     }
1987
1988     /// In some cases, along with the item itself, we also
1989     /// encode some sub-items. Usually we want some info from the item
1990     /// so it's easier to do that here then to wait until we would encounter
1991     /// normally in the visitor walk.
1992     fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) {
1993         match item.kind {
1994             hir::ItemKind::Static(..)
1995             | hir::ItemKind::Const(..)
1996             | hir::ItemKind::Fn(..)
1997             | hir::ItemKind::Macro(..)
1998             | hir::ItemKind::Mod(..)
1999             | hir::ItemKind::ForeignMod { .. }
2000             | hir::ItemKind::GlobalAsm(..)
2001             | hir::ItemKind::ExternCrate(..)
2002             | hir::ItemKind::Use(..)
2003             | hir::ItemKind::TyAlias(..)
2004             | hir::ItemKind::OpaqueTy(..)
2005             | hir::ItemKind::TraitAlias(..) => {
2006                 // no sub-item recording needed in these cases
2007             }
2008             hir::ItemKind::Enum(..) => {
2009                 let def = self.tcx.adt_def(item.def_id.to_def_id());
2010                 self.encode_fields(def);
2011
2012                 for (i, variant) in def.variants().iter_enumerated() {
2013                     self.encode_enum_variant_info(def, i);
2014
2015                     if let Some(_ctor_def_id) = variant.ctor_def_id {
2016                         self.encode_enum_variant_ctor(def, i);
2017                     }
2018                 }
2019             }
2020             hir::ItemKind::Struct(ref struct_def, _) => {
2021                 let def = self.tcx.adt_def(item.def_id.to_def_id());
2022                 self.encode_fields(def);
2023
2024                 // If the struct has a constructor, encode it.
2025                 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
2026                     let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
2027                     self.encode_struct_ctor(def, ctor_def_id.to_def_id());
2028                 }
2029             }
2030             hir::ItemKind::Union(..) => {
2031                 let def = self.tcx.adt_def(item.def_id.to_def_id());
2032                 self.encode_fields(def);
2033             }
2034             hir::ItemKind::Impl { .. } => {
2035                 for &trait_item_def_id in
2036                     self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter()
2037                 {
2038                     self.encode_info_for_impl_item(trait_item_def_id);
2039                 }
2040             }
2041             hir::ItemKind::Trait(..) => {
2042                 for &item_def_id in self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter()
2043                 {
2044                     self.encode_info_for_trait_item(item_def_id);
2045                 }
2046             }
2047         }
2048     }
2049 }
2050
2051 struct ImplsVisitor<'tcx> {
2052     tcx: TyCtxt<'tcx>,
2053     impls: FxHashMap<DefId, Vec<(DefIndex, Option<SimplifiedType>)>>,
2054 }
2055
2056 impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplsVisitor<'tcx> {
2057     fn visit_item(&mut self, item: &hir::Item<'_>) {
2058         match item.kind {
2059             hir::ItemKind::Impl(..) => {
2060                 if let Some(trait_ref) = self.tcx.impl_trait_ref(item.def_id.to_def_id()) {
2061                     let simplified_self_ty = fast_reject::simplify_type(
2062                         self.tcx,
2063                         trait_ref.self_ty(),
2064                         TreatParams::AsPlaceholders,
2065                     );
2066
2067                     self.impls
2068                         .entry(trait_ref.def_id)
2069                         .or_default()
2070                         .push((item.def_id.local_def_index, simplified_self_ty));
2071                 }
2072             }
2073             _ => {}
2074         }
2075     }
2076
2077     fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem<'v>) {}
2078
2079     fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem<'v>) {
2080         // handled in `visit_item` above
2081     }
2082
2083     fn visit_foreign_item(&mut self, _foreign_item: &'v hir::ForeignItem<'v>) {}
2084 }
2085
2086 /// Used to prefetch queries which will be needed later by metadata encoding.
2087 /// Only a subset of the queries are actually prefetched to keep this code smaller.
2088 fn prefetch_mir(tcx: TyCtxt<'_>) {
2089     if !tcx.sess.opts.output_types.should_codegen() {
2090         // We won't emit MIR, so don't prefetch it.
2091         return;
2092     }
2093
2094     par_iter(tcx.mir_keys(())).for_each(|&def_id| {
2095         let (encode_const, encode_opt) = should_encode_mir(tcx, def_id);
2096
2097         if encode_const {
2098             tcx.ensure().mir_for_ctfe(def_id);
2099         }
2100         if encode_opt {
2101             tcx.ensure().optimized_mir(def_id);
2102         }
2103         if encode_opt || encode_const {
2104             tcx.ensure().promoted_mir(def_id);
2105         }
2106     })
2107 }
2108
2109 // NOTE(eddyb) The following comment was preserved for posterity, even
2110 // though it's no longer relevant as EBML (which uses nested & tagged
2111 // "documents") was replaced with a scheme that can't go out of bounds.
2112 //
2113 // And here we run into yet another obscure archive bug: in which metadata
2114 // loaded from archives may have trailing garbage bytes. Awhile back one of
2115 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
2116 // and opt) by having ebml generate an out-of-bounds panic when looking at
2117 // metadata.
2118 //
2119 // Upon investigation it turned out that the metadata file inside of an rlib
2120 // (and ar archive) was being corrupted. Some compilations would generate a
2121 // metadata file which would end in a few extra bytes, while other
2122 // compilations would not have these extra bytes appended to the end. These
2123 // extra bytes were interpreted by ebml as an extra tag, so they ended up
2124 // being interpreted causing the out-of-bounds.
2125 //
2126 // The root cause of why these extra bytes were appearing was never
2127 // discovered, and in the meantime the solution we're employing is to insert
2128 // the length of the metadata to the start of the metadata. Later on this
2129 // will allow us to slice the metadata to the precise length that we just
2130 // generated regardless of trailing bytes that end up in it.
2131
2132 #[derive(Encodable, Decodable)]
2133 pub struct EncodedMetadata {
2134     raw_data: Vec<u8>,
2135 }
2136
2137 impl EncodedMetadata {
2138     #[inline]
2139     pub fn new() -> EncodedMetadata {
2140         EncodedMetadata { raw_data: Vec::new() }
2141     }
2142
2143     #[inline]
2144     pub fn raw_data(&self) -> &[u8] {
2145         &self.raw_data
2146     }
2147 }
2148
2149 pub fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata {
2150     let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata");
2151
2152     // Since encoding metadata is not in a query, and nothing is cached,
2153     // there's no need to do dep-graph tracking for any of it.
2154     tcx.dep_graph.assert_ignored();
2155
2156     join(
2157         || encode_metadata_impl(tcx),
2158         || {
2159             if tcx.sess.threads() == 1 {
2160                 return;
2161             }
2162             // Prefetch some queries used by metadata encoding.
2163             // This is not necessary for correctness, but is only done for performance reasons.
2164             // It can be removed if it turns out to cause trouble or be detrimental to performance.
2165             join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE));
2166         },
2167     )
2168     .0
2169 }
2170
2171 fn encode_metadata_impl(tcx: TyCtxt<'_>) -> EncodedMetadata {
2172     let mut encoder = opaque::Encoder::new(vec![]);
2173     encoder.emit_raw_bytes(METADATA_HEADER).unwrap();
2174
2175     // Will be filled with the root position after encoding everything.
2176     encoder.emit_raw_bytes(&[0, 0, 0, 0]).unwrap();
2177
2178     let source_map_files = tcx.sess.source_map().files();
2179     let source_file_cache = (source_map_files[0].clone(), 0);
2180     let required_source_files = Some(GrowableBitSet::with_capacity(source_map_files.len()));
2181     drop(source_map_files);
2182
2183     let hygiene_ctxt = HygieneEncodeContext::default();
2184
2185     let mut ecx = EncodeContext {
2186         opaque: encoder,
2187         tcx,
2188         feat: tcx.features(),
2189         tables: Default::default(),
2190         lazy_state: LazyState::NoNode,
2191         type_shorthands: Default::default(),
2192         predicate_shorthands: Default::default(),
2193         source_file_cache,
2194         interpret_allocs: Default::default(),
2195         required_source_files,
2196         is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro),
2197         hygiene_ctxt: &hygiene_ctxt,
2198     };
2199
2200     // Encode the rustc version string in a predictable location.
2201     rustc_version().encode(&mut ecx).unwrap();
2202
2203     // Encode all the entries and extra information in the crate,
2204     // culminating in the `CrateRoot` which points to all of it.
2205     let root = ecx.encode_crate_root();
2206
2207     let mut result = ecx.opaque.into_inner();
2208
2209     // Encode the root position.
2210     let header = METADATA_HEADER.len();
2211     let pos = root.position.get();
2212     result[header + 0] = (pos >> 24) as u8;
2213     result[header + 1] = (pos >> 16) as u8;
2214     result[header + 2] = (pos >> 8) as u8;
2215     result[header + 3] = (pos >> 0) as u8;
2216
2217     // Record metadata size for self-profiling
2218     tcx.prof.artifact_size("crate_metadata", "crate_metadata", result.len() as u64);
2219
2220     EncodedMetadata { raw_data: result }
2221 }
2222
2223 pub fn provide(providers: &mut Providers) {
2224     *providers = Providers {
2225         traits_in_crate: |tcx, cnum| {
2226             assert_eq!(cnum, LOCAL_CRATE);
2227
2228             #[derive(Default)]
2229             struct TraitsVisitor {
2230                 traits: Vec<DefId>,
2231             }
2232             impl ItemLikeVisitor<'_> for TraitsVisitor {
2233                 fn visit_item(&mut self, item: &hir::Item<'_>) {
2234                     if let hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) = item.kind {
2235                         self.traits.push(item.def_id.to_def_id());
2236                     }
2237                 }
2238                 fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem<'_>) {}
2239                 fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem<'_>) {}
2240                 fn visit_foreign_item(&mut self, _foreign_item: &hir::ForeignItem<'_>) {}
2241             }
2242
2243             let mut visitor = TraitsVisitor::default();
2244             tcx.hir().visit_all_item_likes(&mut visitor);
2245             // Bring everything into deterministic order.
2246             visitor.traits.sort_by_cached_key(|&def_id| tcx.def_path_hash(def_id));
2247             tcx.arena.alloc_slice(&visitor.traits)
2248         },
2249
2250         ..*providers
2251     };
2252 }