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