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