]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/rmeta/decoder.rs
direct imports for langitem stuff
[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_ast::ast::{self, Ident};
8 use rustc_attr as attr;
9 use rustc_data_structures::captures::Captures;
10 use rustc_data_structures::fingerprint::Fingerprint;
11 use rustc_data_structures::fx::FxHashMap;
12 use rustc_data_structures::svh::Svh;
13 use rustc_data_structures::sync::{AtomicCell, Lock, LockGuard, Lrc, Once};
14 use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind};
15 use rustc_expand::proc_macro::{AttrProcMacro, BangProcMacro, ProcMacroDerive};
16 use rustc_hir as hir;
17 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
18 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
19 use rustc_hir::definitions::DefPathTable;
20 use rustc_hir::definitions::{DefKey, DefPath, DefPathData, DefPathHash};
21 use rustc_hir::lang_items;
22 use rustc_index::vec::{Idx, IndexVec};
23 use rustc_middle::dep_graph::{self, DepNode, DepNodeExt, DepNodeIndex};
24 use rustc_middle::hir::exports::Export;
25 use rustc_middle::middle::cstore::{CrateSource, ExternCrate};
26 use rustc_middle::middle::cstore::{ForeignModule, LinkagePreference, NativeLibrary};
27 use rustc_middle::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel};
28 use rustc_middle::mir::interpret::{AllocDecodingSession, AllocDecodingState};
29 use rustc_middle::mir::{self, interpret, BodyAndCache, Promoted};
30 use rustc_middle::ty::codec::TyDecoder;
31 use rustc_middle::ty::{self, Ty, TyCtxt};
32 use rustc_middle::util::common::record_time;
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<'a, 'tcx> SpecializedDecoder<Fingerprint> for DecodeContext<'a, 'tcx> {
513     fn specialized_decode(&mut self) -> Result<Fingerprint, Self::Error> {
514         Fingerprint::decode_opaque(&mut self.opaque)
515     }
516 }
517
518 impl<'a, 'tcx, T: Decodable> SpecializedDecoder<mir::ClearCrossCrate<T>>
519     for DecodeContext<'a, 'tcx>
520 {
521     #[inline]
522     fn specialized_decode(&mut self) -> Result<mir::ClearCrossCrate<T>, Self::Error> {
523         Ok(mir::ClearCrossCrate::Clear)
524     }
525 }
526
527 implement_ty_decoder!(DecodeContext<'a, 'tcx>);
528
529 impl MetadataBlob {
530     crate fn new(metadata_ref: MetadataRef) -> MetadataBlob {
531         MetadataBlob(metadata_ref)
532     }
533
534     crate fn is_compatible(&self) -> bool {
535         self.raw_bytes().starts_with(METADATA_HEADER)
536     }
537
538     crate fn get_rustc_version(&self) -> String {
539         Lazy::<String>::from_position(NonZeroUsize::new(METADATA_HEADER.len() + 4).unwrap())
540             .decode(self)
541     }
542
543     crate fn get_root(&self) -> CrateRoot<'tcx> {
544         let slice = self.raw_bytes();
545         let offset = METADATA_HEADER.len();
546         let pos = (((slice[offset + 0] as u32) << 24)
547             | ((slice[offset + 1] as u32) << 16)
548             | ((slice[offset + 2] as u32) << 8)
549             | ((slice[offset + 3] as u32) << 0)) as usize;
550         Lazy::<CrateRoot<'tcx>>::from_position(NonZeroUsize::new(pos).unwrap()).decode(self)
551     }
552
553     crate fn list_crate_metadata(&self, out: &mut dyn io::Write) -> io::Result<()> {
554         write!(out, "=External Dependencies=\n")?;
555         let root = self.get_root();
556         for (i, dep) in root.crate_deps.decode(self).enumerate() {
557             write!(out, "{} {}{}\n", i + 1, dep.name, dep.extra_filename)?;
558         }
559         write!(out, "\n")?;
560         Ok(())
561     }
562 }
563
564 impl EntryKind {
565     fn def_kind(&self) -> Option<DefKind> {
566         Some(match *self {
567             EntryKind::Const(..) => DefKind::Const,
568             EntryKind::AssocConst(..) => DefKind::AssocConst,
569             EntryKind::ImmStatic
570             | EntryKind::MutStatic
571             | EntryKind::ForeignImmStatic
572             | EntryKind::ForeignMutStatic => DefKind::Static,
573             EntryKind::Struct(_, _) => DefKind::Struct,
574             EntryKind::Union(_, _) => DefKind::Union,
575             EntryKind::Fn(_) | EntryKind::ForeignFn(_) => DefKind::Fn,
576             EntryKind::AssocFn(_) => DefKind::AssocFn,
577             EntryKind::Type => DefKind::TyAlias,
578             EntryKind::TypeParam => DefKind::TyParam,
579             EntryKind::ConstParam => DefKind::ConstParam,
580             EntryKind::OpaqueTy => DefKind::OpaqueTy,
581             EntryKind::AssocType(_) => DefKind::AssocTy,
582             EntryKind::AssocOpaqueTy(_) => DefKind::AssocOpaqueTy,
583             EntryKind::Mod(_) => DefKind::Mod,
584             EntryKind::Variant(_) => DefKind::Variant,
585             EntryKind::Trait(_) => DefKind::Trait,
586             EntryKind::TraitAlias => DefKind::TraitAlias,
587             EntryKind::Enum(..) => DefKind::Enum,
588             EntryKind::MacroDef(_) => DefKind::Macro(MacroKind::Bang),
589             EntryKind::ForeignType => DefKind::ForeignTy,
590
591             EntryKind::ForeignMod
592             | EntryKind::GlobalAsm
593             | EntryKind::Impl(_)
594             | EntryKind::Field
595             | EntryKind::Generator(_)
596             | EntryKind::Closure => return None,
597         })
598     }
599 }
600
601 impl CrateRoot<'_> {
602     crate fn is_proc_macro_crate(&self) -> bool {
603         self.proc_macro_data.is_some()
604     }
605
606     crate fn name(&self) -> Symbol {
607         self.name
608     }
609
610     crate fn disambiguator(&self) -> CrateDisambiguator {
611         self.disambiguator
612     }
613
614     crate fn hash(&self) -> Svh {
615         self.hash
616     }
617
618     crate fn triple(&self) -> &TargetTriple {
619         &self.triple
620     }
621
622     crate fn decode_crate_deps(
623         &self,
624         metadata: &'a MetadataBlob,
625     ) -> impl ExactSizeIterator<Item = CrateDep> + Captures<'a> {
626         self.crate_deps.decode(metadata)
627     }
628 }
629
630 impl<'a, 'tcx> CrateMetadataRef<'a> {
631     fn is_proc_macro(&self, id: DefIndex) -> bool {
632         self.root.proc_macro_data.and_then(|data| data.decode(self).find(|x| *x == id)).is_some()
633     }
634
635     fn maybe_kind(&self, item_id: DefIndex) -> Option<EntryKind> {
636         self.root.per_def.kind.get(self, item_id).map(|k| k.decode(self))
637     }
638
639     fn kind(&self, item_id: DefIndex) -> EntryKind {
640         assert!(!self.is_proc_macro(item_id));
641         self.maybe_kind(item_id).unwrap_or_else(|| {
642             bug!(
643                 "CrateMetadata::kind({:?}): id not found, in crate {:?} with number {}",
644                 item_id,
645                 self.root.name,
646                 self.cnum,
647             )
648         })
649     }
650
651     fn raw_proc_macro(&self, id: DefIndex) -> &ProcMacro {
652         // DefIndex's in root.proc_macro_data have a one-to-one correspondence
653         // with items in 'raw_proc_macros'.
654         let pos = self.root.proc_macro_data.unwrap().decode(self).position(|i| i == id).unwrap();
655         &self.raw_proc_macros.unwrap()[pos]
656     }
657
658     fn item_ident(&self, item_index: DefIndex, sess: &Session) -> Ident {
659         if !self.is_proc_macro(item_index) {
660             let name = self
661                 .def_key(item_index)
662                 .disambiguated_data
663                 .data
664                 .get_opt_name()
665                 .expect("no name in item_ident");
666             let span = self
667                 .root
668                 .per_def
669                 .ident_span
670                 .get(self, item_index)
671                 .map(|data| data.decode((self, sess)))
672                 .unwrap_or_else(|| panic!("Missing ident span for {:?} ({:?})", name, item_index));
673             Ident::new(name, span)
674         } else {
675             Ident::new(
676                 Symbol::intern(self.raw_proc_macro(item_index).name()),
677                 self.get_span(item_index, sess),
678             )
679         }
680     }
681
682     fn def_kind(&self, index: DefIndex) -> Option<DefKind> {
683         if !self.is_proc_macro(index) {
684             self.kind(index).def_kind()
685         } else {
686             Some(DefKind::Macro(macro_kind(self.raw_proc_macro(index))))
687         }
688     }
689
690     fn get_span(&self, index: DefIndex, sess: &Session) -> Span {
691         self.root.per_def.span.get(self, index).unwrap().decode((self, sess))
692     }
693
694     fn load_proc_macro(&self, id: DefIndex, sess: &Session) -> SyntaxExtension {
695         let (name, kind, helper_attrs) = match *self.raw_proc_macro(id) {
696             ProcMacro::CustomDerive { trait_name, attributes, client } => {
697                 let helper_attrs =
698                     attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
699                 (
700                     trait_name,
701                     SyntaxExtensionKind::Derive(Box::new(ProcMacroDerive { client })),
702                     helper_attrs,
703                 )
704             }
705             ProcMacro::Attr { name, client } => {
706                 (name, SyntaxExtensionKind::Attr(Box::new(AttrProcMacro { client })), Vec::new())
707             }
708             ProcMacro::Bang { name, client } => {
709                 (name, SyntaxExtensionKind::Bang(Box::new(BangProcMacro { client })), Vec::new())
710             }
711         };
712
713         SyntaxExtension::new(
714             &sess.parse_sess,
715             kind,
716             self.get_span(id, sess),
717             helper_attrs,
718             self.root.edition,
719             Symbol::intern(name),
720             &self.get_item_attrs(id, sess),
721         )
722     }
723
724     fn get_trait_def(&self, item_id: DefIndex, sess: &Session) -> ty::TraitDef {
725         match self.kind(item_id) {
726             EntryKind::Trait(data) => {
727                 let data = data.decode((self, sess));
728                 ty::TraitDef::new(
729                     self.local_def_id(item_id),
730                     data.unsafety,
731                     data.paren_sugar,
732                     data.has_auto_impl,
733                     data.is_marker,
734                     data.specialization_kind,
735                     self.def_path_table.def_path_hash(item_id),
736                 )
737             }
738             EntryKind::TraitAlias => ty::TraitDef::new(
739                 self.local_def_id(item_id),
740                 hir::Unsafety::Normal,
741                 false,
742                 false,
743                 false,
744                 ty::trait_def::TraitSpecializationKind::None,
745                 self.def_path_table.def_path_hash(item_id),
746             ),
747             _ => bug!("def-index does not refer to trait or trait alias"),
748         }
749     }
750
751     fn get_variant(
752         &self,
753         tcx: TyCtxt<'tcx>,
754         kind: &EntryKind,
755         index: DefIndex,
756         parent_did: DefId,
757         sess: &Session,
758     ) -> ty::VariantDef {
759         let data = match kind {
760             EntryKind::Variant(data) | EntryKind::Struct(data, _) | EntryKind::Union(data, _) => {
761                 data.decode(self)
762             }
763             _ => bug!(),
764         };
765
766         let adt_kind = match kind {
767             EntryKind::Variant(_) => ty::AdtKind::Enum,
768             EntryKind::Struct(..) => ty::AdtKind::Struct,
769             EntryKind::Union(..) => ty::AdtKind::Union,
770             _ => bug!(),
771         };
772
773         let variant_did =
774             if adt_kind == ty::AdtKind::Enum { Some(self.local_def_id(index)) } else { None };
775         let ctor_did = data.ctor.map(|index| self.local_def_id(index));
776
777         ty::VariantDef::new(
778             tcx,
779             self.item_ident(index, sess),
780             variant_did,
781             ctor_did,
782             data.discr,
783             self.root
784                 .per_def
785                 .children
786                 .get(self, index)
787                 .unwrap_or(Lazy::empty())
788                 .decode(self)
789                 .map(|index| ty::FieldDef {
790                     did: self.local_def_id(index),
791                     ident: self.item_ident(index, sess),
792                     vis: self.get_visibility(index),
793                 })
794                 .collect(),
795             data.ctor_kind,
796             adt_kind,
797             parent_did,
798             false,
799         )
800     }
801
802     fn get_adt_def(&self, item_id: DefIndex, tcx: TyCtxt<'tcx>) -> &'tcx ty::AdtDef {
803         let kind = self.kind(item_id);
804         let did = self.local_def_id(item_id);
805
806         let (adt_kind, repr) = match kind {
807             EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr),
808             EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr),
809             EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr),
810             _ => bug!("get_adt_def called on a non-ADT {:?}", did),
811         };
812
813         let variants = if let ty::AdtKind::Enum = adt_kind {
814             self.root
815                 .per_def
816                 .children
817                 .get(self, item_id)
818                 .unwrap_or(Lazy::empty())
819                 .decode(self)
820                 .map(|index| self.get_variant(tcx, &self.kind(index), index, did, tcx.sess))
821                 .collect()
822         } else {
823             std::iter::once(self.get_variant(tcx, &kind, item_id, did, tcx.sess)).collect()
824         };
825
826         tcx.alloc_adt_def(did, adt_kind, variants, repr)
827     }
828
829     fn get_explicit_predicates(
830         &self,
831         item_id: DefIndex,
832         tcx: TyCtxt<'tcx>,
833     ) -> ty::GenericPredicates<'tcx> {
834         self.root.per_def.explicit_predicates.get(self, item_id).unwrap().decode((self, tcx))
835     }
836
837     fn get_inferred_outlives(
838         &self,
839         item_id: DefIndex,
840         tcx: TyCtxt<'tcx>,
841     ) -> &'tcx [(ty::Predicate<'tcx>, Span)] {
842         self.root
843             .per_def
844             .inferred_outlives
845             .get(self, item_id)
846             .map(|predicates| predicates.decode((self, tcx)))
847             .unwrap_or_default()
848     }
849
850     fn get_super_predicates(
851         &self,
852         item_id: DefIndex,
853         tcx: TyCtxt<'tcx>,
854     ) -> ty::GenericPredicates<'tcx> {
855         self.root.per_def.super_predicates.get(self, item_id).unwrap().decode((self, tcx))
856     }
857
858     fn get_generics(&self, item_id: DefIndex, sess: &Session) -> ty::Generics {
859         self.root.per_def.generics.get(self, item_id).unwrap().decode((self, sess))
860     }
861
862     fn get_type(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
863         self.root.per_def.ty.get(self, id).unwrap().decode((self, tcx))
864     }
865
866     fn get_stability(&self, id: DefIndex) -> Option<attr::Stability> {
867         match self.is_proc_macro(id) {
868             true => self.root.proc_macro_stability,
869             false => self.root.per_def.stability.get(self, id).map(|stab| stab.decode(self)),
870         }
871     }
872
873     fn get_const_stability(&self, id: DefIndex) -> Option<attr::ConstStability> {
874         self.root.per_def.const_stability.get(self, id).map(|stab| stab.decode(self))
875     }
876
877     fn get_deprecation(&self, id: DefIndex) -> Option<attr::Deprecation> {
878         self.root
879             .per_def
880             .deprecation
881             .get(self, id)
882             .filter(|_| !self.is_proc_macro(id))
883             .map(|depr| depr.decode(self))
884     }
885
886     fn get_visibility(&self, id: DefIndex) -> ty::Visibility {
887         match self.is_proc_macro(id) {
888             true => ty::Visibility::Public,
889             false => self.root.per_def.visibility.get(self, id).unwrap().decode(self),
890         }
891     }
892
893     fn get_impl_data(&self, id: DefIndex) -> ImplData {
894         match self.kind(id) {
895             EntryKind::Impl(data) => data.decode(self),
896             _ => bug!(),
897         }
898     }
899
900     fn get_parent_impl(&self, id: DefIndex) -> Option<DefId> {
901         self.get_impl_data(id).parent_impl
902     }
903
904     fn get_impl_polarity(&self, id: DefIndex) -> ty::ImplPolarity {
905         self.get_impl_data(id).polarity
906     }
907
908     fn get_impl_defaultness(&self, id: DefIndex) -> hir::Defaultness {
909         self.get_impl_data(id).defaultness
910     }
911
912     fn get_coerce_unsized_info(&self, id: DefIndex) -> Option<ty::adjustment::CoerceUnsizedInfo> {
913         self.get_impl_data(id).coerce_unsized_info
914     }
915
916     fn get_impl_trait(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Option<ty::TraitRef<'tcx>> {
917         self.root.per_def.impl_trait_ref.get(self, id).map(|tr| tr.decode((self, tcx)))
918     }
919
920     /// Iterates over all the stability attributes in the given crate.
921     fn get_lib_features(&self, tcx: TyCtxt<'tcx>) -> &'tcx [(ast::Name, Option<ast::Name>)] {
922         // FIXME: For a proc macro crate, not sure whether we should return the "host"
923         // features or an empty Vec. Both don't cause ICEs.
924         tcx.arena.alloc_from_iter(self.root.lib_features.decode(self))
925     }
926
927     /// Iterates over the language items in the given crate.
928     fn get_lang_items(&self, tcx: TyCtxt<'tcx>) -> &'tcx [(DefId, usize)] {
929         if self.root.is_proc_macro_crate() {
930             // Proc macro crates do not export any lang-items to the target.
931             &[]
932         } else {
933             tcx.arena.alloc_from_iter(
934                 self.root
935                     .lang_items
936                     .decode(self)
937                     .map(|(def_index, index)| (self.local_def_id(def_index), index)),
938             )
939         }
940     }
941
942     /// Iterates over the diagnostic items in the given crate.
943     fn get_diagnostic_items(&self, tcx: TyCtxt<'tcx>) -> &'tcx FxHashMap<Symbol, DefId> {
944         tcx.arena.alloc(if self.root.is_proc_macro_crate() {
945             // Proc macro crates do not export any diagnostic-items to the target.
946             Default::default()
947         } else {
948             self.root
949                 .diagnostic_items
950                 .decode(self)
951                 .map(|(name, def_index)| (name, self.local_def_id(def_index)))
952                 .collect()
953         })
954     }
955
956     /// Iterates over each child of the given item.
957     fn each_child_of_item<F>(&self, id: DefIndex, mut callback: F, sess: &Session)
958     where
959         F: FnMut(Export<hir::HirId>),
960     {
961         if let Some(proc_macros_ids) = self.root.proc_macro_data.map(|d| d.decode(self)) {
962             /* If we are loading as a proc macro, we want to return the view of this crate
963              * as a proc macro crate.
964              */
965             if id == CRATE_DEF_INDEX {
966                 for def_index in proc_macros_ids {
967                     let raw_macro = self.raw_proc_macro(def_index);
968                     let res = Res::Def(
969                         DefKind::Macro(macro_kind(raw_macro)),
970                         self.local_def_id(def_index),
971                     );
972                     let ident = Ident::from_str(raw_macro.name());
973                     callback(Export { ident, res, vis: ty::Visibility::Public, span: DUMMY_SP });
974                 }
975             }
976             return;
977         }
978
979         // Find the item.
980         let kind = match self.maybe_kind(id) {
981             None => return,
982             Some(kind) => kind,
983         };
984
985         // Iterate over all children.
986         let macros_only = self.dep_kind.lock().macros_only();
987         let children = self.root.per_def.children.get(self, id).unwrap_or(Lazy::empty());
988         for child_index in children.decode((self, sess)) {
989             if macros_only {
990                 continue;
991             }
992
993             // Get the item.
994             if let Some(child_kind) = self.maybe_kind(child_index) {
995                 match child_kind {
996                     EntryKind::MacroDef(..) => {}
997                     _ if macros_only => continue,
998                     _ => {}
999                 }
1000
1001                 // Hand off the item to the callback.
1002                 match child_kind {
1003                     // FIXME(eddyb) Don't encode these in children.
1004                     EntryKind::ForeignMod => {
1005                         let child_children = self
1006                             .root
1007                             .per_def
1008                             .children
1009                             .get(self, child_index)
1010                             .unwrap_or(Lazy::empty());
1011                         for child_index in child_children.decode((self, sess)) {
1012                             if let Some(kind) = self.def_kind(child_index) {
1013                                 callback(Export {
1014                                     res: Res::Def(kind, self.local_def_id(child_index)),
1015                                     ident: self.item_ident(child_index, sess),
1016                                     vis: self.get_visibility(child_index),
1017                                     span: self
1018                                         .root
1019                                         .per_def
1020                                         .span
1021                                         .get(self, child_index)
1022                                         .unwrap()
1023                                         .decode((self, sess)),
1024                                 });
1025                             }
1026                         }
1027                         continue;
1028                     }
1029                     EntryKind::Impl(_) => continue,
1030
1031                     _ => {}
1032                 }
1033
1034                 let def_key = self.def_key(child_index);
1035                 let span = self.get_span(child_index, sess);
1036                 if let (Some(kind), true) = (
1037                     self.def_kind(child_index),
1038                     def_key.disambiguated_data.data.get_opt_name().is_some(),
1039                 ) {
1040                     let ident = self.item_ident(child_index, sess);
1041                     let vis = self.get_visibility(child_index);
1042                     let def_id = self.local_def_id(child_index);
1043                     let res = Res::Def(kind, def_id);
1044                     callback(Export { res, ident, vis, span });
1045                     // For non-re-export structs and variants add their constructors to children.
1046                     // Re-export lists automatically contain constructors when necessary.
1047                     match kind {
1048                         DefKind::Struct => {
1049                             if let Some(ctor_def_id) = self.get_ctor_def_id(child_index) {
1050                                 let ctor_kind = self.get_ctor_kind(child_index);
1051                                 let ctor_res =
1052                                     Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id);
1053                                 let vis = self.get_visibility(ctor_def_id.index);
1054                                 callback(Export { res: ctor_res, vis, ident, span });
1055                             }
1056                         }
1057                         DefKind::Variant => {
1058                             // Braced variants, unlike structs, generate unusable names in
1059                             // value namespace, they are reserved for possible future use.
1060                             // It's ok to use the variant's id as a ctor id since an
1061                             // error will be reported on any use of such resolution anyway.
1062                             let ctor_def_id = self.get_ctor_def_id(child_index).unwrap_or(def_id);
1063                             let ctor_kind = self.get_ctor_kind(child_index);
1064                             let ctor_res =
1065                                 Res::Def(DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_def_id);
1066                             let mut vis = self.get_visibility(ctor_def_id.index);
1067                             if ctor_def_id == def_id && vis == ty::Visibility::Public {
1068                                 // For non-exhaustive variants lower the constructor visibility to
1069                                 // within the crate. We only need this for fictive constructors,
1070                                 // for other constructors correct visibilities
1071                                 // were already encoded in metadata.
1072                                 let attrs = self.get_item_attrs(def_id.index, sess);
1073                                 if attr::contains_name(&attrs, sym::non_exhaustive) {
1074                                     let crate_def_id = self.local_def_id(CRATE_DEF_INDEX);
1075                                     vis = ty::Visibility::Restricted(crate_def_id);
1076                                 }
1077                             }
1078                             callback(Export { res: ctor_res, ident, vis, span });
1079                         }
1080                         _ => {}
1081                     }
1082                 }
1083             }
1084         }
1085
1086         if let EntryKind::Mod(data) = kind {
1087             for exp in data.decode((self, sess)).reexports.decode((self, sess)) {
1088                 match exp.res {
1089                     Res::Def(DefKind::Macro(..), _) => {}
1090                     _ if macros_only => continue,
1091                     _ => {}
1092                 }
1093                 callback(exp);
1094             }
1095         }
1096     }
1097
1098     fn is_item_mir_available(&self, id: DefIndex) -> bool {
1099         !self.is_proc_macro(id) && self.root.per_def.mir.get(self, id).is_some()
1100     }
1101
1102     fn get_optimized_mir(&self, tcx: TyCtxt<'tcx>, id: DefIndex) -> BodyAndCache<'tcx> {
1103         let mut cache = self
1104             .root
1105             .per_def
1106             .mir
1107             .get(self, id)
1108             .filter(|_| !self.is_proc_macro(id))
1109             .unwrap_or_else(|| {
1110                 bug!("get_optimized_mir: missing MIR for `{:?}`", self.local_def_id(id))
1111             })
1112             .decode((self, tcx));
1113         cache.ensure_predecessors();
1114         cache
1115     }
1116
1117     fn get_promoted_mir(
1118         &self,
1119         tcx: TyCtxt<'tcx>,
1120         id: DefIndex,
1121     ) -> IndexVec<Promoted, BodyAndCache<'tcx>> {
1122         let mut cache = self
1123             .root
1124             .per_def
1125             .promoted_mir
1126             .get(self, id)
1127             .filter(|_| !self.is_proc_macro(id))
1128             .unwrap_or_else(|| {
1129                 bug!("get_promoted_mir: missing MIR for `{:?}`", self.local_def_id(id))
1130             })
1131             .decode((self, tcx));
1132         for body in cache.iter_mut() {
1133             body.ensure_predecessors();
1134         }
1135         cache
1136     }
1137
1138     fn mir_const_qualif(&self, id: DefIndex) -> mir::ConstQualifs {
1139         match self.kind(id) {
1140             EntryKind::Const(qualif, _)
1141             | EntryKind::AssocConst(AssocContainer::ImplDefault, qualif, _)
1142             | EntryKind::AssocConst(AssocContainer::ImplFinal, qualif, _) => qualif,
1143             _ => bug!(),
1144         }
1145     }
1146
1147     fn get_associated_item(&self, id: DefIndex, sess: &Session) -> ty::AssocItem {
1148         let def_key = self.def_key(id);
1149         let parent = self.local_def_id(def_key.parent.unwrap());
1150         let ident = self.item_ident(id, sess);
1151
1152         let (kind, container, has_self) = match self.kind(id) {
1153             EntryKind::AssocConst(container, _, _) => (ty::AssocKind::Const, container, false),
1154             EntryKind::AssocFn(data) => {
1155                 let data = data.decode(self);
1156                 (ty::AssocKind::Method, data.container, data.has_self)
1157             }
1158             EntryKind::AssocType(container) => (ty::AssocKind::Type, container, false),
1159             EntryKind::AssocOpaqueTy(container) => (ty::AssocKind::OpaqueTy, container, false),
1160             _ => bug!("cannot get associated-item of `{:?}`", def_key),
1161         };
1162
1163         ty::AssocItem {
1164             ident,
1165             kind,
1166             vis: self.get_visibility(id),
1167             defaultness: container.defaultness(),
1168             def_id: self.local_def_id(id),
1169             container: container.with_def_id(parent),
1170             method_has_self_argument: has_self,
1171         }
1172     }
1173
1174     fn get_item_variances(&self, id: DefIndex) -> Vec<ty::Variance> {
1175         self.root.per_def.variances.get(self, id).unwrap_or(Lazy::empty()).decode(self).collect()
1176     }
1177
1178     fn get_ctor_kind(&self, node_id: DefIndex) -> CtorKind {
1179         match self.kind(node_id) {
1180             EntryKind::Struct(data, _) | EntryKind::Union(data, _) | EntryKind::Variant(data) => {
1181                 data.decode(self).ctor_kind
1182             }
1183             _ => CtorKind::Fictive,
1184         }
1185     }
1186
1187     fn get_ctor_def_id(&self, node_id: DefIndex) -> Option<DefId> {
1188         match self.kind(node_id) {
1189             EntryKind::Struct(data, _) => {
1190                 data.decode(self).ctor.map(|index| self.local_def_id(index))
1191             }
1192             EntryKind::Variant(data) => {
1193                 data.decode(self).ctor.map(|index| self.local_def_id(index))
1194             }
1195             _ => None,
1196         }
1197     }
1198
1199     fn get_item_attrs(&self, node_id: DefIndex, sess: &Session) -> Lrc<[ast::Attribute]> {
1200         // The attributes for a tuple struct/variant are attached to the definition, not the ctor;
1201         // we assume that someone passing in a tuple struct ctor is actually wanting to
1202         // look at the definition
1203         let def_key = self.def_key(node_id);
1204         let item_id = if def_key.disambiguated_data.data == DefPathData::Ctor {
1205             def_key.parent.unwrap()
1206         } else {
1207             node_id
1208         };
1209
1210         Lrc::from(
1211             self.root
1212                 .per_def
1213                 .attributes
1214                 .get(self, item_id)
1215                 .unwrap_or(Lazy::empty())
1216                 .decode((self, sess))
1217                 .collect::<Vec<_>>(),
1218         )
1219     }
1220
1221     fn get_struct_field_names(&self, id: DefIndex, sess: &Session) -> Vec<Spanned<ast::Name>> {
1222         self.root
1223             .per_def
1224             .children
1225             .get(self, id)
1226             .unwrap_or(Lazy::empty())
1227             .decode(self)
1228             .map(|index| respan(self.get_span(index, sess), self.item_ident(index, sess).name))
1229             .collect()
1230     }
1231
1232     fn get_inherent_implementations_for_type(
1233         &self,
1234         tcx: TyCtxt<'tcx>,
1235         id: DefIndex,
1236     ) -> &'tcx [DefId] {
1237         tcx.arena.alloc_from_iter(
1238             self.root
1239                 .per_def
1240                 .inherent_impls
1241                 .get(self, id)
1242                 .unwrap_or(Lazy::empty())
1243                 .decode(self)
1244                 .map(|index| self.local_def_id(index)),
1245         )
1246     }
1247
1248     fn get_implementations_for_trait(
1249         &self,
1250         tcx: TyCtxt<'tcx>,
1251         filter: Option<DefId>,
1252     ) -> &'tcx [DefId] {
1253         if self.root.is_proc_macro_crate() {
1254             // proc-macro crates export no trait impls.
1255             return &[];
1256         }
1257
1258         // Do a reverse lookup beforehand to avoid touching the crate_num
1259         // hash map in the loop below.
1260         let filter = match filter.map(|def_id| self.reverse_translate_def_id(def_id)) {
1261             Some(Some(def_id)) => Some((def_id.krate.as_u32(), def_id.index)),
1262             Some(None) => return &[],
1263             None => None,
1264         };
1265
1266         if let Some(filter) = filter {
1267             if let Some(impls) = self.trait_impls.get(&filter) {
1268                 tcx.arena.alloc_from_iter(impls.decode(self).map(|idx| self.local_def_id(idx)))
1269             } else {
1270                 &[]
1271             }
1272         } else {
1273             tcx.arena.alloc_from_iter(
1274                 self.trait_impls
1275                     .values()
1276                     .flat_map(|impls| impls.decode(self).map(|idx| self.local_def_id(idx))),
1277             )
1278         }
1279     }
1280
1281     fn get_trait_of_item(&self, id: DefIndex) -> Option<DefId> {
1282         let def_key = self.def_key(id);
1283         match def_key.disambiguated_data.data {
1284             DefPathData::TypeNs(..) | DefPathData::ValueNs(..) => (),
1285             // Not an associated item
1286             _ => return None,
1287         }
1288         def_key.parent.and_then(|parent_index| match self.kind(parent_index) {
1289             EntryKind::Trait(_) | EntryKind::TraitAlias => Some(self.local_def_id(parent_index)),
1290             _ => None,
1291         })
1292     }
1293
1294     fn get_native_libraries(&self, sess: &Session) -> Vec<NativeLibrary> {
1295         if self.root.is_proc_macro_crate() {
1296             // Proc macro crates do not have any *target* native libraries.
1297             vec![]
1298         } else {
1299             self.root.native_libraries.decode((self, sess)).collect()
1300         }
1301     }
1302
1303     fn get_foreign_modules(&self, tcx: TyCtxt<'tcx>) -> &'tcx [ForeignModule] {
1304         if self.root.is_proc_macro_crate() {
1305             // Proc macro crates do not have any *target* foreign modules.
1306             &[]
1307         } else {
1308             tcx.arena.alloc_from_iter(self.root.foreign_modules.decode((self, tcx.sess)))
1309         }
1310     }
1311
1312     fn get_dylib_dependency_formats(
1313         &self,
1314         tcx: TyCtxt<'tcx>,
1315     ) -> &'tcx [(CrateNum, LinkagePreference)] {
1316         tcx.arena.alloc_from_iter(
1317             self.root.dylib_dependency_formats.decode(self).enumerate().flat_map(|(i, link)| {
1318                 let cnum = CrateNum::new(i + 1);
1319                 link.map(|link| (self.cnum_map[cnum], link))
1320             }),
1321         )
1322     }
1323
1324     fn get_missing_lang_items(&self, tcx: TyCtxt<'tcx>) -> &'tcx [lang_items::LangItem] {
1325         if self.root.is_proc_macro_crate() {
1326             // Proc macro crates do not depend on any target weak lang-items.
1327             &[]
1328         } else {
1329             tcx.arena.alloc_from_iter(self.root.lang_items_missing.decode(self))
1330         }
1331     }
1332
1333     fn get_fn_param_names(&self, id: DefIndex) -> Vec<ast::Name> {
1334         let param_names = match self.kind(id) {
1335             EntryKind::Fn(data) | EntryKind::ForeignFn(data) => data.decode(self).param_names,
1336             EntryKind::AssocFn(data) => data.decode(self).fn_data.param_names,
1337             _ => Lazy::empty(),
1338         };
1339         param_names.decode(self).collect()
1340     }
1341
1342     fn exported_symbols(
1343         &self,
1344         tcx: TyCtxt<'tcx>,
1345     ) -> Vec<(ExportedSymbol<'tcx>, SymbolExportLevel)> {
1346         if self.root.is_proc_macro_crate() {
1347             // If this crate is a custom derive crate, then we're not even going to
1348             // link those in so we skip those crates.
1349             vec![]
1350         } else {
1351             self.root.exported_symbols.decode((self, tcx)).collect()
1352         }
1353     }
1354
1355     fn get_rendered_const(&self, id: DefIndex) -> String {
1356         match self.kind(id) {
1357             EntryKind::Const(_, data) | EntryKind::AssocConst(_, _, data) => data.decode(self).0,
1358             _ => bug!(),
1359         }
1360     }
1361
1362     fn get_macro(&self, id: DefIndex, sess: &Session) -> MacroDef {
1363         match self.kind(id) {
1364             EntryKind::MacroDef(macro_def) => macro_def.decode((self, sess)),
1365             _ => bug!(),
1366         }
1367     }
1368
1369     // This replicates some of the logic of the crate-local `is_const_fn_raw` query, because we
1370     // don't serialize constness for tuple variant and tuple struct constructors.
1371     fn is_const_fn_raw(&self, id: DefIndex) -> bool {
1372         let constness = match self.kind(id) {
1373             EntryKind::AssocFn(data) => data.decode(self).fn_data.constness,
1374             EntryKind::Fn(data) => data.decode(self).constness,
1375             // Some intrinsics can be const fn. While we could recompute this (at least until we
1376             // stop having hardcoded whitelists and move to stability attributes), it seems cleaner
1377             // to treat all const fns equally.
1378             EntryKind::ForeignFn(data) => data.decode(self).constness,
1379             EntryKind::Variant(..) | EntryKind::Struct(..) => hir::Constness::Const,
1380             _ => hir::Constness::NotConst,
1381         };
1382         constness == hir::Constness::Const
1383     }
1384
1385     fn asyncness(&self, id: DefIndex) -> hir::IsAsync {
1386         match self.kind(id) {
1387             EntryKind::Fn(data) => data.decode(self).asyncness,
1388             EntryKind::AssocFn(data) => data.decode(self).fn_data.asyncness,
1389             EntryKind::ForeignFn(data) => data.decode(self).asyncness,
1390             _ => bug!("asyncness: expected function kind"),
1391         }
1392     }
1393
1394     fn is_foreign_item(&self, id: DefIndex) -> bool {
1395         match self.kind(id) {
1396             EntryKind::ForeignImmStatic | EntryKind::ForeignMutStatic | EntryKind::ForeignFn(_) => {
1397                 true
1398             }
1399             _ => false,
1400         }
1401     }
1402
1403     fn static_mutability(&self, id: DefIndex) -> Option<hir::Mutability> {
1404         match self.kind(id) {
1405             EntryKind::ImmStatic | EntryKind::ForeignImmStatic => Some(hir::Mutability::Not),
1406             EntryKind::MutStatic | EntryKind::ForeignMutStatic => Some(hir::Mutability::Mut),
1407             _ => None,
1408         }
1409     }
1410
1411     fn generator_kind(&self, id: DefIndex) -> Option<hir::GeneratorKind> {
1412         match self.kind(id) {
1413             EntryKind::Generator(data) => Some(data),
1414             _ => None,
1415         }
1416     }
1417
1418     fn fn_sig(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> {
1419         self.root.per_def.fn_sig.get(self, id).unwrap().decode((self, tcx))
1420     }
1421
1422     #[inline]
1423     fn def_key(&self, index: DefIndex) -> DefKey {
1424         let mut key = self.def_path_table.def_key(index);
1425         if self.is_proc_macro(index) {
1426             let name = self.raw_proc_macro(index).name();
1427             key.disambiguated_data.data = DefPathData::MacroNs(Symbol::intern(name));
1428         }
1429         key
1430     }
1431
1432     // Returns the path leading to the thing with this `id`.
1433     fn def_path(&self, id: DefIndex) -> DefPath {
1434         debug!("def_path(cnum={:?}, id={:?})", self.cnum, id);
1435         DefPath::make(self.cnum, id, |parent| self.def_key(parent))
1436     }
1437
1438     /// Imports the source_map from an external crate into the source_map of the crate
1439     /// currently being compiled (the "local crate").
1440     ///
1441     /// The import algorithm works analogous to how AST items are inlined from an
1442     /// external crate's metadata:
1443     /// For every SourceFile in the external source_map an 'inline' copy is created in the
1444     /// local source_map. The correspondence relation between external and local
1445     /// SourceFiles is recorded in the `ImportedSourceFile` objects returned from this
1446     /// function. When an item from an external crate is later inlined into this
1447     /// crate, this correspondence information is used to translate the span
1448     /// information of the inlined item so that it refers the correct positions in
1449     /// the local source_map (see `<decoder::DecodeContext as SpecializedDecoder<Span>>`).
1450     ///
1451     /// The import algorithm in the function below will reuse SourceFiles already
1452     /// existing in the local source_map. For example, even if the SourceFile of some
1453     /// source file of libstd gets imported many times, there will only ever be
1454     /// one SourceFile object for the corresponding file in the local source_map.
1455     ///
1456     /// Note that imported SourceFiles do not actually contain the source code of the
1457     /// file they represent, just information about length, line breaks, and
1458     /// multibyte characters. This information is enough to generate valid debuginfo
1459     /// for items inlined from other crates.
1460     ///
1461     /// Proc macro crates don't currently export spans, so this function does not have
1462     /// to work for them.
1463     fn imported_source_files(
1464         &self,
1465         local_source_map: &source_map::SourceMap,
1466     ) -> &'a [ImportedSourceFile] {
1467         self.cdata.source_map_import_info.init_locking(|| {
1468             let external_source_map = self.root.source_map.decode(self);
1469
1470             external_source_map
1471                 .map(|source_file_to_import| {
1472                     // We can't reuse an existing SourceFile, so allocate a new one
1473                     // containing the information we need.
1474                     let rustc_span::SourceFile {
1475                         name,
1476                         name_was_remapped,
1477                         src_hash,
1478                         start_pos,
1479                         end_pos,
1480                         mut lines,
1481                         mut multibyte_chars,
1482                         mut non_narrow_chars,
1483                         mut normalized_pos,
1484                         name_hash,
1485                         ..
1486                     } = source_file_to_import;
1487
1488                     let source_length = (end_pos - start_pos).to_usize();
1489
1490                     // Translate line-start positions and multibyte character
1491                     // position into frame of reference local to file.
1492                     // `SourceMap::new_imported_source_file()` will then translate those
1493                     // coordinates to their new global frame of reference when the
1494                     // offset of the SourceFile is known.
1495                     for pos in &mut lines {
1496                         *pos = *pos - start_pos;
1497                     }
1498                     for mbc in &mut multibyte_chars {
1499                         mbc.pos = mbc.pos - start_pos;
1500                     }
1501                     for swc in &mut non_narrow_chars {
1502                         *swc = *swc - start_pos;
1503                     }
1504                     for np in &mut normalized_pos {
1505                         np.pos = np.pos - start_pos;
1506                     }
1507
1508                     let local_version = local_source_map.new_imported_source_file(
1509                         name,
1510                         name_was_remapped,
1511                         src_hash,
1512                         name_hash,
1513                         source_length,
1514                         self.cnum,
1515                         lines,
1516                         multibyte_chars,
1517                         non_narrow_chars,
1518                         normalized_pos,
1519                         start_pos,
1520                         end_pos,
1521                     );
1522                     debug!(
1523                         "CrateMetaData::imported_source_files alloc \
1524                          source_file {:?} original (start_pos {:?} end_pos {:?}) \
1525                          translated (start_pos {:?} end_pos {:?})",
1526                         local_version.name,
1527                         start_pos,
1528                         end_pos,
1529                         local_version.start_pos,
1530                         local_version.end_pos
1531                     );
1532
1533                     ImportedSourceFile {
1534                         original_start_pos: start_pos,
1535                         original_end_pos: end_pos,
1536                         translated_source_file: local_version,
1537                     }
1538                 })
1539                 .collect()
1540         })
1541     }
1542 }
1543
1544 impl CrateMetadata {
1545     crate fn new(
1546         sess: &Session,
1547         blob: MetadataBlob,
1548         root: CrateRoot<'static>,
1549         raw_proc_macros: Option<&'static [ProcMacro]>,
1550         cnum: CrateNum,
1551         cnum_map: CrateNumMap,
1552         dep_kind: DepKind,
1553         source: CrateSource,
1554         private_dep: bool,
1555         host_hash: Option<Svh>,
1556     ) -> CrateMetadata {
1557         let def_path_table = record_time(&sess.perf_stats.decode_def_path_tables_time, || {
1558             root.def_path_table.decode((&blob, sess))
1559         });
1560         let trait_impls = root
1561             .impls
1562             .decode((&blob, sess))
1563             .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
1564             .collect();
1565         let alloc_decoding_state =
1566             AllocDecodingState::new(root.interpret_alloc_index.decode(&blob).collect());
1567         let dependencies = Lock::new(cnum_map.iter().cloned().collect());
1568         CrateMetadata {
1569             blob,
1570             root,
1571             def_path_table,
1572             trait_impls,
1573             raw_proc_macros,
1574             source_map_import_info: Once::new(),
1575             alloc_decoding_state,
1576             dep_node_index: AtomicCell::new(DepNodeIndex::INVALID),
1577             cnum,
1578             cnum_map,
1579             dependencies,
1580             dep_kind: Lock::new(dep_kind),
1581             source,
1582             private_dep,
1583             host_hash,
1584             extern_crate: Lock::new(None),
1585         }
1586     }
1587
1588     crate fn dependencies(&self) -> LockGuard<'_, Vec<CrateNum>> {
1589         self.dependencies.borrow()
1590     }
1591
1592     crate fn add_dependency(&self, cnum: CrateNum) {
1593         self.dependencies.borrow_mut().push(cnum);
1594     }
1595
1596     crate fn update_extern_crate(&self, new_extern_crate: ExternCrate) -> bool {
1597         let mut extern_crate = self.extern_crate.borrow_mut();
1598         let update = Some(new_extern_crate.rank()) > extern_crate.as_ref().map(ExternCrate::rank);
1599         if update {
1600             *extern_crate = Some(new_extern_crate);
1601         }
1602         update
1603     }
1604
1605     crate fn source(&self) -> &CrateSource {
1606         &self.source
1607     }
1608
1609     crate fn dep_kind(&self) -> DepKind {
1610         *self.dep_kind.lock()
1611     }
1612
1613     crate fn update_dep_kind(&self, f: impl FnOnce(DepKind) -> DepKind) {
1614         self.dep_kind.with_lock(|dep_kind| *dep_kind = f(*dep_kind))
1615     }
1616
1617     crate fn panic_strategy(&self) -> PanicStrategy {
1618         self.root.panic_strategy
1619     }
1620
1621     crate fn needs_panic_runtime(&self) -> bool {
1622         self.root.needs_panic_runtime
1623     }
1624
1625     crate fn is_panic_runtime(&self) -> bool {
1626         self.root.panic_runtime
1627     }
1628
1629     crate fn is_profiler_runtime(&self) -> bool {
1630         self.root.profiler_runtime
1631     }
1632
1633     crate fn needs_allocator(&self) -> bool {
1634         self.root.needs_allocator
1635     }
1636
1637     crate fn has_global_allocator(&self) -> bool {
1638         self.root.has_global_allocator
1639     }
1640
1641     crate fn has_default_lib_allocator(&self) -> bool {
1642         self.root.has_default_lib_allocator
1643     }
1644
1645     crate fn is_proc_macro_crate(&self) -> bool {
1646         self.root.is_proc_macro_crate()
1647     }
1648
1649     crate fn name(&self) -> Symbol {
1650         self.root.name
1651     }
1652
1653     crate fn disambiguator(&self) -> CrateDisambiguator {
1654         self.root.disambiguator
1655     }
1656
1657     crate fn hash(&self) -> Svh {
1658         self.root.hash
1659     }
1660
1661     fn local_def_id(&self, index: DefIndex) -> DefId {
1662         DefId { krate: self.cnum, index }
1663     }
1664
1665     // Translate a DefId from the current compilation environment to a DefId
1666     // for an external crate.
1667     fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
1668         for (local, &global) in self.cnum_map.iter_enumerated() {
1669             if global == did.krate {
1670                 return Some(DefId { krate: local, index: did.index });
1671             }
1672         }
1673
1674         None
1675     }
1676
1677     #[inline]
1678     fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
1679         self.def_path_table.def_path_hash(index)
1680     }
1681
1682     /// Get the `DepNodeIndex` corresponding this crate. The result of this
1683     /// method is cached in the `dep_node_index` field.
1684     fn get_crate_dep_node_index(&self, tcx: TyCtxt<'tcx>) -> DepNodeIndex {
1685         let mut dep_node_index = self.dep_node_index.load();
1686
1687         if unlikely!(dep_node_index == DepNodeIndex::INVALID) {
1688             // We have not cached the DepNodeIndex for this upstream crate yet,
1689             // so use the dep-graph to find it out and cache it.
1690             // Note that multiple threads can enter this block concurrently.
1691             // That is fine because the DepNodeIndex remains constant
1692             // throughout the whole compilation session, and multiple stores
1693             // would always write the same value.
1694
1695             let def_path_hash = self.def_path_hash(CRATE_DEF_INDEX);
1696             let dep_node =
1697                 DepNode::from_def_path_hash(def_path_hash, dep_graph::DepKind::CrateMetadata);
1698
1699             dep_node_index = tcx.dep_graph.dep_node_index_of(&dep_node);
1700             assert!(dep_node_index != DepNodeIndex::INVALID);
1701             self.dep_node_index.store(dep_node_index);
1702         }
1703
1704         dep_node_index
1705     }
1706 }
1707
1708 // Cannot be implemented on 'ProcMacro', as libproc_macro
1709 // does not depend on librustc_ast
1710 fn macro_kind(raw: &ProcMacro) -> MacroKind {
1711     match raw {
1712         ProcMacro::CustomDerive { .. } => MacroKind::Derive,
1713         ProcMacro::Attr { .. } => MacroKind::Attr,
1714         ProcMacro::Bang { .. } => MacroKind::Bang,
1715     }
1716 }