1use std::iter::TrustedLen;
4use std::ops::{Deref, DerefMut};
5use std::path::{Path, PathBuf};
6use std::sync::{Arc, OnceLock};
7use std::{io, mem};
8
9pub(super) use cstore_impl::provide;
10use rustc_ast as ast;
11use rustc_data_structures::fingerprint::Fingerprint;
12use rustc_data_structures::fx::FxIndexMap;
13use rustc_data_structures::owned_slice::OwnedSlice;
14use rustc_data_structures::sync::Lock;
15use rustc_data_structures::unhash::UnhashMap;
16use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind};
17use rustc_expand::proc_macro::{AttrProcMacro, BangProcMacro, DeriveProcMacro};
18use rustc_hir::Safety;
19use rustc_hir::def::Res;
20use rustc_hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE};
21use rustc_hir::definitions::{DefPath, DefPathData};
22use rustc_hir::diagnostic_items::DiagnosticItems;
23use rustc_index::Idx;
24use rustc_middle::middle::lib_features::LibFeatures;
25use rustc_middle::mir::interpret::{AllocDecodingSession, AllocDecodingState};
26use rustc_middle::ty::Visibility;
27use rustc_middle::ty::codec::TyDecoder;
28use rustc_middle::{bug, implement_ty_decoder};
29use rustc_proc_macro::bridge::client::ProcMacro;
30use rustc_serialize::opaque::MemDecoder;
31use rustc_serialize::{Decodable, Decoder};
32use rustc_session::config::TargetModifier;
33use rustc_session::cstore::{CrateSource, ExternCrate};
34use rustc_span::hygiene::HygieneDecodeContext;
35use rustc_span::{
36 BlobDecoder, BytePos, ByteSymbol, DUMMY_SP, Pos, RemapPathScopeComponents, SpanData,
37 SpanDecoder, Symbol, SyntaxContext, kw,
38};
39use tracing::debug;
40
41use crate::creader::CStore;
42use crate::eii::EiiMapEncodedKeyValue;
43use crate::rmeta::table::IsDefault;
44use crate::rmeta::*;
45
46mod cstore_impl;
47
48pub(crate) struct MetadataBlob(OwnedSlice);
52
53impl std::ops::Deref for MetadataBlob {
54 type Target = [u8];
55
56 #[inline]
57 fn deref(&self) -> &[u8] {
58 &self.0[..]
59 }
60}
61
62impl MetadataBlob {
63 pub(crate) fn new(slice: OwnedSlice) -> Result<Self, ()> {
65 if MemDecoder::new(&slice, 0).is_ok() { Ok(Self(slice)) } else { Err(()) }
66 }
67
68 pub(crate) fn bytes(&self) -> &OwnedSlice {
71 &self.0
72 }
73}
74
75pub(crate) type CrateNumMap = IndexVec<CrateNum, CrateNum>;
80
81pub(crate) type TargetModifiers = Vec<TargetModifier>;
83
84pub(crate) struct CrateMetadata {
85 blob: MetadataBlob,
87
88 root: CrateRoot,
91 trait_impls: FxIndexMap<(u32, DefIndex), LazyArray<(DefIndex, Option<SimplifiedType>)>>,
95 incoherent_impls: FxIndexMap<SimplifiedType, LazyArray<DefIndex>>,
100 raw_proc_macros: Option<&'static [ProcMacro]>,
102 source_map_import_info: Lock<Vec<Option<ImportedSourceFile>>>,
104 def_path_hash_map: DefPathHashMapRef<'static>,
106 expn_hash_map: OnceLock<UnhashMap<ExpnHash, ExpnIndex>>,
108 alloc_decoding_state: AllocDecodingState,
110 def_key_cache: Lock<FxHashMap<DefIndex, DefKey>>,
112
113 cnum: CrateNum,
116 cnum_map: CrateNumMap,
119 dep_kind: CrateDepKind,
121 source: Arc<CrateSource>,
123 private_dep: bool,
127 host_hash: Option<Svh>,
129 used: bool,
131
132 hygiene_context: HygieneDecodeContext,
138
139 extern_crate: Option<ExternCrate>,
143}
144
145#[derive(#[automatically_derived]
impl ::core::clone::Clone for ImportedSourceFile {
#[inline]
fn clone(&self) -> ImportedSourceFile {
ImportedSourceFile {
original_start_pos: ::core::clone::Clone::clone(&self.original_start_pos),
original_end_pos: ::core::clone::Clone::clone(&self.original_end_pos),
translated_source_file: ::core::clone::Clone::clone(&self.translated_source_file),
}
}
}Clone)]
148struct ImportedSourceFile {
149 original_start_pos: rustc_span::BytePos,
151 original_end_pos: rustc_span::BytePos,
153 translated_source_file: Arc<rustc_span::SourceFile>,
155}
156
157pub(super) struct BlobDecodeContext<'a> {
161 opaque: MemDecoder<'a>,
162 blob: &'a MetadataBlob,
163 lazy_state: LazyState,
164}
165
166pub(super) trait LazyDecoder: BlobDecoder {
172 fn set_lazy_state(&mut self, state: LazyState);
173 fn get_lazy_state(&self) -> LazyState;
174
175 fn read_lazy<T>(&mut self) -> LazyValue<T> {
176 self.read_lazy_offset_then(|pos| LazyValue::from_position(pos))
177 }
178
179 fn read_lazy_array<T>(&mut self, len: usize) -> LazyArray<T> {
180 self.read_lazy_offset_then(|pos| LazyArray::from_position_and_num_elems(pos, len))
181 }
182
183 fn read_lazy_table<I, T>(&mut self, width: usize, len: usize) -> LazyTable<I, T> {
184 self.read_lazy_offset_then(|pos| LazyTable::from_position_and_encoded_size(pos, width, len))
185 }
186
187 #[inline]
188 fn read_lazy_offset_then<T>(&mut self, f: impl Fn(NonZero<usize>) -> T) -> T {
189 let distance = self.read_usize();
190 let position = match self.get_lazy_state() {
191 LazyState::NoNode => ::rustc_middle::util::bug::bug_fmt(format_args!("read_lazy_with_meta: outside of a metadata node"))bug!("read_lazy_with_meta: outside of a metadata node"),
192 LazyState::NodeStart(start) => {
193 let start = start.get();
194 if !(distance <= start) {
::core::panicking::panic("assertion failed: distance <= start")
};assert!(distance <= start);
195 start - distance
196 }
197 LazyState::Previous(last_pos) => last_pos.get() + distance,
198 };
199 let position = NonZero::new(position).unwrap();
200 self.set_lazy_state(LazyState::Previous(position));
201 f(position)
202 }
203}
204
205impl<'a> LazyDecoder for BlobDecodeContext<'a> {
206 fn set_lazy_state(&mut self, state: LazyState) {
207 self.lazy_state = state;
208 }
209
210 fn get_lazy_state(&self) -> LazyState {
211 self.lazy_state
212 }
213}
214
215pub(super) struct MetadataDecodeContext<'a, 'tcx> {
219 blob_decoder: BlobDecodeContext<'a>,
220 cdata: CrateMetadataRef<'a>,
221 tcx: TyCtxt<'tcx>,
222
223 alloc_decoding_session: AllocDecodingSession<'a>,
225}
226
227impl<'a, 'tcx> LazyDecoder for MetadataDecodeContext<'a, 'tcx> {
228 fn set_lazy_state(&mut self, state: LazyState) {
229 self.lazy_state = state;
230 }
231
232 fn get_lazy_state(&self) -> LazyState {
233 self.lazy_state
234 }
235}
236
237impl<'a, 'tcx> DerefMut for MetadataDecodeContext<'a, 'tcx> {
238 fn deref_mut(&mut self) -> &mut Self::Target {
239 &mut self.blob_decoder
240 }
241}
242
243impl<'a, 'tcx> Deref for MetadataDecodeContext<'a, 'tcx> {
244 type Target = BlobDecodeContext<'a>;
245
246 fn deref(&self) -> &Self::Target {
247 &self.blob_decoder
248 }
249}
250
251pub(super) trait Metadata<'a>: Copy {
252 type Context: BlobDecoder + LazyDecoder;
253
254 fn blob(self) -> &'a MetadataBlob;
255 fn decoder(self, pos: usize) -> Self::Context;
256}
257
258impl<'a> Metadata<'a> for &'a MetadataBlob {
259 type Context = BlobDecodeContext<'a>;
260
261 fn blob(self) -> &'a MetadataBlob {
262 self
263 }
264
265 fn decoder(self, pos: usize) -> Self::Context {
266 BlobDecodeContext {
267 opaque: MemDecoder::new(self, pos).unwrap(),
275 lazy_state: LazyState::NoNode,
276 blob: self.blob(),
277 }
278 }
279}
280
281impl<'a, 'tcx> Metadata<'a> for (CrateMetadataRef<'a>, TyCtxt<'tcx>) {
282 type Context = MetadataDecodeContext<'a, 'tcx>;
283
284 fn blob(self) -> &'a MetadataBlob {
285 &self.0.cdata.blob
286 }
287
288 fn decoder(self, pos: usize) -> MetadataDecodeContext<'a, 'tcx> {
289 MetadataDecodeContext {
290 blob_decoder: self.blob().decoder(pos),
291 cdata: self.0,
292 tcx: self.1,
293 alloc_decoding_session: self.0.cdata.alloc_decoding_state.new_decoding_session(),
294 }
295 }
296}
297
298impl<T: ParameterizedOverTcx> LazyValue<T> {
299 #[inline]
300 fn decode<'a, 'tcx, M: Metadata<'a>>(self, metadata: M) -> T::Value<'tcx>
301 where
302 T::Value<'tcx>: Decodable<M::Context>,
303 {
304 let mut dcx = metadata.decoder(self.position.get());
305 dcx.set_lazy_state(LazyState::NodeStart(self.position));
306 T::Value::decode(&mut dcx)
307 }
308}
309
310struct DecodeIterator<T, D> {
311 elem_counter: std::ops::Range<usize>,
312 dcx: D,
313 _phantom: PhantomData<fn() -> T>,
314}
315
316impl<D: Decoder, T: Decodable<D>> Iterator for DecodeIterator<T, D> {
317 type Item = T;
318
319 #[inline(always)]
320 fn next(&mut self) -> Option<Self::Item> {
321 self.elem_counter.next().map(|_| T::decode(&mut self.dcx))
322 }
323
324 #[inline(always)]
325 fn size_hint(&self) -> (usize, Option<usize>) {
326 self.elem_counter.size_hint()
327 }
328}
329
330impl<D: Decoder, T: Decodable<D>> ExactSizeIterator for DecodeIterator<T, D> {
331 fn len(&self) -> usize {
332 self.elem_counter.len()
333 }
334}
335
336unsafe impl<D: Decoder, T: Decodable<D>> TrustedLen for DecodeIterator<T, D> {}
337
338impl<T: ParameterizedOverTcx> LazyArray<T> {
339 #[inline]
340 fn decode<'a, 'tcx, M: Metadata<'a>>(
341 self,
342 metadata: M,
343 ) -> DecodeIterator<T::Value<'tcx>, M::Context>
344 where
345 T::Value<'tcx>: Decodable<M::Context>,
346 {
347 let mut dcx = metadata.decoder(self.position.get());
348 dcx.set_lazy_state(LazyState::NodeStart(self.position));
349 DecodeIterator { elem_counter: (0..self.num_elems), dcx, _phantom: PhantomData }
350 }
351}
352
353impl<'a, 'tcx> MetadataDecodeContext<'a, 'tcx> {
354 #[inline]
355 fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
356 self.cdata.map_encoded_cnum_to_current(cnum)
357 }
358}
359
360impl<'a> BlobDecodeContext<'a> {
361 #[inline]
362 pub(crate) fn blob(&self) -> &'a MetadataBlob {
363 self.blob
364 }
365
366 fn decode_symbol_or_byte_symbol<S>(
367 &mut self,
368 new_from_index: impl Fn(u32) -> S,
369 read_and_intern_str_or_byte_str_this: impl Fn(&mut Self) -> S,
370 read_and_intern_str_or_byte_str_opaque: impl Fn(&mut MemDecoder<'a>) -> S,
371 ) -> S {
372 let tag = self.read_u8();
373
374 match tag {
375 SYMBOL_STR => read_and_intern_str_or_byte_str_this(self),
376 SYMBOL_OFFSET => {
377 let pos = self.read_usize();
379
380 self.opaque.with_position(pos, |d| read_and_intern_str_or_byte_str_opaque(d))
382 }
383 SYMBOL_PREDEFINED => new_from_index(self.read_u32()),
384 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
385 }
386 }
387}
388
389impl<'a, 'tcx> TyDecoder<'tcx> for MetadataDecodeContext<'a, 'tcx> {
390 const CLEAR_CROSS_CRATE: bool = true;
391
392 #[inline]
393 fn interner(&self) -> TyCtxt<'tcx> {
394 self.tcx
395 }
396
397 fn cached_ty_for_shorthand<F>(&mut self, shorthand: usize, or_insert_with: F) -> Ty<'tcx>
398 where
399 F: FnOnce(&mut Self) -> Ty<'tcx>,
400 {
401 let tcx = self.tcx;
402
403 let key = ty::CReaderCacheKey { cnum: Some(self.cdata.cnum), pos: shorthand };
404
405 if let Some(&ty) = tcx.ty_rcache.borrow().get(&key) {
406 return ty;
407 }
408
409 let ty = or_insert_with(self);
410 tcx.ty_rcache.borrow_mut().insert(key, ty);
411 ty
412 }
413
414 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
415 where
416 F: FnOnce(&mut Self) -> R,
417 {
418 let new_opaque = self.blob_decoder.opaque.split_at(pos);
419 let old_opaque = mem::replace(&mut self.blob_decoder.opaque, new_opaque);
420 let old_state = mem::replace(&mut self.blob_decoder.lazy_state, LazyState::NoNode);
421 let r = f(self);
422 self.blob_decoder.opaque = old_opaque;
423 self.blob_decoder.lazy_state = old_state;
424 r
425 }
426
427 fn decode_alloc_id(&mut self) -> rustc_middle::mir::interpret::AllocId {
428 let ads = self.alloc_decoding_session;
429 ads.decode_alloc_id(self)
430 }
431}
432
433impl<'a, 'tcx> Decodable<MetadataDecodeContext<'a, 'tcx>> for ExpnIndex {
434 #[inline]
435 fn decode(d: &mut MetadataDecodeContext<'a, 'tcx>) -> ExpnIndex {
436 ExpnIndex::from_u32(d.read_u32())
437 }
438}
439
440impl<'a, 'tcx> SpanDecoder for MetadataDecodeContext<'a, 'tcx> {
441 fn decode_attr_id(&mut self) -> rustc_span::AttrId {
442 self.tcx.sess.psess.attr_id_generator.mk_attr_id()
443 }
444
445 fn decode_crate_num(&mut self) -> CrateNum {
446 let cnum = CrateNum::from_u32(self.read_u32());
447 self.map_encoded_cnum_to_current(cnum)
448 }
449
450 fn decode_def_id(&mut self) -> DefId {
451 DefId { krate: Decodable::decode(self), index: Decodable::decode(self) }
452 }
453
454 fn decode_syntax_context(&mut self) -> SyntaxContext {
455 let cdata = self.cdata;
456 let tcx = self.tcx;
457
458 let cname = cdata.root.name();
459 rustc_span::hygiene::decode_syntax_context(self, &cdata.hygiene_context, |_, id| {
460 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/rmeta/decoder.rs:460",
"rustc_metadata::rmeta::decoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/decoder.rs"),
::tracing_core::__macro_support::Option::Some(460u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::decoder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("SpecializedDecoder<SyntaxContext>: decoding {0}",
id) as &dyn Value))])
});
} else { ; }
};debug!("SpecializedDecoder<SyntaxContext>: decoding {}", id);
461 cdata
462 .root
463 .syntax_contexts
464 .get((cdata, tcx), id)
465 .unwrap_or_else(|| {
::core::panicking::panic_fmt(format_args!("Missing SyntaxContext {0:?} for crate {1:?}",
id, cname));
}panic!("Missing SyntaxContext {id:?} for crate {cname:?}"))
466 .decode((cdata, tcx))
467 })
468 }
469
470 fn decode_expn_id(&mut self) -> ExpnId {
471 let local_cdata = self.cdata;
472
473 let tcx = self.tcx;
474 let cnum = CrateNum::decode(self);
475 let index = u32::decode(self);
476
477 let expn_id = rustc_span::hygiene::decode_expn_id(cnum, index, |expn_id| {
478 let ExpnId { krate: cnum, local_id: index } = expn_id;
479 if true {
match (&cnum, &LOCAL_CRATE) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
};debug_assert_ne!(cnum, LOCAL_CRATE);
482 let crate_data = if cnum == local_cdata.cnum {
483 local_cdata
484 } else {
485 local_cdata.cstore.get_crate_data(cnum)
486 };
487 let expn_data = crate_data
488 .root
489 .expn_data
490 .get((crate_data, tcx), index)
491 .unwrap()
492 .decode((crate_data, tcx));
493 let expn_hash = crate_data
494 .root
495 .expn_hashes
496 .get((crate_data, tcx), index)
497 .unwrap()
498 .decode((crate_data, tcx));
499 (expn_data, expn_hash)
500 });
501 expn_id
502 }
503
504 fn decode_span(&mut self) -> Span {
505 let start = self.position();
506 let tag = SpanTag(self.peek_byte());
507 let data = if tag.kind() == SpanKind::Indirect {
508 self.read_u8();
510 let bytes_needed = tag.length().unwrap().0 as usize;
512 let mut total = [0u8; usize::BITS as usize / 8];
513 total[..bytes_needed].copy_from_slice(self.read_raw_bytes(bytes_needed));
514 let offset_or_position = usize::from_le_bytes(total);
515 let position = if tag.is_relative_offset() {
516 start - offset_or_position
517 } else {
518 offset_or_position
519 };
520 self.with_position(position, SpanData::decode)
521 } else {
522 SpanData::decode(self)
523 };
524 data.span()
525 }
526}
527
528impl<'a, 'tcx> BlobDecoder for MetadataDecodeContext<'a, 'tcx> {
529 fn decode_def_index(&mut self) -> DefIndex {
530 self.blob_decoder.decode_def_index()
531 }
532 fn decode_symbol(&mut self) -> Symbol {
533 self.blob_decoder.decode_symbol()
534 }
535
536 fn decode_byte_symbol(&mut self) -> ByteSymbol {
537 self.blob_decoder.decode_byte_symbol()
538 }
539}
540
541impl<'a> BlobDecoder for BlobDecodeContext<'a> {
542 fn decode_def_index(&mut self) -> DefIndex {
543 DefIndex::from_u32(self.read_u32())
544 }
545 fn decode_symbol(&mut self) -> Symbol {
546 self.decode_symbol_or_byte_symbol(
547 Symbol::new,
548 |this| Symbol::intern(this.read_str()),
549 |opaque| Symbol::intern(opaque.read_str()),
550 )
551 }
552
553 fn decode_byte_symbol(&mut self) -> ByteSymbol {
554 self.decode_symbol_or_byte_symbol(
555 ByteSymbol::new,
556 |this| ByteSymbol::intern(this.read_byte_str()),
557 |opaque| ByteSymbol::intern(opaque.read_byte_str()),
558 )
559 }
560}
561
562impl<'a, 'tcx> Decodable<MetadataDecodeContext<'a, 'tcx>> for SpanData {
563 fn decode(decoder: &mut MetadataDecodeContext<'a, 'tcx>) -> SpanData {
564 let tag = SpanTag::decode(decoder);
565 let ctxt = tag.context().unwrap_or_else(|| SyntaxContext::decode(decoder));
566
567 if tag.kind() == SpanKind::Partial {
568 return DUMMY_SP.with_ctxt(ctxt).data();
569 }
570
571 if true {
if !(tag.kind() == SpanKind::Local || tag.kind() == SpanKind::Foreign) {
::core::panicking::panic("assertion failed: tag.kind() == SpanKind::Local || tag.kind() == SpanKind::Foreign")
};
};debug_assert!(tag.kind() == SpanKind::Local || tag.kind() == SpanKind::Foreign);
572
573 let lo = BytePos::decode(decoder);
574 let len = tag.length().unwrap_or_else(|| BytePos::decode(decoder));
575 let hi = lo + len;
576
577 let tcx = decoder.tcx;
578
579 let metadata_index = u32::decode(decoder);
581
582 let source_file = if tag.kind() == SpanKind::Local {
611 decoder.cdata.imported_source_file(tcx, metadata_index)
612 } else {
613 if decoder.cdata.root.is_proc_macro_crate() {
616 let cnum = u32::decode(decoder);
619 {
::core::panicking::panic_fmt(format_args!("Decoding of crate {0:?} tried to access proc-macro dep {1:?}",
decoder.cdata.root.header.name, cnum));
};panic!(
620 "Decoding of crate {:?} tried to access proc-macro dep {:?}",
621 decoder.cdata.root.header.name, cnum
622 );
623 }
624 let cnum = CrateNum::decode(decoder);
626 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/rmeta/decoder.rs:626",
"rustc_metadata::rmeta::decoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/decoder.rs"),
::tracing_core::__macro_support::Option::Some(626u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::decoder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("SpecializedDecoder<Span>::specialized_decode: loading source files from cnum {0:?}",
cnum) as &dyn Value))])
});
} else { ; }
};debug!(
627 "SpecializedDecoder<Span>::specialized_decode: loading source files from cnum {:?}",
628 cnum
629 );
630
631 let foreign_data = decoder.cdata.cstore.get_crate_data(cnum);
632 foreign_data.imported_source_file(tcx, metadata_index)
633 };
634
635 if true {
if !(lo + source_file.original_start_pos <= source_file.original_end_pos)
{
{
::core::panicking::panic_fmt(format_args!("Malformed encoded span: lo={0:?} source_file.original_start_pos={1:?} source_file.original_end_pos={2:?}",
lo, source_file.original_start_pos,
source_file.original_end_pos));
}
};
};debug_assert!(
637 lo + source_file.original_start_pos <= source_file.original_end_pos,
638 "Malformed encoded span: lo={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}",
639 lo,
640 source_file.original_start_pos,
641 source_file.original_end_pos
642 );
643
644 if true {
if !(hi + source_file.original_start_pos <= source_file.original_end_pos)
{
{
::core::panicking::panic_fmt(format_args!("Malformed encoded span: hi={0:?} source_file.original_start_pos={1:?} source_file.original_end_pos={2:?}",
hi, source_file.original_start_pos,
source_file.original_end_pos));
}
};
};debug_assert!(
646 hi + source_file.original_start_pos <= source_file.original_end_pos,
647 "Malformed encoded span: hi={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}",
648 hi,
649 source_file.original_start_pos,
650 source_file.original_end_pos
651 );
652
653 let lo = lo + source_file.translated_source_file.start_pos;
654 let hi = hi + source_file.translated_source_file.start_pos;
655
656 SpanData { lo, hi, ctxt, parent: None }
658 }
659}
660
661impl<'a, 'tcx> Decodable<MetadataDecodeContext<'a, 'tcx>> for &'tcx [(ty::Clause<'tcx>, Span)] {
662 fn decode(d: &mut MetadataDecodeContext<'a, 'tcx>) -> Self {
663 ty::codec::RefDecodable::decode(d)
664 }
665}
666
667impl<D: LazyDecoder, T> Decodable<D> for LazyValue<T> {
668 fn decode(decoder: &mut D) -> Self {
669 decoder.read_lazy()
670 }
671}
672
673impl<D: LazyDecoder, T> Decodable<D> for LazyArray<T> {
674 #[inline]
675 fn decode(decoder: &mut D) -> Self {
676 let len = decoder.read_usize();
677 if len == 0 { LazyArray::default() } else { decoder.read_lazy_array(len) }
678 }
679}
680
681impl<I: Idx, D: LazyDecoder, T> Decodable<D> for LazyTable<I, T> {
682 fn decode(decoder: &mut D) -> Self {
683 let width = decoder.read_usize();
684 let len = decoder.read_usize();
685 decoder.read_lazy_table(width, len)
686 }
687}
688
689mod meta {
690 use super::*;
691 mod __ty_decoder_impl {
use rustc_serialize::Decoder;
use super::MetadataDecodeContext;
impl<'a, 'tcx> Decoder for MetadataDecodeContext<'a, 'tcx> {
#[inline]
fn read_usize(&mut self) -> usize { self.opaque.read_usize() }
#[inline]
fn read_u128(&mut self) -> u128 { self.opaque.read_u128() }
#[inline]
fn read_u64(&mut self) -> u64 { self.opaque.read_u64() }
#[inline]
fn read_u32(&mut self) -> u32 { self.opaque.read_u32() }
#[inline]
fn read_u16(&mut self) -> u16 { self.opaque.read_u16() }
#[inline]
fn read_u8(&mut self) -> u8 { self.opaque.read_u8() }
#[inline]
fn read_isize(&mut self) -> isize { self.opaque.read_isize() }
#[inline]
fn read_i128(&mut self) -> i128 { self.opaque.read_i128() }
#[inline]
fn read_i64(&mut self) -> i64 { self.opaque.read_i64() }
#[inline]
fn read_i32(&mut self) -> i32 { self.opaque.read_i32() }
#[inline]
fn read_i16(&mut self) -> i16 { self.opaque.read_i16() }
#[inline]
fn read_raw_bytes(&mut self, len: usize) -> &[u8] {
self.opaque.read_raw_bytes(len)
}
#[inline]
fn peek_byte(&self) -> u8 { self.opaque.peek_byte() }
#[inline]
fn position(&self) -> usize { self.opaque.position() }
}
}implement_ty_decoder!(MetadataDecodeContext<'a, 'tcx>);
692}
693mod blob {
694 use super::*;
695 mod __ty_decoder_impl {
use rustc_serialize::Decoder;
use super::BlobDecodeContext;
impl<'a> Decoder for BlobDecodeContext<'a> {
#[inline]
fn read_usize(&mut self) -> usize { self.opaque.read_usize() }
#[inline]
fn read_u128(&mut self) -> u128 { self.opaque.read_u128() }
#[inline]
fn read_u64(&mut self) -> u64 { self.opaque.read_u64() }
#[inline]
fn read_u32(&mut self) -> u32 { self.opaque.read_u32() }
#[inline]
fn read_u16(&mut self) -> u16 { self.opaque.read_u16() }
#[inline]
fn read_u8(&mut self) -> u8 { self.opaque.read_u8() }
#[inline]
fn read_isize(&mut self) -> isize { self.opaque.read_isize() }
#[inline]
fn read_i128(&mut self) -> i128 { self.opaque.read_i128() }
#[inline]
fn read_i64(&mut self) -> i64 { self.opaque.read_i64() }
#[inline]
fn read_i32(&mut self) -> i32 { self.opaque.read_i32() }
#[inline]
fn read_i16(&mut self) -> i16 { self.opaque.read_i16() }
#[inline]
fn read_raw_bytes(&mut self, len: usize) -> &[u8] {
self.opaque.read_raw_bytes(len)
}
#[inline]
fn peek_byte(&self) -> u8 { self.opaque.peek_byte() }
#[inline]
fn position(&self) -> usize { self.opaque.position() }
}
}implement_ty_decoder!(BlobDecodeContext<'a>);
696}
697
698impl MetadataBlob {
699 pub(crate) fn check_compatibility(
700 &self,
701 cfg_version: &'static str,
702 ) -> Result<(), Option<String>> {
703 if !self.starts_with(METADATA_HEADER) {
704 if self.starts_with(b"rust") {
705 return Err(Some("<unknown rustc version>".to_owned()));
706 }
707 return Err(None);
708 }
709
710 let found_version =
711 LazyValue::<String>::from_position(NonZero::new(METADATA_HEADER.len() + 8).unwrap())
712 .decode(self);
713 if rustc_version(cfg_version) != found_version {
714 return Err(Some(found_version));
715 }
716
717 Ok(())
718 }
719
720 fn root_pos(&self) -> NonZero<usize> {
721 let offset = METADATA_HEADER.len();
722 let pos_bytes = self[offset..][..8].try_into().unwrap();
723 let pos = u64::from_le_bytes(pos_bytes);
724 NonZero::new(pos as usize).unwrap()
725 }
726
727 pub(crate) fn get_header(&self) -> CrateHeader {
728 let pos = self.root_pos();
729 LazyValue::<CrateHeader>::from_position(pos).decode(self)
730 }
731
732 pub(crate) fn get_root(&self) -> CrateRoot {
733 let pos = self.root_pos();
734 LazyValue::<CrateRoot>::from_position(pos).decode(self)
735 }
736
737 pub(crate) fn list_crate_metadata(
738 &self,
739 out: &mut dyn io::Write,
740 ls_kinds: &[String],
741 ) -> io::Result<()> {
742 let root = self.get_root();
743
744 let all_ls_kinds = <[_]>::into_vec(::alloc::boxed::box_new(["root".to_owned(),
"lang_items".to_owned(), "features".to_owned(),
"items".to_owned()]))vec![
745 "root".to_owned(),
746 "lang_items".to_owned(),
747 "features".to_owned(),
748 "items".to_owned(),
749 ];
750 let ls_kinds = if ls_kinds.contains(&"all".to_owned()) { &all_ls_kinds } else { ls_kinds };
751
752 for kind in ls_kinds {
753 match &**kind {
754 "root" => {
755 out.write_fmt(format_args!("Crate info:\n"))writeln!(out, "Crate info:")?;
756 out.write_fmt(format_args!("name {0}{1}\n", root.name(), root.extra_filename))writeln!(out, "name {}{}", root.name(), root.extra_filename)?;
757 out.write_fmt(format_args!("hash {0} stable_crate_id {1:?}\n", root.hash(),
root.stable_crate_id))writeln!(
758 out,
759 "hash {} stable_crate_id {:?}",
760 root.hash(),
761 root.stable_crate_id
762 )?;
763 out.write_fmt(format_args!("proc_macro {0:?}\n",
root.proc_macro_data.is_some()))writeln!(out, "proc_macro {:?}", root.proc_macro_data.is_some())?;
764 out.write_fmt(format_args!("triple {0}\n", root.header.triple.tuple()))writeln!(out, "triple {}", root.header.triple.tuple())?;
765 out.write_fmt(format_args!("edition {0}\n", root.edition))writeln!(out, "edition {}", root.edition)?;
766 out.write_fmt(format_args!("symbol_mangling_version {0:?}\n",
root.symbol_mangling_version))writeln!(out, "symbol_mangling_version {:?}", root.symbol_mangling_version)?;
767 out.write_fmt(format_args!("required_panic_strategy {0:?} panic_in_drop_strategy {1:?}\n",
root.required_panic_strategy, root.panic_in_drop_strategy))writeln!(
768 out,
769 "required_panic_strategy {:?} panic_in_drop_strategy {:?}",
770 root.required_panic_strategy, root.panic_in_drop_strategy
771 )?;
772 out.write_fmt(format_args!("has_global_allocator {0} has_alloc_error_handler {1} has_panic_handler {2} has_default_lib_allocator {3}\n",
root.has_global_allocator, root.has_alloc_error_handler,
root.has_panic_handler, root.has_default_lib_allocator))writeln!(
773 out,
774 "has_global_allocator {} has_alloc_error_handler {} has_panic_handler {} has_default_lib_allocator {}",
775 root.has_global_allocator,
776 root.has_alloc_error_handler,
777 root.has_panic_handler,
778 root.has_default_lib_allocator
779 )?;
780 out.write_fmt(format_args!("compiler_builtins {0} needs_allocator {1} needs_panic_runtime {2} no_builtins {3} panic_runtime {4} profiler_runtime {5}\n",
root.compiler_builtins, root.needs_allocator,
root.needs_panic_runtime, root.no_builtins, root.panic_runtime,
root.profiler_runtime))writeln!(
781 out,
782 "compiler_builtins {} needs_allocator {} needs_panic_runtime {} no_builtins {} panic_runtime {} profiler_runtime {}",
783 root.compiler_builtins,
784 root.needs_allocator,
785 root.needs_panic_runtime,
786 root.no_builtins,
787 root.panic_runtime,
788 root.profiler_runtime
789 )?;
790
791 out.write_fmt(format_args!("=External Dependencies=\n"))writeln!(out, "=External Dependencies=")?;
792 let dylib_dependency_formats =
793 root.dylib_dependency_formats.decode(self).collect::<Vec<_>>();
794 for (i, dep) in root.crate_deps.decode(self).enumerate() {
795 let CrateDep { name, extra_filename, hash, host_hash, kind, is_private } =
796 dep;
797 let number = i + 1;
798
799 out.write_fmt(format_args!("{2} {3}{4} hash {5} host_hash {6:?} kind {7:?} {0}{1}\n",
if is_private { "private" } else { "public" },
if dylib_dependency_formats.is_empty() {
String::new()
} else {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" linkage {0:?}",
dylib_dependency_formats[i]))
})
}, number, name, extra_filename, hash, host_hash, kind))writeln!(
800 out,
801 "{number} {name}{extra_filename} hash {hash} host_hash {host_hash:?} kind {kind:?} {privacy}{linkage}",
802 privacy = if is_private { "private" } else { "public" },
803 linkage = if dylib_dependency_formats.is_empty() {
804 String::new()
805 } else {
806 format!(" linkage {:?}", dylib_dependency_formats[i])
807 }
808 )?;
809 }
810 out.write_fmt(format_args!("\n"))write!(out, "\n")?;
811 }
812
813 "lang_items" => {
814 out.write_fmt(format_args!("=Lang items=\n"))writeln!(out, "=Lang items=")?;
815 for (id, lang_item) in root.lang_items.decode(self) {
816 out.write_fmt(format_args!("{0} = crate{1}\n", lang_item.name(),
DefPath::make(LOCAL_CRATE, id,
|parent|
root.tables.def_keys.get(self,
parent).unwrap().decode(self)).to_string_no_crate_verbose()))writeln!(
817 out,
818 "{} = crate{}",
819 lang_item.name(),
820 DefPath::make(LOCAL_CRATE, id, |parent| root
821 .tables
822 .def_keys
823 .get(self, parent)
824 .unwrap()
825 .decode(self))
826 .to_string_no_crate_verbose()
827 )?;
828 }
829 for lang_item in root.lang_items_missing.decode(self) {
830 out.write_fmt(format_args!("{0} = <missing>\n", lang_item.name()))writeln!(out, "{} = <missing>", lang_item.name())?;
831 }
832 out.write_fmt(format_args!("\n"))write!(out, "\n")?;
833 }
834
835 "features" => {
836 out.write_fmt(format_args!("=Lib features=\n"))writeln!(out, "=Lib features=")?;
837 for (feature, since) in root.lib_features.decode(self) {
838 out.write_fmt(format_args!("{0}{1}\n", feature,
if let FeatureStability::AcceptedSince(since) = since {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" since {0}", since))
})
} else { String::new() }))writeln!(
839 out,
840 "{}{}",
841 feature,
842 if let FeatureStability::AcceptedSince(since) = since {
843 format!(" since {since}")
844 } else {
845 String::new()
846 }
847 )?;
848 }
849 out.write_fmt(format_args!("\n"))write!(out, "\n")?;
850 }
851
852 "items" => {
853 out.write_fmt(format_args!("=Items=\n"))writeln!(out, "=Items=")?;
854
855 fn print_item(
856 blob: &MetadataBlob,
857 out: &mut dyn io::Write,
858 item: DefIndex,
859 indent: usize,
860 ) -> io::Result<()> {
861 let root = blob.get_root();
862
863 let def_kind = root.tables.def_kind.get(blob, item).unwrap();
864 let def_key = root.tables.def_keys.get(blob, item).unwrap().decode(blob);
865 #[allow(rustc::symbol_intern_string_literal)]
866 let def_name = if item == CRATE_DEF_INDEX {
867 kw::Crate
868 } else {
869 def_key
870 .disambiguated_data
871 .data
872 .get_opt_name()
873 .unwrap_or_else(|| Symbol::intern("???"))
874 };
875 let visibility =
876 root.tables.visibility.get(blob, item).unwrap().decode(blob).map_id(
877 |index| {
878 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("crate{0}",
DefPath::make(LOCAL_CRATE, index,
|parent|
root.tables.def_keys.get(blob,
parent).unwrap().decode(blob)).to_string_no_crate_verbose()))
})format!(
879 "crate{}",
880 DefPath::make(LOCAL_CRATE, index, |parent| root
881 .tables
882 .def_keys
883 .get(blob, parent)
884 .unwrap()
885 .decode(blob))
886 .to_string_no_crate_verbose()
887 )
888 },
889 );
890 out.write_fmt(format_args!("{3: <4$}{0:?} {1:?} {2} {{", visibility, def_kind,
def_name, "", indent))write!(
891 out,
892 "{nil: <indent$}{:?} {:?} {} {{",
893 visibility,
894 def_kind,
895 def_name,
896 nil = "",
897 )?;
898
899 if let Some(children) =
900 root.tables.module_children_non_reexports.get(blob, item)
901 {
902 out.write_fmt(format_args!("\n"))write!(out, "\n")?;
903 for child in children.decode(blob) {
904 print_item(blob, out, child, indent + 4)?;
905 }
906 out.write_fmt(format_args!("{0: <1$}}}\n", "", indent))writeln!(out, "{nil: <indent$}}}", nil = "")?;
907 } else {
908 out.write_fmt(format_args!("}}\n"))writeln!(out, "}}")?;
909 }
910
911 Ok(())
912 }
913
914 print_item(self, out, CRATE_DEF_INDEX, 0)?;
915
916 out.write_fmt(format_args!("\n"))write!(out, "\n")?;
917 }
918
919 _ => {
920 out.write_fmt(format_args!("unknown -Zls kind. allowed values are: all, root, lang_items, features, items\n"))writeln!(
921 out,
922 "unknown -Zls kind. allowed values are: all, root, lang_items, features, items"
923 )?;
924 }
925 }
926 }
927
928 Ok(())
929 }
930}
931
932impl CrateRoot {
933 pub(crate) fn is_proc_macro_crate(&self) -> bool {
934 self.proc_macro_data.is_some()
935 }
936
937 pub(crate) fn name(&self) -> Symbol {
938 self.header.name
939 }
940
941 pub(crate) fn hash(&self) -> Svh {
942 self.header.hash
943 }
944
945 pub(crate) fn stable_crate_id(&self) -> StableCrateId {
946 self.stable_crate_id
947 }
948
949 pub(crate) fn decode_crate_deps<'a>(
950 &self,
951 metadata: &'a MetadataBlob,
952 ) -> impl ExactSizeIterator<Item = CrateDep> {
953 self.crate_deps.decode(metadata)
954 }
955
956 pub(crate) fn decode_target_modifiers<'a>(
957 &self,
958 metadata: &'a MetadataBlob,
959 ) -> impl ExactSizeIterator<Item = TargetModifier> {
960 self.target_modifiers.decode(metadata)
961 }
962}
963
964impl<'a> CrateMetadataRef<'a> {
965 fn missing(self, descr: &str, id: DefIndex) -> ! {
966 ::rustc_middle::util::bug::bug_fmt(format_args!("missing `{1}` for {0:?}",
self.local_def_id(id), descr))bug!("missing `{descr}` for {:?}", self.local_def_id(id))
967 }
968
969 fn raw_proc_macro(self, tcx: TyCtxt<'_>, id: DefIndex) -> &'a ProcMacro {
970 let pos = self
973 .root
974 .proc_macro_data
975 .as_ref()
976 .unwrap()
977 .macros
978 .decode((self, tcx))
979 .position(|i| i == id)
980 .unwrap();
981 &self.raw_proc_macros.unwrap()[pos]
982 }
983
984 fn opt_item_name(self, item_index: DefIndex) -> Option<Symbol> {
985 let def_key = self.def_key(item_index);
986 def_key.disambiguated_data.data.get_opt_name().or_else(|| {
987 if def_key.disambiguated_data.data == DefPathData::Ctor {
988 let parent_index = def_key.parent.expect("no parent for a constructor");
989 self.def_key(parent_index).disambiguated_data.data.get_opt_name()
990 } else {
991 None
992 }
993 })
994 }
995
996 fn item_name(self, item_index: DefIndex) -> Symbol {
997 self.opt_item_name(item_index).expect("no encoded ident for item")
998 }
999
1000 fn opt_item_ident(self, tcx: TyCtxt<'_>, item_index: DefIndex) -> Option<Ident> {
1001 let name = self.opt_item_name(item_index)?;
1002 let span = self
1003 .root
1004 .tables
1005 .def_ident_span
1006 .get((self, tcx), item_index)
1007 .unwrap_or_else(|| self.missing("def_ident_span", item_index))
1008 .decode((self, tcx));
1009 Some(Ident::new(name, span))
1010 }
1011
1012 fn item_ident(self, tcx: TyCtxt<'_>, item_index: DefIndex) -> Ident {
1013 self.opt_item_ident(tcx, item_index).expect("no encoded ident for item")
1014 }
1015
1016 #[inline]
1017 pub(super) fn map_encoded_cnum_to_current(self, cnum: CrateNum) -> CrateNum {
1018 if cnum == LOCAL_CRATE { self.cnum } else { self.cnum_map[cnum] }
1019 }
1020
1021 fn def_kind(self, tcx: TyCtxt<'_>, item_id: DefIndex) -> DefKind {
1022 self.root
1023 .tables
1024 .def_kind
1025 .get((self, tcx), item_id)
1026 .unwrap_or_else(|| self.missing("def_kind", item_id))
1027 }
1028
1029 fn get_span(self, tcx: TyCtxt<'_>, index: DefIndex) -> Span {
1030 self.root
1031 .tables
1032 .def_span
1033 .get((self, tcx), index)
1034 .unwrap_or_else(|| self.missing("def_span", index))
1035 .decode((self, tcx))
1036 }
1037
1038 fn load_proc_macro<'tcx>(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> SyntaxExtension {
1039 let (name, kind, helper_attrs) = match *self.raw_proc_macro(tcx, id) {
1040 ProcMacro::CustomDerive { trait_name, attributes, client } => {
1041 let helper_attrs =
1042 attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
1043 (
1044 trait_name,
1045 SyntaxExtensionKind::Derive(Arc::new(DeriveProcMacro { client })),
1046 helper_attrs,
1047 )
1048 }
1049 ProcMacro::Attr { name, client } => {
1050 (name, SyntaxExtensionKind::Attr(Arc::new(AttrProcMacro { client })), Vec::new())
1051 }
1052 ProcMacro::Bang { name, client } => {
1053 (name, SyntaxExtensionKind::Bang(Arc::new(BangProcMacro { client })), Vec::new())
1054 }
1055 };
1056
1057 let sess = tcx.sess;
1058 let attrs: Vec<_> = self.get_item_attrs(tcx, id).collect();
1059 SyntaxExtension::new(
1060 sess,
1061 kind,
1062 self.get_span(tcx, id),
1063 helper_attrs,
1064 self.root.edition,
1065 Symbol::intern(name),
1066 &attrs,
1067 false,
1068 )
1069 }
1070
1071 fn get_variant(
1072 self,
1073 tcx: TyCtxt<'_>,
1074 kind: DefKind,
1075 index: DefIndex,
1076 parent_did: DefId,
1077 ) -> (VariantIdx, ty::VariantDef) {
1078 let adt_kind = match kind {
1079 DefKind::Variant => ty::AdtKind::Enum,
1080 DefKind::Struct => ty::AdtKind::Struct,
1081 DefKind::Union => ty::AdtKind::Union,
1082 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
1083 };
1084
1085 let data =
1086 self.root.tables.variant_data.get((self, tcx), index).unwrap().decode((self, tcx));
1087
1088 let variant_did =
1089 if adt_kind == ty::AdtKind::Enum { Some(self.local_def_id(index)) } else { None };
1090 let ctor = data.ctor.map(|(kind, index)| (kind, self.local_def_id(index)));
1091
1092 (
1093 data.idx,
1094 ty::VariantDef::new(
1095 self.item_name(index),
1096 variant_did,
1097 ctor,
1098 data.discr,
1099 self.get_associated_item_or_field_def_ids(tcx, index)
1100 .map(|did| ty::FieldDef {
1101 did,
1102 name: self.item_name(did.index),
1103 vis: self.get_visibility(tcx, did.index),
1104 safety: self.get_safety(tcx, did.index),
1105 value: self.get_default_field(tcx, did.index),
1106 })
1107 .collect(),
1108 parent_did,
1109 None,
1110 data.is_non_exhaustive,
1111 ),
1112 )
1113 }
1114
1115 fn get_adt_def<'tcx>(self, tcx: TyCtxt<'tcx>, item_id: DefIndex) -> ty::AdtDef<'tcx> {
1116 let kind = self.def_kind(tcx, item_id);
1117 let did = self.local_def_id(item_id);
1118
1119 let adt_kind = match kind {
1120 DefKind::Enum => ty::AdtKind::Enum,
1121 DefKind::Struct => ty::AdtKind::Struct,
1122 DefKind::Union => ty::AdtKind::Union,
1123 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("get_adt_def called on a non-ADT {0:?}",
did))bug!("get_adt_def called on a non-ADT {:?}", did),
1124 };
1125 let repr =
1126 self.root.tables.repr_options.get((self, tcx), item_id).unwrap().decode((self, tcx));
1127
1128 let mut variants: Vec<_> = if let ty::AdtKind::Enum = adt_kind {
1129 self.root
1130 .tables
1131 .module_children_non_reexports
1132 .get((self, tcx), item_id)
1133 .expect("variants are not encoded for an enum")
1134 .decode((self, tcx))
1135 .filter_map(|index| {
1136 let kind = self.def_kind(tcx, index);
1137 match kind {
1138 DefKind::Ctor(..) => None,
1139 _ => Some(self.get_variant(tcx, kind, index, did)),
1140 }
1141 })
1142 .collect()
1143 } else {
1144 std::iter::once(self.get_variant(tcx, kind, item_id, did)).collect()
1145 };
1146
1147 variants.sort_by_key(|(idx, _)| *idx);
1148
1149 tcx.mk_adt_def(
1150 did,
1151 adt_kind,
1152 variants.into_iter().map(|(_, variant)| variant).collect(),
1153 repr,
1154 )
1155 }
1156
1157 fn get_visibility(self, tcx: TyCtxt<'_>, id: DefIndex) -> Visibility<DefId> {
1158 self.root
1159 .tables
1160 .visibility
1161 .get((self, tcx), id)
1162 .unwrap_or_else(|| self.missing("visibility", id))
1163 .decode((self, tcx))
1164 .map_id(|index| self.local_def_id(index))
1165 }
1166
1167 fn get_safety(self, tcx: TyCtxt<'_>, id: DefIndex) -> Safety {
1168 self.root.tables.safety.get((self, tcx), id)
1169 }
1170
1171 fn get_default_field(self, tcx: TyCtxt<'_>, id: DefIndex) -> Option<DefId> {
1172 self.root.tables.default_fields.get((self, tcx), id).map(|d| d.decode((self, tcx)))
1173 }
1174
1175 fn get_expn_that_defined(self, tcx: TyCtxt<'_>, id: DefIndex) -> ExpnId {
1176 self.root
1177 .tables
1178 .expn_that_defined
1179 .get((self, tcx), id)
1180 .unwrap_or_else(|| self.missing("expn_that_defined", id))
1181 .decode((self, tcx))
1182 }
1183
1184 fn get_debugger_visualizers(self, tcx: TyCtxt<'_>) -> Vec<DebuggerVisualizerFile> {
1185 self.root.debugger_visualizers.decode((self, tcx)).collect::<Vec<_>>()
1186 }
1187
1188 fn get_lib_features(self, tcx: TyCtxt<'_>) -> LibFeatures {
1190 LibFeatures {
1191 stability: self
1192 .root
1193 .lib_features
1194 .decode((self, tcx))
1195 .map(|(sym, stab)| (sym, (stab, DUMMY_SP)))
1196 .collect(),
1197 }
1198 }
1199
1200 fn get_stability_implications<'tcx>(self, tcx: TyCtxt<'tcx>) -> &'tcx [(Symbol, Symbol)] {
1204 tcx.arena.alloc_from_iter(self.root.stability_implications.decode((self, tcx)))
1205 }
1206
1207 fn get_lang_items<'tcx>(self, tcx: TyCtxt<'tcx>) -> &'tcx [(DefId, LangItem)] {
1209 tcx.arena.alloc_from_iter(
1210 self.root
1211 .lang_items
1212 .decode((self, tcx))
1213 .map(move |(def_index, index)| (self.local_def_id(def_index), index)),
1214 )
1215 }
1216
1217 fn get_stripped_cfg_items<'tcx>(
1218 self,
1219 tcx: TyCtxt<'tcx>,
1220 cnum: CrateNum,
1221 ) -> &'tcx [StrippedCfgItem] {
1222 let item_names = self
1223 .root
1224 .stripped_cfg_items
1225 .decode((self, tcx))
1226 .map(|item| item.map_mod_id(|index| DefId { krate: cnum, index }));
1227 tcx.arena.alloc_from_iter(item_names)
1228 }
1229
1230 fn get_diagnostic_items(self, tcx: TyCtxt<'_>) -> DiagnosticItems {
1232 let mut id_to_name = DefIdMap::default();
1233 let name_to_id = self
1234 .root
1235 .diagnostic_items
1236 .decode((self, tcx))
1237 .map(|(name, def_index)| {
1238 let id = self.local_def_id(def_index);
1239 id_to_name.insert(id, name);
1240 (name, id)
1241 })
1242 .collect();
1243 DiagnosticItems { id_to_name, name_to_id }
1244 }
1245
1246 fn get_mod_child(self, tcx: TyCtxt<'_>, id: DefIndex) -> ModChild {
1247 let ident = self.item_ident(tcx, id);
1248 let res = Res::Def(self.def_kind(tcx, id), self.local_def_id(id));
1249 let vis = self.get_visibility(tcx, id);
1250
1251 ModChild { ident, res, vis, reexport_chain: Default::default() }
1252 }
1253
1254 fn get_module_children(self, tcx: TyCtxt<'_>, id: DefIndex) -> impl Iterator<Item = ModChild> {
1259 gen move {
1260 if let Some(data) = &self.root.proc_macro_data {
1261 if id == CRATE_DEF_INDEX {
1264 for child_index in data.macros.decode((self, tcx)) {
1265 yield self.get_mod_child(tcx, child_index);
1266 }
1267 }
1268 } else {
1269 let non_reexports =
1271 self.root.tables.module_children_non_reexports.get((self, tcx), id);
1272 for child_index in non_reexports.unwrap().decode((self, tcx)) {
1273 yield self.get_mod_child(tcx, child_index);
1274 }
1275
1276 let reexports = self.root.tables.module_children_reexports.get((self, tcx), id);
1277 if !reexports.is_default() {
1278 for reexport in reexports.decode((self, tcx)) {
1279 yield reexport;
1280 }
1281 }
1282 }
1283 }
1284 }
1285
1286 fn get_ambig_module_children(
1287 self,
1288 tcx: TyCtxt<'_>,
1289 id: DefIndex,
1290 ) -> impl Iterator<Item = AmbigModChild> {
1291 gen move {
1292 let children = self.root.tables.ambig_module_children.get((self, tcx), id);
1293 if !children.is_default() {
1294 for child in children.decode((self, tcx)) {
1295 yield child;
1296 }
1297 }
1298 }
1299 }
1300
1301 fn is_item_mir_available(self, tcx: TyCtxt<'_>, id: DefIndex) -> bool {
1302 self.root.tables.optimized_mir.get((self, tcx), id).is_some()
1303 }
1304
1305 fn get_fn_has_self_parameter(self, tcx: TyCtxt<'_>, id: DefIndex) -> bool {
1306 self.root
1307 .tables
1308 .fn_arg_idents
1309 .get((self, tcx), id)
1310 .expect("argument names not encoded for a function")
1311 .decode((self, tcx))
1312 .nth(0)
1313 .is_some_and(|ident| #[allow(non_exhaustive_omitted_patterns)] match ident {
Some(Ident { name: kw::SelfLower, .. }) => true,
_ => false,
}matches!(ident, Some(Ident { name: kw::SelfLower, .. })))
1314 }
1315
1316 fn get_associated_item_or_field_def_ids(
1317 self,
1318 tcx: TyCtxt<'_>,
1319 id: DefIndex,
1320 ) -> impl Iterator<Item = DefId> {
1321 self.root
1322 .tables
1323 .associated_item_or_field_def_ids
1324 .get((self, tcx), id)
1325 .unwrap_or_else(|| self.missing("associated_item_or_field_def_ids", id))
1326 .decode((self, tcx))
1327 .map(move |child_index| self.local_def_id(child_index))
1328 }
1329
1330 fn get_associated_item(self, tcx: TyCtxt<'_>, id: DefIndex) -> ty::AssocItem {
1331 let kind = match self.def_kind(tcx, id) {
1332 DefKind::AssocConst => ty::AssocKind::Const { name: self.item_name(id) },
1333 DefKind::AssocFn => ty::AssocKind::Fn {
1334 name: self.item_name(id),
1335 has_self: self.get_fn_has_self_parameter(tcx, id),
1336 },
1337 DefKind::AssocTy => {
1338 let data = if let Some(rpitit_info) =
1339 self.root.tables.opt_rpitit_info.get((self, tcx), id)
1340 {
1341 ty::AssocTypeData::Rpitit(rpitit_info.decode((self, tcx)))
1342 } else {
1343 ty::AssocTypeData::Normal(self.item_name(id))
1344 };
1345 ty::AssocKind::Type { data }
1346 }
1347 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("cannot get associated-item of `{0:?}`",
self.def_key(id)))bug!("cannot get associated-item of `{:?}`", self.def_key(id)),
1348 };
1349 let container =
1350 self.root.tables.assoc_container.get((self, tcx), id).unwrap().decode((self, tcx));
1351
1352 ty::AssocItem { kind, def_id: self.local_def_id(id), container }
1353 }
1354
1355 fn get_ctor(self, tcx: TyCtxt<'_>, node_id: DefIndex) -> Option<(CtorKind, DefId)> {
1356 match self.def_kind(tcx, node_id) {
1357 DefKind::Struct | DefKind::Variant => {
1358 let vdata = self
1359 .root
1360 .tables
1361 .variant_data
1362 .get((self, tcx), node_id)
1363 .unwrap()
1364 .decode((self, tcx));
1365 vdata.ctor.map(|(kind, index)| (kind, self.local_def_id(index)))
1366 }
1367 _ => None,
1368 }
1369 }
1370
1371 fn get_item_attrs(self, tcx: TyCtxt<'_>, id: DefIndex) -> impl Iterator<Item = hir::Attribute> {
1372 self.root
1373 .tables
1374 .attributes
1375 .get((self, tcx), id)
1376 .unwrap_or_else(|| {
1377 let def_key = self.def_key(id);
1381 match (&def_key.disambiguated_data.data, &DefPathData::Ctor) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(def_key.disambiguated_data.data, DefPathData::Ctor);
1382 let parent_id = def_key.parent.expect("no parent for a constructor");
1383 self.root
1384 .tables
1385 .attributes
1386 .get((self, tcx), parent_id)
1387 .expect("no encoded attributes for a structure or variant")
1388 })
1389 .decode((self, tcx))
1390 }
1391
1392 fn get_inherent_implementations_for_type<'tcx>(
1393 self,
1394 tcx: TyCtxt<'tcx>,
1395 id: DefIndex,
1396 ) -> &'tcx [DefId] {
1397 tcx.arena.alloc_from_iter(
1398 self.root
1399 .tables
1400 .inherent_impls
1401 .get((self, tcx), id)
1402 .decode((self, tcx))
1403 .map(|index| self.local_def_id(index)),
1404 )
1405 }
1406
1407 fn get_traits(self, tcx: TyCtxt<'_>) -> impl Iterator<Item = DefId> {
1409 self.root.traits.decode((self, tcx)).map(move |index| self.local_def_id(index))
1410 }
1411
1412 fn get_trait_impls(self, tcx: TyCtxt<'_>) -> impl Iterator<Item = DefId> {
1414 self.cdata.trait_impls.values().flat_map(move |impls| {
1415 impls.decode((self, tcx)).map(move |(impl_index, _)| self.local_def_id(impl_index))
1416 })
1417 }
1418
1419 fn get_incoherent_impls<'tcx>(self, tcx: TyCtxt<'tcx>, simp: SimplifiedType) -> &'tcx [DefId] {
1420 if let Some(impls) = self.cdata.incoherent_impls.get(&simp) {
1421 tcx.arena.alloc_from_iter(impls.decode((self, tcx)).map(|idx| self.local_def_id(idx)))
1422 } else {
1423 &[]
1424 }
1425 }
1426
1427 fn get_implementations_of_trait<'tcx>(
1428 self,
1429 tcx: TyCtxt<'tcx>,
1430 trait_def_id: DefId,
1431 ) -> &'tcx [(DefId, Option<SimplifiedType>)] {
1432 if self.trait_impls.is_empty() {
1433 return &[];
1434 }
1435
1436 let key = match self.reverse_translate_def_id(trait_def_id) {
1439 Some(def_id) => (def_id.krate.as_u32(), def_id.index),
1440 None => return &[],
1441 };
1442
1443 if let Some(impls) = self.trait_impls.get(&key) {
1444 tcx.arena.alloc_from_iter(
1445 impls
1446 .decode((self, tcx))
1447 .map(|(idx, simplified_self_ty)| (self.local_def_id(idx), simplified_self_ty)),
1448 )
1449 } else {
1450 &[]
1451 }
1452 }
1453
1454 fn get_native_libraries(self, tcx: TyCtxt<'_>) -> impl Iterator<Item = NativeLib> {
1455 self.root.native_libraries.decode((self, tcx))
1456 }
1457
1458 fn get_proc_macro_quoted_span(self, tcx: TyCtxt<'_>, index: usize) -> Span {
1459 self.root
1460 .tables
1461 .proc_macro_quoted_spans
1462 .get((self, tcx), index)
1463 .unwrap_or_else(|| {
::core::panicking::panic_fmt(format_args!("Missing proc macro quoted span: {0:?}",
index));
}panic!("Missing proc macro quoted span: {index:?}"))
1464 .decode((self, tcx))
1465 }
1466
1467 fn get_foreign_modules(self, tcx: TyCtxt<'_>) -> impl Iterator<Item = ForeignModule> {
1468 self.root.foreign_modules.decode((self, tcx))
1469 }
1470
1471 fn get_dylib_dependency_formats<'tcx>(
1472 self,
1473 tcx: TyCtxt<'tcx>,
1474 ) -> &'tcx [(CrateNum, LinkagePreference)] {
1475 tcx.arena.alloc_from_iter(
1476 self.root.dylib_dependency_formats.decode((self, tcx)).enumerate().flat_map(
1477 |(i, link)| {
1478 let cnum = CrateNum::new(i + 1); link.map(|link| (self.cnum_map[cnum], link))
1480 },
1481 ),
1482 )
1483 }
1484
1485 fn get_externally_implementable_items(
1486 self,
1487 tcx: TyCtxt<'_>,
1488 ) -> impl Iterator<Item = EiiMapEncodedKeyValue> {
1489 self.root.externally_implementable_items.decode((self, tcx))
1490 }
1491
1492 fn get_missing_lang_items<'tcx>(self, tcx: TyCtxt<'tcx>) -> &'tcx [LangItem] {
1493 tcx.arena.alloc_from_iter(self.root.lang_items_missing.decode((self, tcx)))
1494 }
1495
1496 fn get_exportable_items(self, tcx: TyCtxt<'_>) -> impl Iterator<Item = DefId> {
1497 self.root.exportable_items.decode((self, tcx)).map(move |index| self.local_def_id(index))
1498 }
1499
1500 fn get_stable_order_of_exportable_impls(
1501 self,
1502 tcx: TyCtxt<'_>,
1503 ) -> impl Iterator<Item = (DefId, usize)> {
1504 self.root
1505 .stable_order_of_exportable_impls
1506 .decode((self, tcx))
1507 .map(move |v| (self.local_def_id(v.0), v.1))
1508 }
1509
1510 fn exported_non_generic_symbols<'tcx>(
1511 self,
1512 tcx: TyCtxt<'tcx>,
1513 ) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
1514 tcx.arena.alloc_from_iter(self.root.exported_non_generic_symbols.decode((self, tcx)))
1515 }
1516
1517 fn exported_generic_symbols<'tcx>(
1518 self,
1519 tcx: TyCtxt<'tcx>,
1520 ) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
1521 tcx.arena.alloc_from_iter(self.root.exported_generic_symbols.decode((self, tcx)))
1522 }
1523
1524 fn get_macro(self, tcx: TyCtxt<'_>, id: DefIndex) -> ast::MacroDef {
1525 match self.def_kind(tcx, id) {
1526 DefKind::Macro(_) => {
1527 let macro_rules = self.root.tables.is_macro_rules.get((self, tcx), id);
1528 let body = self
1529 .root
1530 .tables
1531 .macro_definition
1532 .get((self, tcx), id)
1533 .unwrap()
1534 .decode((self, tcx));
1535 ast::MacroDef { macro_rules, body: Box::new(body), eii_declaration: None }
1536 }
1537 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
1538 }
1539 }
1540
1541 #[inline]
1542 fn def_key(self, index: DefIndex) -> DefKey {
1543 *self.def_key_cache.lock().entry(index).or_insert_with(|| {
1544 self.root.tables.def_keys.get(&self.blob, index).unwrap().decode(&self.blob)
1545 })
1546 }
1547
1548 fn def_path(self, id: DefIndex) -> DefPath {
1550 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/rmeta/decoder.rs:1550",
"rustc_metadata::rmeta::decoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/decoder.rs"),
::tracing_core::__macro_support::Option::Some(1550u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::decoder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("def_path(cnum={0:?}, id={1:?})",
self.cnum, id) as &dyn Value))])
});
} else { ; }
};debug!("def_path(cnum={:?}, id={:?})", self.cnum, id);
1551 DefPath::make(self.cnum, id, |parent| self.def_key(parent))
1552 }
1553
1554 #[inline]
1555 fn def_path_hash(self, index: DefIndex) -> DefPathHash {
1556 let fingerprint = Fingerprint::new(
1560 self.root.stable_crate_id.as_u64(),
1561 self.root.tables.def_path_hashes.get(&self.blob, index),
1562 );
1563 DefPathHash::new(self.root.stable_crate_id, fingerprint.split().1)
1564 }
1565
1566 #[inline]
1567 fn def_path_hash_to_def_index(self, hash: DefPathHash) -> Option<DefIndex> {
1568 self.def_path_hash_map.def_path_hash_to_def_index(&hash)
1569 }
1570
1571 fn expn_hash_to_expn_id(self, tcx: TyCtxt<'_>, index_guess: u32, hash: ExpnHash) -> ExpnId {
1572 let index_guess = ExpnIndex::from_u32(index_guess);
1573 let old_hash = self
1574 .root
1575 .expn_hashes
1576 .get((self, tcx), index_guess)
1577 .map(|lazy| lazy.decode((self, tcx)));
1578
1579 let index = if old_hash == Some(hash) {
1580 index_guess
1584 } else {
1585 let map = self.cdata.expn_hash_map.get_or_init(|| {
1589 let end_id = self.root.expn_hashes.size() as u32;
1590 let mut map =
1591 UnhashMap::with_capacity_and_hasher(end_id as usize, Default::default());
1592 for i in 0..end_id {
1593 let i = ExpnIndex::from_u32(i);
1594 if let Some(hash) = self.root.expn_hashes.get((self, tcx), i) {
1595 map.insert(hash.decode((self, tcx)), i);
1596 }
1597 }
1598 map
1599 });
1600 map[&hash]
1601 };
1602
1603 let data = self.root.expn_data.get((self, tcx), index).unwrap().decode((self, tcx));
1604 rustc_span::hygiene::register_expn_id(self.cnum, index, data, hash)
1605 }
1606
1607 fn imported_source_file(self, tcx: TyCtxt<'_>, source_file_index: u32) -> ImportedSourceFile {
1633 fn filter<'a>(
1634 tcx: TyCtxt<'_>,
1635 real_source_base_dir: &Option<PathBuf>,
1636 path: Option<&'a Path>,
1637 ) -> Option<&'a Path> {
1638 path.filter(|_| {
1639 real_source_base_dir.is_some()
1641 && tcx.sess.opts.unstable_opts.translate_remapped_path_to_local_path
1643 })
1644 .filter(|virtual_dir| {
1645 !tcx.sess.opts.remap_path_prefix.iter().any(|(_from, to)| to == virtual_dir)
1649 })
1650 }
1651
1652 let try_to_translate_virtual_to_real =
1653 |virtual_source_base_dir: Option<&str>,
1654 real_source_base_dir: &Option<PathBuf>,
1655 name: &mut rustc_span::FileName| {
1656 let virtual_source_base_dir = [
1657 filter(tcx, real_source_base_dir, virtual_source_base_dir.map(Path::new)),
1658 filter(
1659 tcx,
1660 real_source_base_dir,
1661 tcx.sess.opts.unstable_opts.simulate_remapped_rust_src_base.as_deref(),
1662 ),
1663 ];
1664
1665 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/rmeta/decoder.rs:1665",
"rustc_metadata::rmeta::decoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/decoder.rs"),
::tracing_core::__macro_support::Option::Some(1665u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::decoder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("try_to_translate_virtual_to_real(name={0:?}): virtual_source_base_dir={1:?}, real_source_base_dir={2:?}",
name, virtual_source_base_dir, real_source_base_dir) as
&dyn Value))])
});
} else { ; }
};debug!(
1666 "try_to_translate_virtual_to_real(name={:?}): \
1667 virtual_source_base_dir={:?}, real_source_base_dir={:?}",
1668 name, virtual_source_base_dir, real_source_base_dir,
1669 );
1670
1671 for virtual_dir in virtual_source_base_dir.iter().flatten() {
1672 if let Some(real_dir) = &real_source_base_dir
1673 && let rustc_span::FileName::Real(old_name) = name
1674 && let virtual_path = old_name.path(RemapPathScopeComponents::MACRO)
1675 && let Ok(rest) = virtual_path.strip_prefix(virtual_dir)
1676 {
1677 let new_path = real_dir.join(rest);
1678
1679 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/rmeta/decoder.rs:1679",
"rustc_metadata::rmeta::decoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/decoder.rs"),
::tracing_core::__macro_support::Option::Some(1679u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::decoder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("try_to_translate_virtual_to_real: `{0}` -> `{1}`",
virtual_path.display(), new_path.display()) as
&dyn Value))])
});
} else { ; }
};debug!(
1680 "try_to_translate_virtual_to_real: `{}` -> `{}`",
1681 virtual_path.display(),
1682 new_path.display(),
1683 );
1684
1685 *name = rustc_span::FileName::Real(
1691 tcx.sess
1692 .source_map()
1693 .path_mapping()
1694 .to_real_filename(&rustc_span::RealFileName::empty(), new_path),
1695 );
1696 }
1697 }
1698 };
1699
1700 let try_to_translate_real_to_virtual =
1701 |virtual_source_base_dir: Option<&str>,
1702 real_source_base_dir: &Option<PathBuf>,
1703 subdir: &str,
1704 name: &mut rustc_span::FileName| {
1705 if let Some(virtual_dir) =
1706 &tcx.sess.opts.unstable_opts.simulate_remapped_rust_src_base
1707 && let Some(real_dir) = real_source_base_dir
1708 && let rustc_span::FileName::Real(old_name) = name
1709 {
1710 let (_working_dir, embeddable_path) =
1711 old_name.embeddable_name(RemapPathScopeComponents::MACRO);
1712 let relative_path = embeddable_path.strip_prefix(real_dir).ok().or_else(|| {
1713 virtual_source_base_dir
1714 .and_then(|virtual_dir| embeddable_path.strip_prefix(virtual_dir).ok())
1715 });
1716 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/rmeta/decoder.rs:1716",
"rustc_metadata::rmeta::decoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/decoder.rs"),
::tracing_core::__macro_support::Option::Some(1716u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::decoder"),
::tracing_core::field::FieldSet::new(&["message",
"relative_path", "virtual_dir", "subdir"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("simulate_remapped_rust_src_base")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&relative_path)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&virtual_dir)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&subdir) as
&dyn Value))])
});
} else { ; }
};debug!(
1717 ?relative_path,
1718 ?virtual_dir,
1719 ?subdir,
1720 "simulate_remapped_rust_src_base"
1721 );
1722 if let Some(rest) = relative_path.and_then(|p| p.strip_prefix(subdir).ok()) {
1723 *name =
1724 rustc_span::FileName::Real(rustc_span::RealFileName::from_virtual_path(
1725 &virtual_dir.join(subdir).join(rest),
1726 ))
1727 }
1728 }
1729 };
1730
1731 let mut import_info = self.cdata.source_map_import_info.lock();
1732 for _ in import_info.len()..=(source_file_index as usize) {
1733 import_info.push(None);
1734 }
1735 import_info[source_file_index as usize]
1736 .get_or_insert_with(|| {
1737 let source_file_to_import = self
1738 .root
1739 .source_map
1740 .get((self, tcx), source_file_index)
1741 .expect("missing source file")
1742 .decode((self, tcx));
1743
1744 let original_end_pos = source_file_to_import.end_position();
1747 let rustc_span::SourceFile {
1748 mut name,
1749 src_hash,
1750 checksum_hash,
1751 start_pos: original_start_pos,
1752 normalized_source_len,
1753 unnormalized_source_len,
1754 lines,
1755 multibyte_chars,
1756 normalized_pos,
1757 stable_id,
1758 ..
1759 } = source_file_to_import;
1760
1761 try_to_translate_real_to_virtual(
1769 ::core::option::Option::Some("/rustc/47611e16044c68ef27bac31c35fda2ba1dc20b73")option_env!("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR"),
1770 &tcx.sess.opts.real_rust_source_base_dir,
1771 "library",
1772 &mut name,
1773 );
1774
1775 try_to_translate_real_to_virtual(
1780 ::core::option::Option::Some("/rustc-dev/47611e16044c68ef27bac31c35fda2ba1dc20b73")option_env!("CFG_VIRTUAL_RUSTC_DEV_SOURCE_BASE_DIR"),
1781 &tcx.sess.opts.real_rustc_dev_source_base_dir,
1782 "compiler",
1783 &mut name,
1784 );
1785
1786 try_to_translate_virtual_to_real(
1792 ::core::option::Option::Some("/rustc/47611e16044c68ef27bac31c35fda2ba1dc20b73")option_env!("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR"),
1793 &tcx.sess.opts.real_rust_source_base_dir,
1794 &mut name,
1795 );
1796
1797 try_to_translate_virtual_to_real(
1803 ::core::option::Option::Some("/rustc-dev/47611e16044c68ef27bac31c35fda2ba1dc20b73")option_env!("CFG_VIRTUAL_RUSTC_DEV_SOURCE_BASE_DIR"),
1804 &tcx.sess.opts.real_rustc_dev_source_base_dir,
1805 &mut name,
1806 );
1807
1808 let local_version = tcx.sess.source_map().new_imported_source_file(
1809 name,
1810 src_hash,
1811 checksum_hash,
1812 stable_id,
1813 normalized_source_len.to_u32(),
1814 unnormalized_source_len,
1815 self.cnum,
1816 lines,
1817 multibyte_chars,
1818 normalized_pos,
1819 source_file_index,
1820 );
1821 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/rmeta/decoder.rs:1821",
"rustc_metadata::rmeta::decoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/decoder.rs"),
::tracing_core::__macro_support::Option::Some(1821u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::decoder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("CrateMetaData::imported_source_files alloc source_file {0:?} original (start_pos {1:?} source_len {2:?}) translated (start_pos {3:?} source_len {4:?})",
local_version.name, original_start_pos,
normalized_source_len, local_version.start_pos,
local_version.normalized_source_len) as &dyn Value))])
});
} else { ; }
};debug!(
1822 "CrateMetaData::imported_source_files alloc \
1823 source_file {:?} original (start_pos {:?} source_len {:?}) \
1824 translated (start_pos {:?} source_len {:?})",
1825 local_version.name,
1826 original_start_pos,
1827 normalized_source_len,
1828 local_version.start_pos,
1829 local_version.normalized_source_len
1830 );
1831
1832 ImportedSourceFile {
1833 original_start_pos,
1834 original_end_pos,
1835 translated_source_file: local_version,
1836 }
1837 })
1838 .clone()
1839 }
1840
1841 fn get_attr_flags(self, tcx: TyCtxt<'_>, index: DefIndex) -> AttrFlags {
1842 self.root.tables.attr_flags.get((self, tcx), index)
1843 }
1844
1845 fn get_intrinsic(self, tcx: TyCtxt<'_>, index: DefIndex) -> Option<ty::IntrinsicDef> {
1846 self.root.tables.intrinsic.get((self, tcx), index).map(|d| d.decode((self, tcx)))
1847 }
1848
1849 fn get_doc_link_resolutions(self, tcx: TyCtxt<'_>, index: DefIndex) -> DocLinkResMap {
1850 self.root
1851 .tables
1852 .doc_link_resolutions
1853 .get((self, tcx), index)
1854 .expect("no resolutions for a doc link")
1855 .decode((self, tcx))
1856 }
1857
1858 fn get_doc_link_traits_in_scope(
1859 self,
1860 tcx: TyCtxt<'_>,
1861 index: DefIndex,
1862 ) -> impl Iterator<Item = DefId> {
1863 self.root
1864 .tables
1865 .doc_link_traits_in_scope
1866 .get((self, tcx), index)
1867 .expect("no traits in scope for a doc link")
1868 .decode((self, tcx))
1869 }
1870}
1871
1872impl CrateMetadata {
1873 pub(crate) fn new(
1874 tcx: TyCtxt<'_>,
1875 cstore: &CStore,
1876 blob: MetadataBlob,
1877 root: CrateRoot,
1878 raw_proc_macros: Option<&'static [ProcMacro]>,
1879 cnum: CrateNum,
1880 cnum_map: CrateNumMap,
1881 dep_kind: CrateDepKind,
1882 source: CrateSource,
1883 private_dep: bool,
1884 host_hash: Option<Svh>,
1885 ) -> CrateMetadata {
1886 let trait_impls = root
1887 .impls
1888 .decode(&blob)
1889 .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
1890 .collect();
1891 let alloc_decoding_state =
1892 AllocDecodingState::new(root.interpret_alloc_index.decode(&blob).collect());
1893
1894 let def_path_hash_map = root.def_path_hash_map.decode(&blob);
1897
1898 let mut cdata = CrateMetadata {
1899 blob,
1900 root,
1901 trait_impls,
1902 incoherent_impls: Default::default(),
1903 raw_proc_macros,
1904 source_map_import_info: Lock::new(Vec::new()),
1905 def_path_hash_map,
1906 expn_hash_map: Default::default(),
1907 alloc_decoding_state,
1908 cnum,
1909 cnum_map,
1910 dep_kind,
1911 source: Arc::new(source),
1912 private_dep,
1913 host_hash,
1914 used: false,
1915 extern_crate: None,
1916 hygiene_context: Default::default(),
1917 def_key_cache: Default::default(),
1918 };
1919
1920 let cref = CrateMetadataRef { cdata: &cdata, cstore };
1922 cdata.incoherent_impls = cdata
1923 .root
1924 .incoherent_impls
1925 .decode((cref, tcx))
1926 .map(|incoherent_impls| {
1927 (incoherent_impls.self_ty.decode((cref, tcx)), incoherent_impls.impls)
1928 })
1929 .collect();
1930
1931 cdata
1932 }
1933
1934 pub(crate) fn dependencies(&self) -> impl Iterator<Item = CrateNum> {
1935 self.cnum_map.iter().copied()
1936 }
1937
1938 pub(crate) fn target_modifiers(&self) -> TargetModifiers {
1939 self.root.decode_target_modifiers(&self.blob).collect()
1940 }
1941
1942 pub(crate) fn update_extern_crate_diagnostics(
1944 &mut self,
1945 new_extern_crate: ExternCrate,
1946 ) -> bool {
1947 let update =
1948 self.extern_crate.as_ref().is_none_or(|old| old.rank() < new_extern_crate.rank());
1949 if update {
1950 self.extern_crate = Some(new_extern_crate);
1951 }
1952 update
1953 }
1954
1955 pub(crate) fn source(&self) -> &CrateSource {
1956 &*self.source
1957 }
1958
1959 pub(crate) fn dep_kind(&self) -> CrateDepKind {
1960 self.dep_kind
1961 }
1962
1963 pub(crate) fn set_dep_kind(&mut self, dep_kind: CrateDepKind) {
1964 self.dep_kind = dep_kind;
1965 }
1966
1967 pub(crate) fn update_and_private_dep(&mut self, private_dep: bool) {
1968 self.private_dep &= private_dep;
1969 }
1970
1971 pub(crate) fn used(&self) -> bool {
1972 self.used
1973 }
1974
1975 pub(crate) fn required_panic_strategy(&self) -> Option<PanicStrategy> {
1976 self.root.required_panic_strategy
1977 }
1978
1979 pub(crate) fn needs_panic_runtime(&self) -> bool {
1980 self.root.needs_panic_runtime
1981 }
1982
1983 pub(crate) fn is_private_dep(&self) -> bool {
1984 self.private_dep
1985 }
1986
1987 pub(crate) fn is_panic_runtime(&self) -> bool {
1988 self.root.panic_runtime
1989 }
1990
1991 pub(crate) fn is_profiler_runtime(&self) -> bool {
1992 self.root.profiler_runtime
1993 }
1994
1995 pub(crate) fn is_compiler_builtins(&self) -> bool {
1996 self.root.compiler_builtins
1997 }
1998
1999 pub(crate) fn needs_allocator(&self) -> bool {
2000 self.root.needs_allocator
2001 }
2002
2003 pub(crate) fn has_global_allocator(&self) -> bool {
2004 self.root.has_global_allocator
2005 }
2006
2007 pub(crate) fn has_alloc_error_handler(&self) -> bool {
2008 self.root.has_alloc_error_handler
2009 }
2010
2011 pub(crate) fn has_default_lib_allocator(&self) -> bool {
2012 self.root.has_default_lib_allocator
2013 }
2014
2015 pub(crate) fn is_proc_macro_crate(&self) -> bool {
2016 self.root.is_proc_macro_crate()
2017 }
2018
2019 pub(crate) fn proc_macros_for_crate(
2020 &self,
2021 tcx: TyCtxt<'_>,
2022 krate: CrateNum,
2023 cstore: &CStore,
2024 ) -> impl Iterator<Item = DefId> {
2025 gen move {
2026 for def_id in self.root.proc_macro_data.as_ref().into_iter().flat_map(move |data| {
2027 data.macros
2028 .decode((CrateMetadataRef { cdata: self, cstore }, tcx))
2029 .map(move |index| DefId { index, krate })
2030 }) {
2031 yield def_id;
2032 }
2033 }
2034 }
2035
2036 pub(crate) fn name(&self) -> Symbol {
2037 self.root.header.name
2038 }
2039
2040 pub(crate) fn hash(&self) -> Svh {
2041 self.root.header.hash
2042 }
2043
2044 pub(crate) fn has_async_drops(&self) -> bool {
2045 self.root.tables.adt_async_destructor.len > 0
2046 }
2047
2048 fn num_def_ids(&self) -> usize {
2049 self.root.tables.def_keys.size()
2050 }
2051
2052 fn local_def_id(&self, index: DefIndex) -> DefId {
2053 DefId { krate: self.cnum, index }
2054 }
2055
2056 fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
2059 for (local, &global) in self.cnum_map.iter_enumerated() {
2060 if global == did.krate {
2061 return Some(DefId { krate: local, index: did.index });
2062 }
2063 }
2064
2065 None
2066 }
2067}