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