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