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