]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/rmeta/decoder.rs
Rollup merge of #70145 - lzutao:patch-1, r=Dylan-DPC
[rust.git] / src / librustc_metadata / rmeta / decoder.rs
1 // Decoding metadata from a single crate's metadata
2
3 use crate::creader::CrateMetadataRef;
4 use crate::rmeta::table::{FixedSizeEncoding, Table};
5 use crate::rmeta::*;
6
7 use rustc::dep_graph::{self, DepNode, DepNodeIndex};
8 use rustc::hir::exports::Export;
9 use rustc::hir::map::definitions::DefPathTable;
10 use rustc::hir::map::{DefKey, DefPath, DefPathData, DefPathHash};
11 use rustc::middle::cstore::{CrateSource, ExternCrate};
12 use rustc::middle::cstore::{ForeignModule, LinkagePreference, NativeLibrary};
13 use rustc::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel};
14 use rustc::middle::lang_items;
15 use rustc::mir::interpret::{AllocDecodingSession, AllocDecodingState};
16 use rustc::mir::{self, interpret, BodyAndCache, Promoted};
17 use rustc::ty::codec::TyDecoder;
18 use rustc::ty::{self, Ty, TyCtxt};
19 use rustc::util::common::record_time;
20 use rustc_ast::ast::{self, Ident};
21 use rustc_attr as attr;
22 use rustc_data_structures::captures::Captures;
23 use rustc_data_structures::fingerprint::Fingerprint;
24 use rustc_data_structures::fx::FxHashMap;
25 use rustc_data_structures::svh::Svh;
26 use rustc_data_structures::sync::{AtomicCell, Lock, LockGuard, Lrc, Once};
27 use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind};
28 use rustc_expand::proc_macro::{AttrProcMacro, BangProcMacro, ProcMacroDerive};
29 use rustc_hir as hir;
30 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
31 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
32 use rustc_index::vec::{Idx, IndexVec};
33 use rustc_serialize::{opaque, Decodable, Decoder, SpecializedDecoder};
34 use rustc_session::Session;
35 use rustc_span::source_map::{self, respan, Spanned};
36 use rustc_span::symbol::{sym, Symbol};
37 use rustc_span::{self, hygiene::MacroKind, BytePos, Pos, Span, DUMMY_SP};
38
39 use log::debug;
40 use proc_macro::bridge::client::ProcMacro;
41 use std::io;
42 use std::mem;
43 use std::num::NonZeroUsize;
44 use std::u32;
45
46 pub use cstore_impl::{provide, provide_extern};
47
48 mod cstore_impl;
49
50 crate struct MetadataBlob(MetadataRef);
51
52 // A map from external crate numbers (as decoded from some crate file) to
53 // local crate numbers (as generated during this session). Each external
54 // crate may refer to types in other external crates, and each has their
55 // own crate numbers.
56 crate type CrateNumMap = IndexVec<CrateNum, CrateNum>;
57
58 crate struct CrateMetadata {
59     /// The primary crate data - binary metadata blob.
60     blob: MetadataBlob,
61
62     // --- Some data pre-decoded from the metadata blob, usually for performance ---
63     /// Properties of the whole crate.
64     /// NOTE(eddyb) we pass `'static` to a `'tcx` parameter because this
65     /// lifetime is only used behind `Lazy`, and therefore acts like an
66     /// universal (`for<'tcx>`), that is paired up with whichever `TyCtxt`
67     /// is being used to decode those values.
68     root: CrateRoot<'static>,
69     /// For each definition in this crate, we encode a key. When the
70     /// crate is loaded, we read all the keys and put them in this
71     /// hashmap, which gives the reverse mapping. This allows us to
72     /// quickly retrace a `DefPath`, which is needed for incremental
73     /// compilation support.
74     def_path_table: DefPathTable,
75     /// Trait impl data.
76     /// FIXME: Used only from queries and can use query cache,
77     /// so pre-decoding can probably be avoided.
78     trait_impls: FxHashMap<(u32, DefIndex), Lazy<[DefIndex]>>,
79     /// Proc macro descriptions for this crate, if it's a proc macro crate.
80     raw_proc_macros: Option<&'static [ProcMacro]>,
81     /// Source maps for code from the crate.
82     source_map_import_info: Once<Vec<ImportedSourceFile>>,
83     /// Used for decoding interpret::AllocIds in a cached & thread-safe manner.
84     alloc_decoding_state: AllocDecodingState,
85     /// The `DepNodeIndex` of the `DepNode` representing this upstream crate.
86     /// It is initialized on the first access in `get_crate_dep_node_index()`.
87     /// Do not access the value directly, as it might not have been initialized yet.
88     /// The field must always be initialized to `DepNodeIndex::INVALID`.
89     dep_node_index: AtomicCell<DepNodeIndex>,
90
91     // --- Other significant crate properties ---
92     /// ID of this crate, from the current compilation session's point of view.
93     cnum: CrateNum,
94     /// Maps crate IDs as they are were seen from this crate's compilation sessions into
95     /// IDs as they are seen from the current compilation session.
96     cnum_map: CrateNumMap,
97     /// Same ID set as `cnum_map` plus maybe some injected crates like panic runtime.
98     dependencies: Lock<Vec<CrateNum>>,
99     /// How to link (or not link) this crate to the currently compiled crate.
100     dep_kind: Lock<DepKind>,
101     /// Filesystem location of this crate.
102     source: CrateSource,
103     /// Whether or not this crate should be consider a private dependency
104     /// for purposes of the 'exported_private_dependencies' lint
105     private_dep: bool,
106     /// The hash for the host proc macro. Used to support `-Z dual-proc-macro`.
107     host_hash: Option<Svh>,
108
109     // --- Data used only for improving diagnostics ---
110     /// Information about the `extern crate` item or path that caused this crate to be loaded.
111     /// If this is `None`, then the crate was injected (e.g., by the allocator).
112     extern_crate: Lock<Option<ExternCrate>>,
113 }
114
115 /// Holds information about a rustc_span::SourceFile imported from another crate.
116 /// See `imported_source_files()` for more information.
117 struct ImportedSourceFile {
118     /// This SourceFile's byte-offset within the source_map of its original crate
119     original_start_pos: rustc_span::BytePos,
120     /// The end of this SourceFile within the source_map of its original crate
121     original_end_pos: rustc_span::BytePos,
122     /// The imported SourceFile's representation within the local source_map
123     translated_source_file: Lrc<rustc_span::SourceFile>,
124 }
125
126 pub(super) struct DecodeContext<'a, 'tcx> {
127     opaque: opaque::Decoder<'a>,
128     cdata: Option<CrateMetadataRef<'a>>,
129     sess: Option<&'tcx Session>,
130     tcx: Option<TyCtxt<'tcx>>,
131
132     // Cache the last used source_file for translating spans as an optimization.
133     last_source_file_index: usize,
134
135     lazy_state: LazyState,
136
137     // Used for decoding interpret::AllocIds in a cached & thread-safe manner.
138     alloc_decoding_session: Option<AllocDecodingSession<'a>>,
139 }
140
141 /// Abstract over the various ways one can create metadata decoders.
142 pub(super) trait Metadata<'a, 'tcx>: Copy {
143     fn raw_bytes(self) -> &'a [u8];
144     fn cdata(self) -> Option<CrateMetadataRef<'a>> {
145         None
146     }
147     fn sess(self) -> Option<&'tcx Session> {
148         None
149     }
150     fn tcx(self) -> Option<TyCtxt<'tcx>> {
151         None
152     }
153
154     fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> {
155         let tcx = self.tcx();
156         DecodeContext {
157             opaque: opaque::Decoder::new(self.raw_bytes(), pos),
158             cdata: self.cdata(),
159             sess: self.sess().or(tcx.map(|tcx| tcx.sess)),
160             tcx,
161             last_source_file_index: 0,
162             lazy_state: LazyState::NoNode,
163             alloc_decoding_session: self
164                 .cdata()
165                 .map(|cdata| cdata.cdata.alloc_decoding_state.new_decoding_session()),
166         }
167     }
168 }
169
170 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob {
171     fn raw_bytes(self) -> &'a [u8] {
172         &self.0
173     }
174 }
175
176 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a MetadataBlob, &'tcx Session) {
177     fn raw_bytes(self) -> &'a [u8] {
178         let (blob, _) = self;
179         &blob.0
180     }
181
182     fn sess(self) -> Option<&'tcx Session> {
183         let (_, sess) = self;
184         Some(sess)
185     }
186 }
187
188 impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a CrateMetadataRef<'a> {
189     fn raw_bytes(self) -> &'a [u8] {
190         self.blob.raw_bytes()
191     }
192     fn cdata(self) -> Option<CrateMetadataRef<'a>> {
193         Some(*self)
194     }
195 }
196
197 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadataRef<'a>, &'tcx Session) {
198     fn raw_bytes(self) -> &'a [u8] {
199         self.0.raw_bytes()
200     }
201     fn cdata(self) -> Option<CrateMetadataRef<'a>> {
202         Some(*self.0)
203     }
204     fn sess(self) -> Option<&'tcx Session> {
205         Some(&self.1)
206     }
207 }
208
209 impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadataRef<'a>, TyCtxt<'tcx>) {
210     fn raw_bytes(self) -> &'a [u8] {
211         self.0.raw_bytes()
212     }
213     fn cdata(self) -> Option<CrateMetadataRef<'a>> {
214         Some(*self.0)
215     }
216     fn tcx(self) -> Option<TyCtxt<'tcx>> {
217         Some(self.1)
218     }
219 }
220
221 impl<'a, 'tcx, T: Decodable> Lazy<T> {
222     fn decode<M: Metadata<'a, 'tcx>>(self, metadata: M) -> T {
223         let mut dcx = metadata.decoder(self.position.get());
224         dcx.lazy_state = LazyState::NodeStart(self.position);
225         T::decode(&mut dcx).unwrap()
226     }
227 }
228
229 impl<'a: 'x, 'tcx: 'x, 'x, T: Decodable> Lazy<[T]> {
230     fn decode<M: Metadata<'a, 'tcx>>(
231         self,
232         metadata: M,
233     ) -> impl ExactSizeIterator<Item = T> + Captures<'a> + Captures<'tcx> + 'x {
234         let mut dcx = metadata.decoder(self.position.get());
235         dcx.lazy_state = LazyState::NodeStart(self.position);
236         (0..self.meta).map(move |_| T::decode(&mut dcx).unwrap())
237     }
238 }
239
240 impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
241     fn tcx(&self) -> TyCtxt<'tcx> {
242         self.tcx.expect("missing TyCtxt in DecodeContext")
243     }
244
245     fn cdata(&self) -> CrateMetadataRef<'a> {
246         self.cdata.expect("missing CrateMetadata in DecodeContext")
247     }
248
249     fn read_lazy_with_meta<T: ?Sized + LazyMeta>(
250         &mut self,
251         meta: T::Meta,
252     ) -> Result<Lazy<T>, <Self as Decoder>::Error> {
253         let min_size = T::min_size(meta);
254         let distance = self.read_usize()?;
255         let position = match self.lazy_state {
256             LazyState::NoNode => bug!("read_lazy_with_meta: outside of a metadata node"),
257             LazyState::NodeStart(start) => {
258                 let start = start.get();
259                 assert!(distance + min_size <= start);
260                 start - distance - min_size
261             }
262             LazyState::Previous(last_min_end) => last_min_end.get() + distance,
263         };
264         self.lazy_state = LazyState::Previous(NonZeroUsize::new(position + min_size).unwrap());
265         Ok(Lazy::from_position_and_meta(NonZeroUsize::new(position).unwrap(), meta))
266     }
267 }
268
269 impl<'a, 'tcx> TyDecoder<'tcx> for DecodeContext<'a, 'tcx> {
270     #[inline]
271     fn tcx(&self) -> TyCtxt<'tcx> {
272         self.tcx.expect("missing TyCtxt in DecodeContext")
273     }
274
275     #[inline]
276     fn peek_byte(&self) -> u8 {
277         self.opaque.data[self.opaque.position()]
278     }
279
280     #[inline]
281     fn position(&self) -> usize {
282         self.opaque.position()
283     }
284
285     fn cached_ty_for_shorthand<F>(
286         &mut self,
287         shorthand: usize,
288         or_insert_with: F,
289     ) -> Result<Ty<'tcx>, Self::Error>
290     where
291         F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>,
292     {
293         let tcx = self.tcx();
294
295         let key = ty::CReaderCacheKey { cnum: self.cdata().cnum, pos: shorthand };
296
297         if let Some(&ty) = tcx.rcache.borrow().get(&key) {
298             return Ok(ty);
299         }
300
301         let ty = or_insert_with(self)?;
302         tcx.rcache.borrow_mut().insert(key, ty);
303         Ok(ty)
304     }
305
306     fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
307     where
308         F: FnOnce(&mut Self) -> R,
309     {
310         let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
311         let old_opaque = mem::replace(&mut self.opaque, new_opaque);
312         let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode);
313         let r = f(self);
314         self.opaque = old_opaque;
315         self.lazy_state = old_state;
316         r
317     }
318
319     fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
320         if cnum == LOCAL_CRATE { self.cdata().cnum } else { self.cdata().cnum_map[cnum] }
321     }
322 }
323
324 impl<'a, 'tcx, T> SpecializedDecoder<Lazy<T>> for DecodeContext<'a, 'tcx> {
325     fn specialized_decode(&mut self) -> Result<Lazy<T>, Self::Error> {
326         self.read_lazy_with_meta(())
327     }
328 }
329
330 impl<'a, 'tcx, T> SpecializedDecoder<Lazy<[T]>> for DecodeContext<'a, 'tcx> {
331     fn specialized_decode(&mut self) -> Result<Lazy<[T]>, Self::Error> {
332         let len = self.read_usize()?;
333         if len == 0 { Ok(Lazy::empty()) } else { self.read_lazy_with_meta(len) }
334     }
335 }
336
337 impl<'a, 'tcx, I: Idx, T> SpecializedDecoder<Lazy<Table<I, T>>> for DecodeContext<'a, 'tcx>
338 where
339     Option<T>: FixedSizeEncoding,
340 {
341     fn specialized_decode(&mut self) -> Result<Lazy<Table<I, T>>, Self::Error> {
342         let len = self.read_usize()?;
343         self.read_lazy_with_meta(len)
344     }
345 }
346
347 impl<'a, 'tcx> SpecializedDecoder<DefId> for DecodeContext<'a, 'tcx> {
348     #[inline]
349     fn specialized_decode(&mut self) -> Result<DefId, Self::Error> {
350         let krate = CrateNum::decode(self)?;
351         let index = DefIndex::decode(self)?;
352
353         Ok(DefId { krate, index })
354     }
355 }
356
357 impl<'a, 'tcx> SpecializedDecoder<DefIndex> for DecodeContext<'a, 'tcx> {
358     #[inline]
359     fn specialized_decode(&mut self) -> Result<DefIndex, Self::Error> {
360         Ok(DefIndex::from_u32(self.read_u32()?))
361     }
362 }
363
364 impl<'a, 'tcx> SpecializedDecoder<LocalDefId> for DecodeContext<'a, 'tcx> {
365     #[inline]
366     fn specialized_decode(&mut self) -> Result<LocalDefId, Self::Error> {
367         Ok(DefId::decode(self)?.expect_local())
368     }
369 }
370
371 impl<'a, 'tcx> SpecializedDecoder<interpret::AllocId> for DecodeContext<'a, 'tcx> {
372     fn specialized_decode(&mut self) -> Result<interpret::AllocId, Self::Error> {
373         if let Some(alloc_decoding_session) = self.alloc_decoding_session {
374             alloc_decoding_session.decode_alloc_id(self)
375         } else {
376             bug!("Attempting to decode interpret::AllocId without CrateMetadata")
377         }
378     }
379 }
380
381 impl<'a, 'tcx> SpecializedDecoder<Span> for DecodeContext<'a, 'tcx> {
382     fn specialized_decode(&mut self) -> Result<Span, Self::Error> {
383         let tag = u8::decode(self)?;
384
385         if tag == TAG_INVALID_SPAN {
386             return Ok(DUMMY_SP);
387         }
388
389         debug_assert!(tag == TAG_VALID_SPAN_LOCAL || tag == TAG_VALID_SPAN_FOREIGN);
390
391         let lo = BytePos::decode(self)?;
392         let len = BytePos::decode(self)?;
393         let hi = lo + len;
394
395         let sess = if let Some(sess) = self.sess {
396             sess
397         } else {
398             bug!("Cannot decode Span without Session.")
399         };
400
401         // There are two possibilities here:
402         // 1. This is a 'local span', which is located inside a `SourceFile`
403         // that came from this crate. In this case, we use the source map data
404         // encoded in this crate. This branch should be taken nearly all of the time.
405         // 2. This is a 'foreign span', which is located inside a `SourceFile`
406         // that came from a *different* crate (some crate upstream of the one
407         // whose metadata we're looking at). For example, consider this dependency graph:
408         //
409         // A -> B -> C
410         //
411         // Suppose that we're currently compiling crate A, and start deserializing
412         // metadata from crate B. When we deserialize a Span from crate B's metadata,
413         // there are two posibilites:
414         //
415         // 1. The span references a file from crate B. This makes it a 'local' span,
416         // which means that we can use crate B's serialized source map information.
417         // 2. The span references a file from crate C. This makes it a 'foreign' span,
418         // which means we need to use Crate *C* (not crate B) to determine the source
419         // map information. We only record source map information for a file in the
420         // crate that 'owns' it, so deserializing a Span may require us to look at
421         // a transitive dependency.
422         //
423         // When we encode a foreign span, we adjust its 'lo' and 'high' values
424         // to be based on the *foreign* crate (e.g. crate C), not the crate
425         // we are writing metadata for (e.g. crate B). This allows us to
426         // treat the 'local' and 'foreign' cases almost identically during deserialization:
427         // we can call `imported_source_files` for the proper crate, and binary search
428         // through the returned slice using our span.
429         let imported_source_files = if tag == TAG_VALID_SPAN_LOCAL {
430             self.cdata().imported_source_files(sess.source_map())
431         } else {
432             // FIXME: We don't decode dependencies of proc-macros.
433             // Remove this once #69976 is merged
434             if self.cdata().root.is_proc_macro_crate() {
435                 debug!(
436                     "SpecializedDecoder<Span>::specialized_decode: skipping span for proc-macro crate {:?}",
437                     self.cdata().cnum
438                 );
439                 // Decode `CrateNum` as u32 - using `CrateNum::decode` will ICE
440                 // since we don't have `cnum_map` populated.
441                 // This advances the decoder position so that we can continue
442                 // to read metadata.
443                 let _ = u32::decode(self)?;
444                 return Ok(DUMMY_SP);
445             }
446             // tag is TAG_VALID_SPAN_FOREIGN, checked by `debug_assert` above
447             let cnum = CrateNum::decode(self)?;
448             debug!(
449                 "SpecializedDecoder<Span>::specialized_decode: loading source files from cnum {:?}",
450                 cnum
451             );
452
453             // Decoding 'foreign' spans should be rare enough that it's
454             // not worth it to maintain a per-CrateNum cache for `last_source_file_index`.
455             // We just set it to 0, to ensure that we don't try to access something out
456             // of bounds for our initial 'guess'
457             self.last_source_file_index = 0;
458
459             let foreign_data = self.cdata().cstore.get_crate_data(cnum);
460             foreign_data.imported_source_files(sess.source_map())
461         };
462
463         let source_file = {
464             // Optimize for the case that most spans within a translated item
465             // originate from the same source_file.
466             let last_source_file = &imported_source_files[self.last_source_file_index];
467
468             if lo >= last_source_file.original_start_pos && lo <= last_source_file.original_end_pos
469             {
470                 last_source_file
471             } else {
472                 let index = imported_source_files
473                     .binary_search_by_key(&lo, |source_file| source_file.original_start_pos)
474                     .unwrap_or_else(|index| index - 1);
475
476                 // Don't try to cache the index for foreign spans,
477                 // as this would require a map from CrateNums to indices
478                 if tag == TAG_VALID_SPAN_LOCAL {
479                     self.last_source_file_index = index;
480                 }
481                 &imported_source_files[index]
482             }
483         };
484
485         // Make sure our binary search above is correct.
486         debug_assert!(
487             lo >= source_file.original_start_pos && lo <= source_file.original_end_pos,
488             "Bad binary search: lo={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}",
489             lo,
490             source_file.original_start_pos,
491             source_file.original_end_pos
492         );
493
494         // Make sure we correctly filtered out invalid spans during encoding
495         debug_assert!(
496             hi >= source_file.original_start_pos && hi <= source_file.original_end_pos,
497             "Bad binary search: hi={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}",
498             hi,
499             source_file.original_start_pos,
500             source_file.original_end_pos
501         );
502
503         let lo =
504             (lo + source_file.translated_source_file.start_pos) - source_file.original_start_pos;
505         let hi =
506             (hi + source_file.translated_source_file.start_pos) - source_file.original_start_pos;
507
508         Ok(Span::with_root_ctxt(lo, hi))
509     }
510 }
511
512 impl SpecializedDecoder<Ident> for DecodeContext<'_, '_> {
513     fn specialized_decode(&mut self) -> Result<Ident, Self::Error> {
514         // FIXME(jseyfried): intercrate hygiene
515
516         Ok(Ident::with_dummy_span(Symbol::decode(self)?))
517     }
518 }
519
520 impl<'a, 'tcx> SpecializedDecoder<Fingerprint> for DecodeContext<'a, 'tcx> {
521     fn specialized_decode(&mut self) -> Result<Fingerprint, Self::Error> {
522         Fingerprint::decode_opaque(&mut self.opaque)
523     }
524 }
525
526 impl<'a, 'tcx, T: Decodable> SpecializedDecoder<mir::ClearCrossCrate<T>>
527     for DecodeContext<'a, 'tcx>
528 {
529     #[inline]
530     fn specialized_decode(&mut self) -> Result<mir::ClearCrossCrate<T>, Self::Error> {
531         Ok(mir::ClearCrossCrate::Clear)
532     }
533 }
534
535 implement_ty_decoder!(DecodeContext<'a, 'tcx>);
536
537 impl MetadataBlob {
538     crate fn new(metadata_ref: MetadataRef) -> MetadataBlob {
539         MetadataBlob(metadata_ref)
540     }
541
542     crate fn is_compatible(&self) -> bool {
543         self.raw_bytes().starts_with(METADATA_HEADER)
544     }
545
546     crate fn get_rustc_version(&self) -> String {
547         Lazy::<String>::from_position(NonZeroUsize::new(METADATA_HEADER.len() + 4).unwrap())
548             .decode(self)
549     }
550
551     crate fn get_root(&self) -> CrateRoot<'tcx> {
552         let slice = self.raw_bytes();
553         let offset = METADATA_HEADER.len();
554         let pos = (((slice[offset + 0] as u32) << 24)
555             | ((slice[offset + 1] as u32) << 16)
556             | ((slice[offset + 2] as u32) << 8)
557             | ((slice[offset + 3] as u32) << 0)) as usize;
558         Lazy::<CrateRoot<'tcx>>::from_position(NonZeroUsize::new(pos).unwrap()).decode(self)
559     }
560
561     crate fn list_crate_metadata(&self, out: &mut dyn io::Write) -> io::Result<()> {
562         write!(out, "=External Dependencies=\n")?;
563         let root = self.get_root();
564         for (i, dep) in root.crate_deps.decode(self).enumerate() {
565             write!(out, "{} {}{}\n", i + 1, dep.name, dep.extra_filename)?;
566         }
567         write!(out, "\n")?;
568         Ok(())
569     }
570 }
571
572 impl EntryKind {
573     fn def_kind(&self) -> Option<DefKind> {
574         Some(match *self {
575             EntryKind::Const(..) => DefKind::Const,
576             EntryKind::AssocConst(..) => DefKind::AssocConst,
577             EntryKind::ImmStatic
578             | EntryKind::MutStatic
579             | EntryKind::ForeignImmStatic
580             | EntryKind::ForeignMutStatic => DefKind::Static,
581             EntryKind::Struct(_, _) => DefKind::Struct,
582             EntryKind::Union(_, _) => DefKind::Union,
583             EntryKind::Fn(_) | EntryKind::ForeignFn(_) => DefKind::Fn,
584             EntryKind::AssocFn(_) => DefKind::AssocFn,
585             EntryKind::Type => DefKind::TyAlias,
586             EntryKind::TypeParam => DefKind::TyParam,
587             EntryKind::ConstParam => DefKind::ConstParam,
588             EntryKind::OpaqueTy => DefKind::OpaqueTy,
589             EntryKind::AssocType(_) => DefKind::AssocTy,
590             EntryKind::AssocOpaqueTy(_) => DefKind::AssocOpaqueTy,
591             EntryKind::Mod(_) => DefKind::Mod,
592             EntryKind::Variant(_) => DefKind::Variant,
593             EntryKind::Trait(_) => DefKind::Trait,
594             EntryKind::TraitAlias => DefKind::TraitAlias,
595             EntryKind::Enum(..) => DefKind::Enum,
596             EntryKind::MacroDef(_) => DefKind::Macro(MacroKind::Bang),
597             EntryKind::ForeignType => DefKind::ForeignTy,
598
599             EntryKind::ForeignMod
600             | EntryKind::GlobalAsm
601             | EntryKind::Impl(_)
602             | EntryKind::Field
603             | EntryKind::Generator(_)
604             | EntryKind::Closure => return None,
605         })
606     }
607 }
608
609 impl CrateRoot<'_> {
610     crate fn is_proc_macro_crate(&self) -> bool {
611         self.proc_macro_data.is_some()
612     }
613
614     crate fn name(&self) -> Symbol {
615         self.name
616     }
617
618     crate fn disambiguator(&self) -> CrateDisambiguator {
619         self.disambiguator
620     }
621
622     crate fn hash(&self) -> Svh {
623         self.hash
624     }
625
626     crate fn triple(&self) -> &TargetTriple {
627         &self.triple
628     }
629
630     crate fn decode_crate_deps(
631         &self,
632         metadata: &'a MetadataBlob,
633     ) -> impl ExactSizeIterator<Item = CrateDep> + Captures<'a> {
634         self.crate_deps.decode(metadata)
635     }
636 }
637
638 impl<'a, 'tcx> CrateMetadataRef<'a> {
639     fn is_proc_macro(&self, id: DefIndex) -> bool {
640         self.root.proc_macro_data.and_then(|data| data.decode(self).find(|x| *x == id)).is_some()
641     }
642
643     fn maybe_kind(&self, item_id: DefIndex) -> Option<EntryKind> {
644         self.root.per_def.kind.get(self, item_id).map(|k| k.decode(self))
645     }
646
647     fn kind(&self, item_id: DefIndex) -> EntryKind {
648         assert!(!self.is_proc_macro(item_id));
649         self.maybe_kind(item_id).unwrap_or_else(|| {
650             bug!(
651                 "CrateMetadata::kind({:?}): id not found, in crate {:?} with number {}",
652                 item_id,
653                 self.root.name,
654                 self.cnum,
655             )
656         })
657     }
658
659     fn raw_proc_macro(&self, id: DefIndex) -> &ProcMacro {
660         // DefIndex's in root.proc_macro_data have a one-to-one correspondence
661         // with items in 'raw_proc_macros'.
662         let pos = self.root.proc_macro_data.unwrap().decode(self).position(|i| i == id).unwrap();
663         &self.raw_proc_macros.unwrap()[pos]
664     }
665
666     fn item_name(&self, item_index: DefIndex) -> Symbol {
667         if !self.is_proc_macro(item_index) {
668             self.def_key(item_index)
669                 .disambiguated_data
670                 .data
671                 .get_opt_name()
672                 .expect("no name in item_name")
673         } else {
674             Symbol::intern(self.raw_proc_macro(item_index).name())
675         }
676     }
677
678     fn def_kind(&self, index: DefIndex) -> Option<DefKind> {
679         if !self.is_proc_macro(index) {
680             self.kind(index).def_kind()
681         } else {
682             Some(DefKind::Macro(macro_kind(self.raw_proc_macro(index))))
683         }
684     }
685
686     fn get_span(&self, index: DefIndex, sess: &Session) -> Span {
687         self.root.per_def.span.get(self, index).unwrap().decode((self, sess))
688     }
689
690     fn load_proc_macro(&self, id: DefIndex, sess: &Session) -> SyntaxExtension {
691         let (name, kind, helper_attrs) = match *self.raw_proc_macro(id) {
692             ProcMacro::CustomDerive { trait_name, attributes, client } => {
693                 let helper_attrs =
694                     attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
695                 (
696                     trait_name,
697                     SyntaxExtensionKind::Derive(Box::new(ProcMacroDerive { client })),
698                     helper_attrs,
699                 )
700             }
701             ProcMacro::Attr { name, client } => {
702                 (name, SyntaxExtensionKind::Attr(Box::new(AttrProcMacro { client })), Vec::new())
703             }
704             ProcMacro::Bang { name, client } => {
705                 (name, SyntaxExtensionKind::Bang(Box::new(BangProcMacro { client })), Vec::new())
706             }
707         };
708
709         SyntaxExtension::new(
710             &sess.parse_sess,
711             kind,
712             self.get_span(id, sess),
713             helper_attrs,
714             self.root.edition,
715             Symbol::intern(name),
716             &self.get_item_attrs(id, sess),
717         )
718     }
719
720     fn get_trait_def(&self, item_id: DefIndex, sess: &Session) -> ty::TraitDef {
721         match self.kind(item_id) {
722             EntryKind::Trait(data) => {
723                 let data = data.decode((self, sess));
724                 ty::TraitDef::new(
725                     self.local_def_id(item_id),
726                     data.unsafety,
727                     data.paren_sugar,
728                     data.has_auto_impl,
729                     data.is_marker,
730                     data.specialization_kind,
731                     self.def_path_table.def_path_hash(item_id),
732                 )
733             }
734             EntryKind::TraitAlias => ty::TraitDef::new(
735                 self.local_def_id(item_id),
736                 hir::Unsafety::Normal,
737                 false,
738                 false,
739                 false,
740                 ty::trait_def::TraitSpecializationKind::None,
741                 self.def_path_table.def_path_hash(item_id),
742             ),
743             _ => bug!("def-index does not refer to trait or trait alias"),
744         }
745     }
746
747     fn get_variant(
748         &self,
749         tcx: TyCtxt<'tcx>,
750         kind: &EntryKind,
751         index: DefIndex,
752         parent_did: DefId,
753     ) -> ty::VariantDef {
754         let data = match kind {
755             EntryKind::Variant(data) | EntryKind::Struct(data, _) | EntryKind::Union(data, _) => {
756                 data.decode(self)
757             }
758             _ => bug!(),
759         };
760
761         let adt_kind = match kind {
762             EntryKind::Variant(_) => ty::AdtKind::Enum,
763             EntryKind::Struct(..) => ty::AdtKind::Struct,
764             EntryKind::Union(..) => ty::AdtKind::Union,
765             _ => bug!(),
766         };
767
768         let variant_did =
769             if adt_kind == ty::AdtKind::Enum { Some(self.local_def_id(index)) } else { None };
770         let ctor_did = data.ctor.map(|index| self.local_def_id(index));
771
772         ty::VariantDef::new(
773             tcx,
774             Ident::with_dummy_span(self.item_name(index)),
775             variant_did,
776             ctor_did,
777             data.discr,
778             self.root
779                 .per_def
780                 .children
781                 .get(self, index)
782                 .unwrap_or(Lazy::empty())
783                 .decode(self)
784                 .map(|index| ty::FieldDef {
785                     did: self.local_def_id(index),
786                     ident: Ident::with_dummy_span(self.item_name(index)),
787                     vis: self.get_visibility(index),
788                 })
789                 .collect(),
790             data.ctor_kind,
791             adt_kind,
792             parent_did,
793             false,
794         )
795     }
796
797     fn get_adt_def(&self, item_id: DefIndex, tcx: TyCtxt<'tcx>) -> &'tcx ty::AdtDef {
798         let kind = self.kind(item_id);
799         let did = self.local_def_id(item_id);
800
801         let (adt_kind, repr) = match kind {
802             EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr),
803             EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr),
804             EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr),
805             _ => bug!("get_adt_def called on a non-ADT {:?}", did),
806         };
807
808         let variants = if let ty::AdtKind::Enum = adt_kind {
809             self.root
810                 .per_def
811                 .children
812                 .get(self, item_id)
813                 .unwrap_or(Lazy::empty())
814                 .decode(self)
815                 .map(|index| self.get_variant(tcx, &self.kind(index), index, did))
816                 .collect()
817         } else {
818             std::iter::once(self.get_variant(tcx, &kind, item_id, did)).collect()
819         };
820
821         tcx.alloc_adt_def(did, adt_kind, variants, repr)
822     }
823
824     fn get_explicit_predicates(
825         &self,
826         item_id: DefIndex,
827         tcx: TyCtxt<'tcx>,
828     ) -> ty::GenericPredicates<'tcx> {
829         self.root.per_def.explicit_predicates.get(self, item_id).unwrap().decode((self, tcx))
830     }
831
832     fn get_inferred_outlives(
833         &self,
834         item_id: DefIndex,
835         tcx: TyCtxt<'tcx>,
836     ) -> &'tcx [(ty::Predicate<'tcx>, Span)] {
837         self.root
838             .per_def
839             .inferred_outlives
840             .get(self, item_id)
841             .map(|predicates| predicates.decode((self, tcx)))
842             .unwrap_or_default()
843     }
844
845     fn get_super_predicates(
846         &self,
847         item_id: DefIndex,
848         tcx: TyCtxt<'tcx>,
849     ) -> ty::GenericPredicates<'tcx> {
850         self.root.per_def.super_predicates.get(self, item_id).unwrap().decode((self, tcx))
851     }
852
853     fn get_generics(&self, item_id: DefIndex, sess: &Session) -> ty::Generics {
854         self.root.per_def.generics.get(self, item_id).unwrap().decode((self, sess))
855     }
856
857     fn get_type(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
858         self.root.per_def.ty.get(self, id).unwrap().decode((self, tcx))
859     }
860
861     fn get_stability(&self, id: DefIndex) -> Option<attr::Stability> {
862         match self.is_proc_macro(id) {
863             true => self.root.proc_macro_stability,
864             false => self.root.per_def.stability.get(self, id).map(|stab| stab.decode(self)),
865         }
866     }
867
868     fn get_const_stability(&self, id: DefIndex) -> Option<attr::ConstStability> {
869         self.root.per_def.const_stability.get(self, id).map(|stab| stab.decode(self))
870     }
871
872     fn get_deprecation(&self, id: DefIndex) -> Option<attr::Deprecation> {
873         self.root
874             .per_def
875             .deprecation
876             .get(self, id)
877             .filter(|_| !self.is_proc_macro(id))
878             .map(|depr| depr.decode(self))
879     }
880
881     fn get_visibility(&self, id: DefIndex) -> ty::Visibility {
882         match self.is_proc_macro(id) {
883             true => ty::Visibility::Public,
884             false => self.root.per_def.visibility.get(self, id).unwrap().decode(self),
885         }
886     }
887
888     fn get_impl_data(&self, id: DefIndex) -> ImplData {
889         match self.kind(id) {
890             EntryKind::Impl(data) => data.decode(self),
891             _ => bug!(),
892         }
893     }
894
895     fn get_parent_impl(&self, id: DefIndex) -> Option<DefId> {
896         self.get_impl_data(id).parent_impl
897     }
898
899     fn get_impl_polarity(&self, id: DefIndex) -> ty::ImplPolarity {
900         self.get_impl_data(id).polarity
901     }
902
903     fn get_impl_defaultness(&self, id: DefIndex) -> hir::Defaultness {
904         self.get_impl_data(id).defaultness
905     }
906
907     fn get_coerce_unsized_info(&self, id: DefIndex) -> Option<ty::adjustment::CoerceUnsizedInfo> {
908         self.get_impl_data(id).coerce_unsized_info
909     }
910
911     fn get_impl_trait(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Option<ty::TraitRef<'tcx>> {
912         self.root.per_def.impl_trait_ref.get(self, id).map(|tr| tr.decode((self, tcx)))
913     }
914
915     /// Iterates over all the stability attributes in the given crate.
916     fn get_lib_features(&self, tcx: TyCtxt<'tcx>) -> &'tcx [(ast::Name, Option<ast::Name>)] {
917         // FIXME: For a proc macro crate, not sure whether we should return the "host"
918         // features or an empty Vec. Both don't cause ICEs.
919         tcx.arena.alloc_from_iter(self.root.lib_features.decode(self))
920     }
921
922     /// Iterates over the language items in the given crate.
923     fn get_lang_items(&self, tcx: TyCtxt<'tcx>) -> &'tcx [(DefId, usize)] {
924         if self.root.is_proc_macro_crate() {
925             // Proc macro crates do not export any lang-items to the target.
926             &[]
927         } else {
928             tcx.arena.alloc_from_iter(
929                 self.root
930                     .lang_items
931                     .decode(self)
932                     .map(|(def_index, index)| (self.local_def_id(def_index), index)),
933             )
934         }
935     }
936
937     /// Iterates over the diagnostic items in the given crate.
938     fn get_diagnostic_items(&self, tcx: TyCtxt<'tcx>) -> &'tcx FxHashMap<Symbol, DefId> {
939         tcx.arena.alloc(if self.root.is_proc_macro_crate() {
940             // Proc macro crates do not export any diagnostic-items to the target.
941             Default::default()
942         } else {
943             self.root
944                 .diagnostic_items
945                 .decode(self)
946                 .map(|(name, def_index)| (name, self.local_def_id(def_index)))
947                 .collect()
948         })
949     }
950
951     /// Iterates over each child of the given item.
952     fn each_child_of_item<F>(&self, id: DefIndex, mut callback: F, sess: &Session)
953     where
954         F: FnMut(Export<hir::HirId>),
955     {
956         if let Some(proc_macros_ids) = self.root.proc_macro_data.map(|d| d.decode(self)) {
957             /* If we are loading as a proc macro, we want to return the view of this crate
958              * as a proc macro crate.
959              */
960             if id == CRATE_DEF_INDEX {
961                 for def_index in proc_macros_ids {
962                     let raw_macro = self.raw_proc_macro(def_index);
963                     let res = Res::Def(
964                         DefKind::Macro(macro_kind(raw_macro)),
965                         self.local_def_id(def_index),
966                     );
967                     let ident = Ident::from_str(raw_macro.name());
968                     callback(Export { ident, res, vis: ty::Visibility::Public, span: DUMMY_SP });
969                 }
970             }
971             return;
972         }
973
974         // Find the item.
975         let kind = match self.maybe_kind(id) {
976             None => return,
977             Some(kind) => kind,
978         };
979
980         // Iterate over all children.
981         let macros_only = self.dep_kind.lock().macros_only();
982         let children = self.root.per_def.children.get(self, id).unwrap_or(Lazy::empty());
983         for child_index in children.decode((self, sess)) {
984             if macros_only {
985                 continue;
986             }
987
988             // Get the item.
989             if let Some(child_kind) = self.maybe_kind(child_index) {
990                 match child_kind {
991                     EntryKind::MacroDef(..) => {}
992                     _ if macros_only => continue,
993                     _ => {}
994                 }
995
996                 // Hand off the item to the callback.
997                 match child_kind {
998                     // FIXME(eddyb) Don't encode these in children.
999                     EntryKind::ForeignMod => {
1000                         let child_children = self
1001                             .root
1002                             .per_def
1003                             .children
1004                             .get(self, child_index)
1005                             .unwrap_or(Lazy::empty());
1006                         for child_index in child_children.decode((self, sess)) {
1007                             if let Some(kind) = self.def_kind(child_index) {
1008                                 callback(Export {
1009                                     res: Res::Def(kind, self.local_def_id(child_index)),
1010                                     ident: Ident::with_dummy_span(self.item_name(child_index)),
1011                                     vis: self.get_visibility(child_index),
1012                                     span: self
1013                                         .root
1014                                         .per_def
1015                                         .span
1016                                         .get(self, child_index)
1017                                         .unwrap()
1018                                         .decode((self, sess)),
1019                                 });
1020                             }
1021                         }
1022                         continue;
1023                     }
1024                     EntryKind::Impl(_) => continue,
1025
1026                     _ => {}
1027                 }
1028
1029                 let def_key = self.def_key(child_index);
1030                 let span = self.get_span(child_index, sess);
1031                 if let (Some(kind), Some(name)) =
1032                     (self.def_kind(child_index), def_key.disambiguated_data.data.get_opt_name())
1033                 {
1034                     let ident = Ident::with_dummy_span(name);
1035                     let vis = self.get_visibility(child_index);
1036                     let def_id = self.local_def_id(child_index);
1037                     let res = Res::Def(kind, def_id);
1038                     callback(Export { res, ident, vis, span });
1039                     // For non-re-export structs and variants add their constructors to children.
1040                     // Re-export lists automatically contain constructors when necessary.
1041                     match kind {
1042                         DefKind::Struct => {
1043                             if let Some(ctor_def_id) = self.get_ctor_def_id(child_index) {
1044                                 let ctor_kind = self.get_ctor_kind(child_index);
1045                                 let ctor_res =
1046                                     Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id);
1047                                 let vis = self.get_visibility(ctor_def_id.index);
1048                                 callback(Export { res: ctor_res, vis, ident, span });
1049                             }
1050                         }
1051                         DefKind::Variant => {
1052                             // Braced variants, unlike structs, generate unusable names in
1053                             // value namespace, they are reserved for possible future use.
1054                             // It's ok to use the variant's id as a ctor id since an
1055                             // error will be reported on any use of such resolution anyway.
1056                             let ctor_def_id = self.get_ctor_def_id(child_index).unwrap_or(def_id);
1057                             let ctor_kind = self.get_ctor_kind(child_index);
1058                             let ctor_res =
1059                                 Res::Def(DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_def_id);
1060                             let mut vis = self.get_visibility(ctor_def_id.index);
1061                             if ctor_def_id == def_id && vis == ty::Visibility::Public {
1062                                 // For non-exhaustive variants lower the constructor visibility to
1063                                 // within the crate. We only need this for fictive constructors,
1064                                 // for other constructors correct visibilities
1065                                 // were already encoded in metadata.
1066                                 let attrs = self.get_item_attrs(def_id.index, sess);
1067                                 if attr::contains_name(&attrs, sym::non_exhaustive) {
1068                                     let crate_def_id = self.local_def_id(CRATE_DEF_INDEX);
1069                                     vis = ty::Visibility::Restricted(crate_def_id);
1070                                 }
1071                             }
1072                             callback(Export { res: ctor_res, ident, vis, span });
1073                         }
1074                         _ => {}
1075                     }
1076                 }
1077             }
1078         }
1079
1080         if let EntryKind::Mod(data) = kind {
1081             for exp in data.decode((self, sess)).reexports.decode((self, sess)) {
1082                 match exp.res {
1083                     Res::Def(DefKind::Macro(..), _) => {}
1084                     _ if macros_only => continue,
1085                     _ => {}
1086                 }
1087                 callback(exp);
1088             }
1089         }
1090     }
1091
1092     fn is_item_mir_available(&self, id: DefIndex) -> bool {
1093         !self.is_proc_macro(id) && self.root.per_def.mir.get(self, id).is_some()
1094     }
1095
1096     fn get_optimized_mir(&self, tcx: TyCtxt<'tcx>, id: DefIndex) -> BodyAndCache<'tcx> {
1097         let mut cache = self
1098             .root
1099             .per_def
1100             .mir
1101             .get(self, id)
1102             .filter(|_| !self.is_proc_macro(id))
1103             .unwrap_or_else(|| {
1104                 bug!("get_optimized_mir: missing MIR for `{:?}`", self.local_def_id(id))
1105             })
1106             .decode((self, tcx));
1107         cache.ensure_predecessors();
1108         cache
1109     }
1110
1111     fn get_promoted_mir(
1112         &self,
1113         tcx: TyCtxt<'tcx>,
1114         id: DefIndex,
1115     ) -> IndexVec<Promoted, BodyAndCache<'tcx>> {
1116         let mut cache = self
1117             .root
1118             .per_def
1119             .promoted_mir
1120             .get(self, id)
1121             .filter(|_| !self.is_proc_macro(id))
1122             .unwrap_or_else(|| {
1123                 bug!("get_promoted_mir: missing MIR for `{:?}`", self.local_def_id(id))
1124             })
1125             .decode((self, tcx));
1126         for body in cache.iter_mut() {
1127             body.ensure_predecessors();
1128         }
1129         cache
1130     }
1131
1132     fn mir_const_qualif(&self, id: DefIndex) -> mir::ConstQualifs {
1133         match self.kind(id) {
1134             EntryKind::Const(qualif, _)
1135             | EntryKind::AssocConst(AssocContainer::ImplDefault, qualif, _)
1136             | EntryKind::AssocConst(AssocContainer::ImplFinal, qualif, _) => qualif,
1137             _ => bug!(),
1138         }
1139     }
1140
1141     fn get_associated_item(&self, id: DefIndex) -> ty::AssocItem {
1142         let def_key = self.def_key(id);
1143         let parent = self.local_def_id(def_key.parent.unwrap());
1144         let name = def_key.disambiguated_data.data.get_opt_name().unwrap();
1145
1146         let (kind, container, has_self) = match self.kind(id) {
1147             EntryKind::AssocConst(container, _, _) => (ty::AssocKind::Const, container, false),
1148             EntryKind::AssocFn(data) => {
1149                 let data = data.decode(self);
1150                 (ty::AssocKind::Method, data.container, data.has_self)
1151             }
1152             EntryKind::AssocType(container) => (ty::AssocKind::Type, container, false),
1153             EntryKind::AssocOpaqueTy(container) => (ty::AssocKind::OpaqueTy, container, false),
1154             _ => bug!("cannot get associated-item of `{:?}`", def_key),
1155         };
1156
1157         ty::AssocItem {
1158             ident: Ident::with_dummy_span(name),
1159             kind,
1160             vis: self.get_visibility(id),
1161             defaultness: container.defaultness(),
1162             def_id: self.local_def_id(id),
1163             container: container.with_def_id(parent),
1164             method_has_self_argument: has_self,
1165         }
1166     }
1167
1168     fn get_item_variances(&self, id: DefIndex) -> Vec<ty::Variance> {
1169         self.root.per_def.variances.get(self, id).unwrap_or(Lazy::empty()).decode(self).collect()
1170     }
1171
1172     fn get_ctor_kind(&self, node_id: DefIndex) -> CtorKind {
1173         match self.kind(node_id) {
1174             EntryKind::Struct(data, _) | EntryKind::Union(data, _) | EntryKind::Variant(data) => {
1175                 data.decode(self).ctor_kind
1176             }
1177             _ => CtorKind::Fictive,
1178         }
1179     }
1180
1181     fn get_ctor_def_id(&self, node_id: DefIndex) -> Option<DefId> {
1182         match self.kind(node_id) {
1183             EntryKind::Struct(data, _) => {
1184                 data.decode(self).ctor.map(|index| self.local_def_id(index))
1185             }
1186             EntryKind::Variant(data) => {
1187                 data.decode(self).ctor.map(|index| self.local_def_id(index))
1188             }
1189             _ => None,
1190         }
1191     }
1192
1193     fn get_item_attrs(&self, node_id: DefIndex, sess: &Session) -> Lrc<[ast::Attribute]> {
1194         // The attributes for a tuple struct/variant are attached to the definition, not the ctor;
1195         // we assume that someone passing in a tuple struct ctor is actually wanting to
1196         // look at the definition
1197         let def_key = self.def_key(node_id);
1198         let item_id = if def_key.disambiguated_data.data == DefPathData::Ctor {
1199             def_key.parent.unwrap()
1200         } else {
1201             node_id
1202         };
1203
1204         Lrc::from(
1205             self.root
1206                 .per_def
1207                 .attributes
1208                 .get(self, item_id)
1209                 .unwrap_or(Lazy::empty())
1210                 .decode((self, sess))
1211                 .collect::<Vec<_>>(),
1212         )
1213     }
1214
1215     fn get_struct_field_names(&self, id: DefIndex, sess: &Session) -> Vec<Spanned<ast::Name>> {
1216         self.root
1217             .per_def
1218             .children
1219             .get(self, id)
1220             .unwrap_or(Lazy::empty())
1221             .decode(self)
1222             .map(|index| respan(self.get_span(index, sess), self.item_name(index)))
1223             .collect()
1224     }
1225
1226     fn get_inherent_implementations_for_type(
1227         &self,
1228         tcx: TyCtxt<'tcx>,
1229         id: DefIndex,
1230     ) -> &'tcx [DefId] {
1231         tcx.arena.alloc_from_iter(
1232             self.root
1233                 .per_def
1234                 .inherent_impls
1235                 .get(self, id)
1236                 .unwrap_or(Lazy::empty())
1237                 .decode(self)
1238                 .map(|index| self.local_def_id(index)),
1239         )
1240     }
1241
1242     fn get_implementations_for_trait(
1243         &self,
1244         tcx: TyCtxt<'tcx>,
1245         filter: Option<DefId>,
1246     ) -> &'tcx [DefId] {
1247         if self.root.is_proc_macro_crate() {
1248             // proc-macro crates export no trait impls.
1249             return &[];
1250         }
1251
1252         // Do a reverse lookup beforehand to avoid touching the crate_num
1253         // hash map in the loop below.
1254         let filter = match filter.map(|def_id| self.reverse_translate_def_id(def_id)) {
1255             Some(Some(def_id)) => Some((def_id.krate.as_u32(), def_id.index)),
1256             Some(None) => return &[],
1257             None => None,
1258         };
1259
1260         if let Some(filter) = filter {
1261             if let Some(impls) = self.trait_impls.get(&filter) {
1262                 tcx.arena.alloc_from_iter(impls.decode(self).map(|idx| self.local_def_id(idx)))
1263             } else {
1264                 &[]
1265             }
1266         } else {
1267             tcx.arena.alloc_from_iter(
1268                 self.trait_impls
1269                     .values()
1270                     .flat_map(|impls| impls.decode(self).map(|idx| self.local_def_id(idx))),
1271             )
1272         }
1273     }
1274
1275     fn get_trait_of_item(&self, id: DefIndex) -> Option<DefId> {
1276         let def_key = self.def_key(id);
1277         match def_key.disambiguated_data.data {
1278             DefPathData::TypeNs(..) | DefPathData::ValueNs(..) => (),
1279             // Not an associated item
1280             _ => return None,
1281         }
1282         def_key.parent.and_then(|parent_index| match self.kind(parent_index) {
1283             EntryKind::Trait(_) | EntryKind::TraitAlias => Some(self.local_def_id(parent_index)),
1284             _ => None,
1285         })
1286     }
1287
1288     fn get_native_libraries(&self, sess: &Session) -> Vec<NativeLibrary> {
1289         if self.root.is_proc_macro_crate() {
1290             // Proc macro crates do not have any *target* native libraries.
1291             vec![]
1292         } else {
1293             self.root.native_libraries.decode((self, sess)).collect()
1294         }
1295     }
1296
1297     fn get_foreign_modules(&self, tcx: TyCtxt<'tcx>) -> &'tcx [ForeignModule] {
1298         if self.root.is_proc_macro_crate() {
1299             // Proc macro crates do not have any *target* foreign modules.
1300             &[]
1301         } else {
1302             tcx.arena.alloc_from_iter(self.root.foreign_modules.decode((self, tcx.sess)))
1303         }
1304     }
1305
1306     fn get_dylib_dependency_formats(
1307         &self,
1308         tcx: TyCtxt<'tcx>,
1309     ) -> &'tcx [(CrateNum, LinkagePreference)] {
1310         tcx.arena.alloc_from_iter(
1311             self.root.dylib_dependency_formats.decode(self).enumerate().flat_map(|(i, link)| {
1312                 let cnum = CrateNum::new(i + 1);
1313                 link.map(|link| (self.cnum_map[cnum], link))
1314             }),
1315         )
1316     }
1317
1318     fn get_missing_lang_items(&self, tcx: TyCtxt<'tcx>) -> &'tcx [lang_items::LangItem] {
1319         if self.root.is_proc_macro_crate() {
1320             // Proc macro crates do not depend on any target weak lang-items.
1321             &[]
1322         } else {
1323             tcx.arena.alloc_from_iter(self.root.lang_items_missing.decode(self))
1324         }
1325     }
1326
1327     fn get_fn_param_names(&self, id: DefIndex) -> Vec<ast::Name> {
1328         let param_names = match self.kind(id) {
1329             EntryKind::Fn(data) | EntryKind::ForeignFn(data) => data.decode(self).param_names,
1330             EntryKind::AssocFn(data) => data.decode(self).fn_data.param_names,
1331             _ => Lazy::empty(),
1332         };
1333         param_names.decode(self).collect()
1334     }
1335
1336     fn exported_symbols(
1337         &self,
1338         tcx: TyCtxt<'tcx>,
1339     ) -> Vec<(ExportedSymbol<'tcx>, SymbolExportLevel)> {
1340         if self.root.is_proc_macro_crate() {
1341             // If this crate is a custom derive crate, then we're not even going to
1342             // link those in so we skip those crates.
1343             vec![]
1344         } else {
1345             self.root.exported_symbols.decode((self, tcx)).collect()
1346         }
1347     }
1348
1349     fn get_rendered_const(&self, id: DefIndex) -> String {
1350         match self.kind(id) {
1351             EntryKind::Const(_, data) | EntryKind::AssocConst(_, _, data) => data.decode(self).0,
1352             _ => bug!(),
1353         }
1354     }
1355
1356     fn get_macro(&self, id: DefIndex, sess: &Session) -> MacroDef {
1357         match self.kind(id) {
1358             EntryKind::MacroDef(macro_def) => macro_def.decode((self, sess)),
1359             _ => bug!(),
1360         }
1361     }
1362
1363     // This replicates some of the logic of the crate-local `is_const_fn_raw` query, because we
1364     // don't serialize constness for tuple variant and tuple struct constructors.
1365     fn is_const_fn_raw(&self, id: DefIndex) -> bool {
1366         let constness = match self.kind(id) {
1367             EntryKind::AssocFn(data) => data.decode(self).fn_data.constness,
1368             EntryKind::Fn(data) => data.decode(self).constness,
1369             // Some intrinsics can be const fn. While we could recompute this (at least until we
1370             // stop having hardcoded whitelists and move to stability attributes), it seems cleaner
1371             // to treat all const fns equally.
1372             EntryKind::ForeignFn(data) => data.decode(self).constness,
1373             EntryKind::Variant(..) | EntryKind::Struct(..) => hir::Constness::Const,
1374             _ => hir::Constness::NotConst,
1375         };
1376         constness == hir::Constness::Const
1377     }
1378
1379     fn asyncness(&self, id: DefIndex) -> hir::IsAsync {
1380         match self.kind(id) {
1381             EntryKind::Fn(data) => data.decode(self).asyncness,
1382             EntryKind::AssocFn(data) => data.decode(self).fn_data.asyncness,
1383             EntryKind::ForeignFn(data) => data.decode(self).asyncness,
1384             _ => bug!("asyncness: expected function kind"),
1385         }
1386     }
1387
1388     fn is_foreign_item(&self, id: DefIndex) -> bool {
1389         match self.kind(id) {
1390             EntryKind::ForeignImmStatic | EntryKind::ForeignMutStatic | EntryKind::ForeignFn(_) => {
1391                 true
1392             }
1393             _ => false,
1394         }
1395     }
1396
1397     fn static_mutability(&self, id: DefIndex) -> Option<hir::Mutability> {
1398         match self.kind(id) {
1399             EntryKind::ImmStatic | EntryKind::ForeignImmStatic => Some(hir::Mutability::Not),
1400             EntryKind::MutStatic | EntryKind::ForeignMutStatic => Some(hir::Mutability::Mut),
1401             _ => None,
1402         }
1403     }
1404
1405     fn generator_kind(&self, id: DefIndex) -> Option<hir::GeneratorKind> {
1406         match self.kind(id) {
1407             EntryKind::Generator(data) => Some(data),
1408             _ => None,
1409         }
1410     }
1411
1412     fn fn_sig(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> {
1413         self.root.per_def.fn_sig.get(self, id).unwrap().decode((self, tcx))
1414     }
1415
1416     #[inline]
1417     fn def_key(&self, index: DefIndex) -> DefKey {
1418         let mut key = self.def_path_table.def_key(index);
1419         if self.is_proc_macro(index) {
1420             let name = self.raw_proc_macro(index).name();
1421             key.disambiguated_data.data = DefPathData::MacroNs(Symbol::intern(name));
1422         }
1423         key
1424     }
1425
1426     // Returns the path leading to the thing with this `id`.
1427     fn def_path(&self, id: DefIndex) -> DefPath {
1428         debug!("def_path(cnum={:?}, id={:?})", self.cnum, id);
1429         DefPath::make(self.cnum, id, |parent| self.def_key(parent))
1430     }
1431
1432     /// Imports the source_map from an external crate into the source_map of the crate
1433     /// currently being compiled (the "local crate").
1434     ///
1435     /// The import algorithm works analogous to how AST items are inlined from an
1436     /// external crate's metadata:
1437     /// For every SourceFile in the external source_map an 'inline' copy is created in the
1438     /// local source_map. The correspondence relation between external and local
1439     /// SourceFiles is recorded in the `ImportedSourceFile` objects returned from this
1440     /// function. When an item from an external crate is later inlined into this
1441     /// crate, this correspondence information is used to translate the span
1442     /// information of the inlined item so that it refers the correct positions in
1443     /// the local source_map (see `<decoder::DecodeContext as SpecializedDecoder<Span>>`).
1444     ///
1445     /// The import algorithm in the function below will reuse SourceFiles already
1446     /// existing in the local source_map. For example, even if the SourceFile of some
1447     /// source file of libstd gets imported many times, there will only ever be
1448     /// one SourceFile object for the corresponding file in the local source_map.
1449     ///
1450     /// Note that imported SourceFiles do not actually contain the source code of the
1451     /// file they represent, just information about length, line breaks, and
1452     /// multibyte characters. This information is enough to generate valid debuginfo
1453     /// for items inlined from other crates.
1454     ///
1455     /// Proc macro crates don't currently export spans, so this function does not have
1456     /// to work for them.
1457     fn imported_source_files(
1458         &self,
1459         local_source_map: &source_map::SourceMap,
1460     ) -> &'a [ImportedSourceFile] {
1461         self.cdata.source_map_import_info.init_locking(|| {
1462             let external_source_map = self.root.source_map.decode(self);
1463
1464             external_source_map
1465                 .map(|source_file_to_import| {
1466                     // We can't reuse an existing SourceFile, so allocate a new one
1467                     // containing the information we need.
1468                     let rustc_span::SourceFile {
1469                         name,
1470                         name_was_remapped,
1471                         src_hash,
1472                         start_pos,
1473                         end_pos,
1474                         mut lines,
1475                         mut multibyte_chars,
1476                         mut non_narrow_chars,
1477                         mut normalized_pos,
1478                         name_hash,
1479                         ..
1480                     } = source_file_to_import;
1481
1482                     let source_length = (end_pos - start_pos).to_usize();
1483
1484                     // Translate line-start positions and multibyte character
1485                     // position into frame of reference local to file.
1486                     // `SourceMap::new_imported_source_file()` will then translate those
1487                     // coordinates to their new global frame of reference when the
1488                     // offset of the SourceFile is known.
1489                     for pos in &mut lines {
1490                         *pos = *pos - start_pos;
1491                     }
1492                     for mbc in &mut multibyte_chars {
1493                         mbc.pos = mbc.pos - start_pos;
1494                     }
1495                     for swc in &mut non_narrow_chars {
1496                         *swc = *swc - start_pos;
1497                     }
1498                     for np in &mut normalized_pos {
1499                         np.pos = np.pos - start_pos;
1500                     }
1501
1502                     let local_version = local_source_map.new_imported_source_file(
1503                         name,
1504                         name_was_remapped,
1505                         src_hash,
1506                         name_hash,
1507                         source_length,
1508                         self.cnum,
1509                         lines,
1510                         multibyte_chars,
1511                         non_narrow_chars,
1512                         normalized_pos,
1513                         start_pos,
1514                         end_pos,
1515                     );
1516                     debug!(
1517                         "CrateMetaData::imported_source_files alloc \
1518                          source_file {:?} original (start_pos {:?} end_pos {:?}) \
1519                          translated (start_pos {:?} end_pos {:?})",
1520                         local_version.name,
1521                         start_pos,
1522                         end_pos,
1523                         local_version.start_pos,
1524                         local_version.end_pos
1525                     );
1526
1527                     ImportedSourceFile {
1528                         original_start_pos: start_pos,
1529                         original_end_pos: end_pos,
1530                         translated_source_file: local_version,
1531                     }
1532                 })
1533                 .collect()
1534         })
1535     }
1536 }
1537
1538 impl CrateMetadata {
1539     crate fn new(
1540         sess: &Session,
1541         blob: MetadataBlob,
1542         root: CrateRoot<'static>,
1543         raw_proc_macros: Option<&'static [ProcMacro]>,
1544         cnum: CrateNum,
1545         cnum_map: CrateNumMap,
1546         dep_kind: DepKind,
1547         source: CrateSource,
1548         private_dep: bool,
1549         host_hash: Option<Svh>,
1550     ) -> CrateMetadata {
1551         let def_path_table = record_time(&sess.perf_stats.decode_def_path_tables_time, || {
1552             root.def_path_table.decode((&blob, sess))
1553         });
1554         let trait_impls = root
1555             .impls
1556             .decode((&blob, sess))
1557             .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
1558             .collect();
1559         let alloc_decoding_state =
1560             AllocDecodingState::new(root.interpret_alloc_index.decode(&blob).collect());
1561         let dependencies = Lock::new(cnum_map.iter().cloned().collect());
1562         CrateMetadata {
1563             blob,
1564             root,
1565             def_path_table,
1566             trait_impls,
1567             raw_proc_macros,
1568             source_map_import_info: Once::new(),
1569             alloc_decoding_state,
1570             dep_node_index: AtomicCell::new(DepNodeIndex::INVALID),
1571             cnum,
1572             cnum_map,
1573             dependencies,
1574             dep_kind: Lock::new(dep_kind),
1575             source,
1576             private_dep,
1577             host_hash,
1578             extern_crate: Lock::new(None),
1579         }
1580     }
1581
1582     crate fn dependencies(&self) -> LockGuard<'_, Vec<CrateNum>> {
1583         self.dependencies.borrow()
1584     }
1585
1586     crate fn add_dependency(&self, cnum: CrateNum) {
1587         self.dependencies.borrow_mut().push(cnum);
1588     }
1589
1590     crate fn update_extern_crate(&self, new_extern_crate: ExternCrate) -> bool {
1591         let mut extern_crate = self.extern_crate.borrow_mut();
1592         let update = Some(new_extern_crate.rank()) > extern_crate.as_ref().map(ExternCrate::rank);
1593         if update {
1594             *extern_crate = Some(new_extern_crate);
1595         }
1596         update
1597     }
1598
1599     crate fn source(&self) -> &CrateSource {
1600         &self.source
1601     }
1602
1603     crate fn dep_kind(&self) -> DepKind {
1604         *self.dep_kind.lock()
1605     }
1606
1607     crate fn update_dep_kind(&self, f: impl FnOnce(DepKind) -> DepKind) {
1608         self.dep_kind.with_lock(|dep_kind| *dep_kind = f(*dep_kind))
1609     }
1610
1611     crate fn panic_strategy(&self) -> PanicStrategy {
1612         self.root.panic_strategy
1613     }
1614
1615     crate fn needs_panic_runtime(&self) -> bool {
1616         self.root.needs_panic_runtime
1617     }
1618
1619     crate fn is_panic_runtime(&self) -> bool {
1620         self.root.panic_runtime
1621     }
1622
1623     crate fn is_profiler_runtime(&self) -> bool {
1624         self.root.profiler_runtime
1625     }
1626
1627     crate fn needs_allocator(&self) -> bool {
1628         self.root.needs_allocator
1629     }
1630
1631     crate fn has_global_allocator(&self) -> bool {
1632         self.root.has_global_allocator
1633     }
1634
1635     crate fn has_default_lib_allocator(&self) -> bool {
1636         self.root.has_default_lib_allocator
1637     }
1638
1639     crate fn is_proc_macro_crate(&self) -> bool {
1640         self.root.is_proc_macro_crate()
1641     }
1642
1643     crate fn name(&self) -> Symbol {
1644         self.root.name
1645     }
1646
1647     crate fn disambiguator(&self) -> CrateDisambiguator {
1648         self.root.disambiguator
1649     }
1650
1651     crate fn hash(&self) -> Svh {
1652         self.root.hash
1653     }
1654
1655     fn local_def_id(&self, index: DefIndex) -> DefId {
1656         DefId { krate: self.cnum, index }
1657     }
1658
1659     // Translate a DefId from the current compilation environment to a DefId
1660     // for an external crate.
1661     fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
1662         for (local, &global) in self.cnum_map.iter_enumerated() {
1663             if global == did.krate {
1664                 return Some(DefId { krate: local, index: did.index });
1665             }
1666         }
1667
1668         None
1669     }
1670
1671     #[inline]
1672     fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
1673         self.def_path_table.def_path_hash(index)
1674     }
1675
1676     /// Get the `DepNodeIndex` corresponding this crate. The result of this
1677     /// method is cached in the `dep_node_index` field.
1678     fn get_crate_dep_node_index(&self, tcx: TyCtxt<'tcx>) -> DepNodeIndex {
1679         let mut dep_node_index = self.dep_node_index.load();
1680
1681         if unlikely!(dep_node_index == DepNodeIndex::INVALID) {
1682             // We have not cached the DepNodeIndex for this upstream crate yet,
1683             // so use the dep-graph to find it out and cache it.
1684             // Note that multiple threads can enter this block concurrently.
1685             // That is fine because the DepNodeIndex remains constant
1686             // throughout the whole compilation session, and multiple stores
1687             // would always write the same value.
1688
1689             let def_path_hash = self.def_path_hash(CRATE_DEF_INDEX);
1690             let dep_node =
1691                 DepNode::from_def_path_hash(def_path_hash, dep_graph::DepKind::CrateMetadata);
1692
1693             dep_node_index = tcx.dep_graph.dep_node_index_of(&dep_node);
1694             assert!(dep_node_index != DepNodeIndex::INVALID);
1695             self.dep_node_index.store(dep_node_index);
1696         }
1697
1698         dep_node_index
1699     }
1700 }
1701
1702 // Cannot be implemented on 'ProcMacro', as libproc_macro
1703 // does not depend on librustc_ast
1704 fn macro_kind(raw: &ProcMacro) -> MacroKind {
1705     match raw {
1706         ProcMacro::CustomDerive { .. } => MacroKind::Derive,
1707         ProcMacro::Attr { .. } => MacroKind::Attr,
1708         ProcMacro::Bang { .. } => MacroKind::Bang,
1709     }
1710 }