1use std::borrow::Borrow;
2use std::cell::RefCell;
3use std::collections::hash_map::Entry;
4use std::fs::File;
5use std::io::{Read, Seek, SeekFrom, Write};
6use std::ops::Deref;
7use std::path::{Path, PathBuf};
8use std::rc::Rc;
9use std::sync::{Arc, Mutex};
10
11use rustc_attr_ir::{AttributeKind, EncodeCrossCrate, find_attr};
12use rustc_data_structures::fingerprint::Fingerprint;
13use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
14use rustc_data_structures::memmap::{Mmap, MmapMut};
15use rustc_data_structures::owned_slice::slice_owned;
16use rustc_data_structures::stable_hash::{StableHash, StableHasher};
17use rustc_data_structures::sync::{par_for_each_in, par_join};
18use rustc_data_structures::temp_dir::MaybeTempDir;
19use rustc_data_structures::thousands::usize_with_underscores;
20use rustc_hir as hir;
21use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE, LocalDefId, LocalDefIdSet};
22use rustc_hir::definitions::DefPathData;
23use rustc_hir_pretty::id_to_string;
24use rustc_index::IndexVec;
25use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
26use rustc_middle::hir::map::compute_hir_hash;
27use rustc_middle::middle::dependency_format::Linkage;
28use rustc_middle::mir::interpret;
29use rustc_middle::query::Providers;
30use rustc_middle::traits::specialization_graph;
31use rustc_middle::ty::AssocContainer;
32use rustc_middle::ty::codec::TyEncoder;
33use rustc_middle::ty::fast_reject::{self, TreatParams};
34use rustc_serialize::opaque::FileEncoder;
35use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
36use rustc_session::config::mitigation_coverage::DeniedPartialMitigation;
37use rustc_session::config::{OptLevel, OutputType, TargetModifier};
38use rustc_span::def_id::CRATE_MOD_ID;
39use rustc_span::hygiene::{
40 HygieneEncodeContext, HygieneRemapper, HygieneRemappingResults, LocalExpnIdRemapper,
41 SyntaxContextRemapper,
42};
43use rustc_span::{
44 ByteSymbol, ExternalSource, FileName, LocalExpnId, SourceFile, SpanData, SpanEncoder,
45 StableSourceFileId, Symbol, SyntaxContext, bug, span_bug,
46};
47use rustc_structures::CrateType;
48use tracing::{debug, instrument, trace};
49use twox_hash::XxHash3_128;
50
51use crate::diagnostics::{FailCreateFileEncoder, FailWriteFile};
52use crate::eii::EiiMapEncodedKeyValue;
53use crate::rmeta::remapped_def_id::RemappedRawDefId;
54use crate::rmeta::*;
55
56pub(super) struct EncodeContext<'a, 'tcx> {
57 opaque: FileEncoder<'a>,
58 metadata_hasher: Arc<Mutex<XxHash3_128>>,
59 tcx: TyCtxt<'tcx>,
60 feat: &'tcx rustc_feature::Features,
61 pub(super) tables: TableBuilders,
62
63 lazy_state: LazyState,
64 span_shorthands: FxHashMap<Span, usize>,
65 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
66 predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
67
68 interpret_allocs: FxIndexSet<interpret::AllocId>,
69
70 source_file_cache: (Arc<SourceFile>, usize),
74 required_source_files: Option<FxIndexSet<usize>>,
81 is_proc_macro: bool,
82 hygiene_ctxt: Rc<RefCell<HygieneEncodeContext>>,
83 symbol_index_table: FxHashMap<u32, usize>,
85 pub(super) local_defs_remapping: LocalDefsRemapping,
86 syntax_context_remapping: HygieneRemappingResults<SyntaxContext, RemappedSyntaxContext>,
87 local_expn_id_remapping: HygieneRemappingResults<LocalExpnId, RemappedLocalExpnIndex>,
88}
89
90macro_rules! empty_proc_macro {
94 ($self:ident) => {
95 if $self.is_proc_macro {
96 return LazyArray::default();
97 }
98 };
99}
100
101macro_rules! encoder_methods {
102 ($($name:ident($ty:ty);)*) => {
103 $(fn $name(&mut self, value: $ty) {
104 self.opaque.$name(value)
105 })*
106 }
107}
108
109impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
110 const DETERMINISTIC_HASH_MAP_ENCODE: bool = true;
111
112 fn emit_usize(&mut self, value: usize) { self.opaque.emit_usize(value) }
fn emit_u128(&mut self, value: u128) { self.opaque.emit_u128(value) }
fn emit_u64(&mut self, value: u64) { self.opaque.emit_u64(value) }
fn emit_u32(&mut self, value: u32) { self.opaque.emit_u32(value) }
fn emit_u16(&mut self, value: u16) { self.opaque.emit_u16(value) }
fn emit_u8(&mut self, value: u8) { self.opaque.emit_u8(value) }
fn emit_isize(&mut self, value: isize) { self.opaque.emit_isize(value) }
fn emit_i128(&mut self, value: i128) { self.opaque.emit_i128(value) }
fn emit_i64(&mut self, value: i64) { self.opaque.emit_i64(value) }
fn emit_i32(&mut self, value: i32) { self.opaque.emit_i32(value) }
fn emit_i16(&mut self, value: i16) { self.opaque.emit_i16(value) }
fn emit_raw_bytes(&mut self, value: &[u8]) {
self.opaque.emit_raw_bytes(value)
}encoder_methods! {
113 emit_usize(usize);
114 emit_u128(u128);
115 emit_u64(u64);
116 emit_u32(u32);
117 emit_u16(u16);
118 emit_u8(u8);
119
120 emit_isize(isize);
121 emit_i128(i128);
122 emit_i64(i64);
123 emit_i32(i32);
124 emit_i16(i16);
125
126 emit_raw_bytes(&[u8]);
127 }
128}
129
130impl<'a, 'tcx, T> Encodable<EncodeContext<'a, 'tcx>> for LazyValue<T> {
131 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
132 e.emit_lazy_distance(self.position);
133 }
134}
135
136impl<'a, 'tcx, T> Encodable<EncodeContext<'a, 'tcx>> for LazyArray<T> {
137 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
138 e.emit_usize(self.num_elems);
139 if self.num_elems > 0 {
140 e.emit_lazy_distance(self.position)
141 }
142 }
143}
144
145impl<'a, 'tcx, Ie, Id, T> Encodable<EncodeContext<'a, 'tcx>> for LazyTable<Ie, Id, T> {
146 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
147 e.emit_usize(self.width_and_sparse);
148 e.emit_usize(self.len);
149 e.emit_lazy_distance(self.position);
150 }
151}
152
153impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnIndex {
154 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
155 s.emit_u32(self.as_u32());
156 }
157}
158
159impl<'a, 'tcx> SpanEncoder for EncodeContext<'a, 'tcx> {
160 fn def_path_hasher(&self) -> impl Fn(DefId) -> DefPathHash {
161 self.tcx.prelocked_def_path_hasher()
162 }
163
164 fn encode_crate_num(&mut self, crate_num: CrateNum) {
165 if crate_num != LOCAL_CRATE && self.is_proc_macro {
166 {
::core::panicking::panic_fmt(format_args!("Attempted to encode non-local CrateNum {0:?} for proc-macro crate",
crate_num));
};panic!("Attempted to encode non-local CrateNum {crate_num:?} for proc-macro crate");
167 }
168 self.emit_u32(crate_num.as_u32());
169 }
170
171 fn encode_def_index(&mut self, _: DefIndex) {
176 {
::core::panicking::panic_fmt(format_args!("use LocalDefId or DefId or encode DefIndex manually"));
}panic!("use LocalDefId or DefId or encode DefIndex manually")
177 }
178
179 fn encode_def_id(&mut self, def_id: DefId) {
180 let def_id = self.local_defs_remapping.map_def_id(def_id);
181
182 def_id.krate.encode(self);
183 self.emit_u32(def_id.index.as_u32());
184 }
185
186 fn encode_syntax_context(&mut self, syntax_context: SyntaxContext) {
187 self.hygiene_ctxt.borrow_mut().enqueue_syntax_context_for_encoding(syntax_context);
188 self.emit_u32(self.syntax_context_remapping.map_id(syntax_context).as_u32());
189 }
190
191 fn encode_expn_id(&mut self, expn_id: ExpnId) {
192 if expn_id.krate == LOCAL_CRATE {
193 self.hygiene_ctxt.borrow_mut().schedule_expn_data_for_encoding(expn_id);
198 }
199 expn_id.krate.encode(self);
200
201 let raw_expn_index = match expn_id.as_local() {
202 Some(local_expn) => self.local_expn_id_remapping.map_id(local_expn).as_u32(),
203 None => expn_id.local_id.as_u32(),
204 };
205
206 raw_expn_index.encode(self);
207 }
208
209 fn encode_span(&mut self, span: Span) {
210 match self.span_shorthands.entry(span) {
211 Entry::Occupied(o) => {
212 let last_location = *o.get();
215 let offset = self.opaque.position() - last_location;
218 if offset < last_location {
219 let needed = bytes_needed(offset);
220 SpanTag::indirect(true, needed as u8).encode(self);
221 self.opaque.write_with(|dest| {
222 *dest = offset.to_le_bytes();
223 needed
224 });
225 } else {
226 let needed = bytes_needed(last_location);
227 SpanTag::indirect(false, needed as u8).encode(self);
228 self.opaque.write_with(|dest| {
229 *dest = last_location.to_le_bytes();
230 needed
231 });
232 }
233 }
234 Entry::Vacant(v) => {
235 let position = self.opaque.position();
236 v.insert(position);
237 span.data().encode(self);
239 }
240 }
241 }
242
243 fn encode_symbol(&mut self, sym: Symbol) {
244 self.encode_symbol_or_byte_symbol(sym.as_u32(), |this| this.emit_str(sym.as_str()));
245 }
246
247 fn encode_byte_symbol(&mut self, byte_sym: ByteSymbol) {
248 self.encode_symbol_or_byte_symbol(byte_sym.as_u32(), |this| {
249 this.emit_byte_str(byte_sym.as_byte_str())
250 });
251 }
252
253 fn encode_local_def_id(&mut self, def_id: LocalDefId) {
259 self.emit_u32(self.local_defs_remapping.map_local_def_id(def_id).index.as_u32());
260 }
261
262 fn encode_def_key(
266 &mut self,
267 parent: Option<DefIndex>,
268 disambiguated_data: impl Encodable<Self>,
269 ) {
270 parent.as_ref().map(|p| LocalDefId { local_def_index: *p }).encode(self);
271 disambiguated_data.encode(self);
272 }
273}
274
275fn bytes_needed(n: usize) -> usize {
276 (usize::BITS - n.leading_zeros()).div_ceil(u8::BITS) as usize
277}
278
279impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for SpanData {
280 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
281 let ctxt = if s.is_proc_macro { SyntaxContext::root() } else { self.ctxt };
313
314 if self.is_dummy() {
315 let tag = SpanTag::new(SpanKind::Partial, ctxt, 0);
316 tag.encode(s);
317 if tag.context().is_none() {
318 ctxt.encode(s);
319 }
320 return;
321 }
322
323 if true {
if !(self.lo <= self.hi) {
::core::panicking::panic("assertion failed: self.lo <= self.hi")
};
};debug_assert!(self.lo <= self.hi);
325
326 if !s.source_file_cache.0.contains(self.lo) {
327 let source_map = s.tcx.sess.source_map();
328 let source_file_index = source_map.lookup_source_file_idx(self.lo);
329 s.source_file_cache =
330 (Arc::clone(&source_map.files()[source_file_index]), source_file_index);
331 }
332 let (ref source_file, source_file_index) = s.source_file_cache;
333 if true {
if !source_file.contains(self.lo) {
::core::panicking::panic("assertion failed: source_file.contains(self.lo)")
};
};debug_assert!(source_file.contains(self.lo));
334
335 if !source_file.contains(self.hi) {
336 let tag = SpanTag::new(SpanKind::Partial, ctxt, 0);
339 tag.encode(s);
340 if tag.context().is_none() {
341 ctxt.encode(s);
342 }
343 return;
344 }
345
346 let (kind, metadata_index) = if source_file.is_imported() && !s.is_proc_macro {
363 let metadata_index = {
373 match &*source_file.external_src.read() {
375 ExternalSource::Foreign { metadata_index, .. } => *metadata_index,
376 src => {
::core::panicking::panic_fmt(format_args!("Unexpected external source {0:?}",
src));
}panic!("Unexpected external source {src:?}"),
377 }
378 };
379
380 (SpanKind::Foreign, metadata_index)
381 } else {
382 let source_files =
384 s.required_source_files.as_mut().expect("Already encoded SourceMap!");
385 let (metadata_index, _) = source_files.insert_full(source_file_index);
386 let metadata_index: u32 =
387 metadata_index.try_into().expect("cannot export more than U32_MAX files");
388
389 (SpanKind::Local, metadata_index)
390 };
391
392 let lo = self.lo - source_file.start_pos;
395
396 let len = self.hi - self.lo;
399
400 let tag = SpanTag::new(kind, ctxt, len.0 as usize);
401 tag.encode(s);
402 if tag.context().is_none() {
403 ctxt.encode(s);
404 }
405 lo.encode(s);
406 if tag.length().is_none() {
407 len.encode(s);
408 }
409
410 metadata_index.encode(s);
412
413 if kind == SpanKind::Foreign {
414 let cnum = s.source_file_cache.0.cnum;
417 cnum.encode(s);
418 }
419 }
420}
421
422impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for [u8] {
423 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
424 Encoder::emit_usize(e, self.len());
425 e.emit_raw_bytes(self);
426 }
427}
428
429impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> {
430 const CLEAR_CROSS_CRATE: bool = true;
431
432 fn position(&self) -> usize {
433 self.opaque.position()
434 }
435
436 fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
437 &mut self.type_shorthands
438 }
439
440 fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
441 &mut self.predicate_shorthands
442 }
443
444 fn encode_alloc_id(&mut self, alloc_id: &rustc_middle::mir::interpret::AllocId) {
445 let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
446
447 index.encode(self);
448 }
449}
450
451impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
452 fn emit_lazy_distance(&mut self, position: NonZero<usize>) {
453 let pos = position.get();
454 let distance = match self.lazy_state {
455 LazyState::NoNode => ::rustc_span::macros::bug_impl(None,
format_args!("emit_lazy_distance: outside of a metadata node"),
Location::caller())bug!("emit_lazy_distance: outside of a metadata node"),
456 LazyState::NodeStart(start) => {
457 let start = start.get();
458 if !(pos <= start) {
::core::panicking::panic("assertion failed: pos <= start")
};assert!(pos <= start);
459 start - pos
460 }
461 LazyState::Previous(last_pos) => {
462 if !(last_pos <= position) {
{
::core::panicking::panic_fmt(format_args!("make sure that the calls to `lazy*` are in the same order as the metadata fields"));
}
};assert!(
463 last_pos <= position,
464 "make sure that the calls to `lazy*` \
465 are in the same order as the metadata fields",
466 );
467 position.get() - last_pos.get()
468 }
469 };
470 self.lazy_state = LazyState::Previous(NonZero::new(pos).unwrap());
471 self.emit_usize(distance);
472 }
473
474 pub(super) fn lazy<T: ParameterizedOverTcx, B: Borrow<T::Value<'tcx>>>(
475 &mut self,
476 value: B,
477 ) -> LazyValue<T>
478 where
479 T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
480 {
481 let pos = NonZero::new(self.position()).unwrap();
482
483 {
match (&self.lazy_state, &LazyState::NoNode) {
(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!(self.lazy_state, LazyState::NoNode);
484 self.lazy_state = LazyState::NodeStart(pos);
485 value.borrow().encode(self);
486 self.lazy_state = LazyState::NoNode;
487
488 if !(pos.get() <= self.position()) {
::core::panicking::panic("assertion failed: pos.get() <= self.position()")
};assert!(pos.get() <= self.position());
489
490 LazyValue::from_position(pos)
491 }
492
493 pub(super) fn lazy_array<
494 T: ParameterizedOverTcx,
495 I: IntoIterator<Item = B>,
496 B: Borrow<T::Value<'tcx>>,
497 >(
498 &mut self,
499 values: I,
500 ) -> LazyArray<T>
501 where
502 T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
503 {
504 let pos = NonZero::new(self.position()).unwrap();
505
506 {
match (&self.lazy_state, &LazyState::NoNode) {
(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!(self.lazy_state, LazyState::NoNode);
507 self.lazy_state = LazyState::NodeStart(pos);
508 let len = values.into_iter().map(|value| value.borrow().encode(self)).count();
509 self.lazy_state = LazyState::NoNode;
510
511 if !(pos.get() <= self.position()) {
::core::panicking::panic("assertion failed: pos.get() <= self.position()")
};assert!(pos.get() <= self.position());
512
513 LazyArray::from_position_and_num_elems(pos, len)
514 }
515
516 fn encode_symbol_or_byte_symbol(
517 &mut self,
518 index: u32,
519 emit_str_or_byte_str: impl Fn(&mut Self),
520 ) {
521 if Symbol::is_predefined(index) {
523 self.opaque.emit_u8(SYMBOL_PREDEFINED);
524 self.opaque.emit_u32(index);
525 } else {
526 match self.symbol_index_table.entry(index) {
528 Entry::Vacant(o) => {
529 self.opaque.emit_u8(SYMBOL_STR);
530 let pos = self.opaque.position();
531 o.insert(pos);
532 emit_str_or_byte_str(self);
533 }
534 Entry::Occupied(o) => {
535 let x = *o.get();
536 self.emit_u8(SYMBOL_OFFSET);
537 self.emit_usize(x);
538 }
539 }
540 }
541 }
542
543 fn encode_def_path_table(&mut self) {
544 let defs = self.tcx.definitions();
545 if self.is_proc_macro {
546 for def_id in std::iter::once(CRATE_DEF_ID)
547 .chain(self.tcx.resolutions(()).proc_macros.iter().copied())
548 {
549 let def_key = defs.def_key(def_id);
550 let def_path_hash = defs.def_path_hash(def_id);
551
552 self.table_writer().def_keys(def_id, def_key);
553 self.table_writer().def_path_hashes(def_id, def_path_hash.local_hash().as_u64());
554 }
555 } else {
556 for def_id in self.local_defs_remapping.iter_sorted_local_ids() {
557 let def_key = defs.def_key(def_id);
558 let hash = defs.def_path_hash(def_id).local_hash().as_u64();
559
560 self.table_writer().def_keys(def_id, def_key);
561 self.table_writer().def_path_hashes(def_id, hash);
562 }
563 }
564 }
565
566 fn encode_def_path_hash_map(&mut self) -> LazyValue<DefPathHashMapRef<'static>> {
567 self.lazy(DefPathHashMapRef::BorrowedFromTcx(self.tcx.def_path_hash_to_def_index_map()))
568 }
569
570 fn encode_source_map(
571 &mut self,
572 ) -> LazyTable<u32, u32, Option<LazyValue<rustc_span::SourceFile>>> {
573 let source_map = self.tcx.sess.source_map();
574 let all_source_files = source_map.files();
575
576 let required_source_files = self.required_source_files.take().unwrap();
580
581 let mut adapted = TableBuilder::default();
582
583 let local_crate_stable_id = self.tcx.stable_crate_id(LOCAL_CRATE);
584
585 for (on_disk_index, &source_file_index) in required_source_files.iter().enumerate() {
590 let source_file = &all_source_files[source_file_index];
591 if !(!source_file.is_imported() || self.is_proc_macro) {
::core::panicking::panic("assertion failed: !source_file.is_imported() || self.is_proc_macro")
};assert!(!source_file.is_imported() || self.is_proc_macro);
593
594 let mut adapted_source_file = (**source_file).clone();
602
603 match source_file.name {
604 FileName::Real(ref original_file_name) => {
605 let mut adapted_file_name = original_file_name.clone();
606 adapted_file_name.update_for_crate_metadata();
607 adapted_source_file.name = FileName::Real(adapted_file_name);
608 }
609 _ => {
610 }
612 };
613
614 if self.is_proc_macro {
621 adapted_source_file.cnum = LOCAL_CRATE;
622 }
623
624 adapted_source_file.stable_id = StableSourceFileId::from_filename_for_export(
628 &adapted_source_file.name,
629 local_crate_stable_id,
630 );
631
632 let on_disk_index: u32 =
633 on_disk_index.try_into().expect("cannot export more than U32_MAX files");
634 adapted.set_some(on_disk_index, self.lazy(adapted_source_file));
635 }
636
637 adapted.encode(&mut self.opaque)
638 }
639
640 fn encode_crate_root(&mut self) -> (LazyValue<CrateRoot>, LazyValue<CrateRootUnhashed>) {
641 let tcx = self.tcx;
642
643 self.local_defs_remapping = LocalDefsRemapping::new(tcx);
646
647 (self.syntax_context_remapping, self.local_expn_id_remapping) = tcx
648 .with_stable_hashing_context(|mut ctx| {
649 (
650 SyntaxContextRemapper::with(|r| r.remapping_results(&mut ctx)),
651 LocalExpnIdRemapper::with(|r| r.remapping_results(&mut ctx)),
652 )
653 });
654
655 let mut stats: Vec<(&'static str, usize)> = Vec::with_capacity(32);
656
657 macro_rules! stat {
658 ($label:literal, $f:expr) => {{
659 let orig_pos = self.position();
660 let res = $f();
661 stats.push(($label, self.position() - orig_pos));
662 res
663 }};
664 }
665
666 stats.push(("preamble", self.position()));
668
669 let externally_implementable_items = {
let orig_pos = self.position();
let res = (|| self.encode_externally_implementable_items())();
stats.push(("externally-implementable-items",
self.position() - orig_pos));
res
}stat!("externally-implementable-items", || self
670 .encode_externally_implementable_items());
671
672 let (crate_deps, dylib_dependency_formats) =
673 {
let orig_pos = self.position();
let res =
(||
(self.encode_crate_deps(),
self.encode_dylib_dependency_formats()))();
stats.push(("dep", self.position() - orig_pos));
res
}stat!("dep", || (self.encode_crate_deps(), self.encode_dylib_dependency_formats()));
674
675 let lib_features = {
let orig_pos = self.position();
let res = (|| self.encode_lib_features())();
stats.push(("lib-features", self.position() - orig_pos));
res
}stat!("lib-features", || self.encode_lib_features());
676
677 let stability_implications =
678 {
let orig_pos = self.position();
let res = (|| self.encode_stability_implications())();
stats.push(("stability-implications", self.position() - orig_pos));
res
}stat!("stability-implications", || self.encode_stability_implications());
679
680 let (lang_items, lang_items_missing) = {
let orig_pos = self.position();
let res =
(||
{
(self.encode_lang_items(), self.encode_lang_items_missing())
})();
stats.push(("lang-items", self.position() - orig_pos));
res
}stat!("lang-items", || {
681 (self.encode_lang_items(), self.encode_lang_items_missing())
682 });
683
684 let stripped_cfg_items = {
let orig_pos = self.position();
let res = (|| self.encode_stripped_cfg_items())();
stats.push(("stripped-cfg-items", self.position() - orig_pos));
res
}stat!("stripped-cfg-items", || self.encode_stripped_cfg_items());
685
686 let diagnostic_items = {
let orig_pos = self.position();
let res = (|| self.encode_diagnostic_items())();
stats.push(("diagnostic-items", self.position() - orig_pos));
res
}stat!("diagnostic-items", || self.encode_diagnostic_items());
687
688 let canonical_symbols = {
let orig_pos = self.position();
let res = (|| self.encode_canonical_symbols())();
stats.push(("canonical-symbols", self.position() - orig_pos));
res
}stat!("canonical-symbols", || self.encode_canonical_symbols());
689
690 let fake_doc_items = {
let orig_pos = self.position();
let res = (|| self.encode_fake_doc_items())();
stats.push(("fake-doc-items", self.position() - orig_pos));
res
}stat!("fake-doc-items", || self.encode_fake_doc_items());
691
692 let native_libraries = {
let orig_pos = self.position();
let res = (|| self.encode_native_libraries())();
stats.push(("native-libs", self.position() - orig_pos));
res
}stat!("native-libs", || self.encode_native_libraries());
693
694 let foreign_modules = {
let orig_pos = self.position();
let res = (|| self.encode_foreign_modules())();
stats.push(("foreign-modules", self.position() - orig_pos));
res
}stat!("foreign-modules", || self.encode_foreign_modules());
695
696 _ = {
let orig_pos = self.position();
let res = (|| self.encode_def_path_table())();
stats.push(("def-path-table", self.position() - orig_pos));
res
}stat!("def-path-table", || self.encode_def_path_table());
697
698 let traits = {
let orig_pos = self.position();
let res = (|| self.encode_traits())();
stats.push(("traits", self.position() - orig_pos));
res
}stat!("traits", || self.encode_traits());
700
701 let impls = {
let orig_pos = self.position();
let res = (|| self.encode_impls())();
stats.push(("impls", self.position() - orig_pos));
res
}stat!("impls", || self.encode_impls());
703
704 let incoherent_impls = {
let orig_pos = self.position();
let res = (|| self.encode_incoherent_impls())();
stats.push(("incoherent-impls", self.position() - orig_pos));
res
}stat!("incoherent-impls", || self.encode_incoherent_impls());
705
706 _ = {
let orig_pos = self.position();
let res = (|| self.encode_mir())();
stats.push(("mir", self.position() - orig_pos));
res
}stat!("mir", || self.encode_mir());
707
708 _ = {
let orig_pos = self.position();
let res = (|| self.encode_def_ids())();
stats.push(("def-ids", self.position() - orig_pos));
res
}stat!("def-ids", || self.encode_def_ids());
709
710 let interpret_alloc_index = {
let orig_pos = self.position();
let res =
(||
{
let mut interpret_alloc_index = Vec::new();
let mut n = 0;
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_metadata/src/rmeta/encoder.rs:713",
"rustc_metadata::rmeta::encoder", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(713u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("beginning to encode alloc ids")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
loop {
let new_n = self.interpret_allocs.len();
if n == new_n { break; }
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_metadata/src/rmeta/encoder.rs:721",
"rustc_metadata::rmeta::encoder", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(721u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("encoding {0} further alloc ids",
new_n - n) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
for idx in n..new_n {
let id = self.interpret_allocs[idx];
let pos = self.position() as u64;
interpret_alloc_index.push(pos);
interpret::specialized_encode_alloc_id(self, tcx, id);
}
n = new_n;
}
self.lazy_array(interpret_alloc_index)
})();
stats.push(("interpret-alloc-index", self.position() - orig_pos));
res
}stat!("interpret-alloc-index", || {
711 let mut interpret_alloc_index = Vec::new();
712 let mut n = 0;
713 trace!("beginning to encode alloc ids");
714 loop {
715 let new_n = self.interpret_allocs.len();
716 if n == new_n {
718 break;
720 }
721 trace!("encoding {} further alloc ids", new_n - n);
722 for idx in n..new_n {
723 let id = self.interpret_allocs[idx];
724 let pos = self.position() as u64;
725 interpret_alloc_index.push(pos);
726 interpret::specialized_encode_alloc_id(self, tcx, id);
727 }
728 n = new_n;
729 }
730 self.lazy_array(interpret_alloc_index)
731 });
732
733 let proc_macro_data = {
let orig_pos = self.position();
let res = (|| self.encode_proc_macros())();
stats.push(("proc-macro-data", self.position() - orig_pos));
res
}stat!("proc-macro-data", || self.encode_proc_macros());
737
738 let tables = {
let orig_pos = self.position();
let res = (|| self.tables.encode(&mut self.opaque))();
stats.push(("tables", self.position() - orig_pos));
res
}stat!("tables", || self.tables.encode(&mut self.opaque));
739
740 let debugger_visualizers =
741 {
let orig_pos = self.position();
let res = (|| self.encode_debugger_visualizers())();
stats.push(("debugger-visualizers", self.position() - orig_pos));
res
}stat!("debugger-visualizers", || self.encode_debugger_visualizers());
742
743 let exportable_items = {
let orig_pos = self.position();
let res = (|| self.encode_exportable_items())();
stats.push(("exportable-items", self.position() - orig_pos));
res
}stat!("exportable-items", || self.encode_exportable_items());
744
745 let stable_order_of_exportable_impls =
746 {
let orig_pos = self.position();
let res = (|| self.encode_stable_order_of_exportable_impls())();
stats.push(("exportable-items", self.position() - orig_pos));
res
}stat!("exportable-items", || self.encode_stable_order_of_exportable_impls());
747
748 let (exported_non_generic_symbols, exported_generic_symbols) =
750 {
let orig_pos = self.position();
let res =
(||
{
(self.encode_exported_symbols(tcx.exported_non_generic_symbols(LOCAL_CRATE)),
self.encode_exported_symbols(tcx.exported_generic_symbols(LOCAL_CRATE)))
})();
stats.push(("exported-symbols", self.position() - orig_pos));
res
}stat!("exported-symbols", || {
751 (
752 self.encode_exported_symbols(tcx.exported_non_generic_symbols(LOCAL_CRATE)),
753 self.encode_exported_symbols(tcx.exported_generic_symbols(LOCAL_CRATE)),
754 )
755 });
756
757 let (syntax_contexts, expn_data, expn_hashes) = {
let orig_pos = self.position();
let res = (|| self.encode_hygiene())();
stats.push(("hygiene", self.position() - orig_pos));
res
}stat!("hygiene", || self.encode_hygiene());
764
765 let def_path_hash_map = {
let orig_pos = self.position();
let res = (|| self.encode_def_path_hash_map())();
stats.push(("def-path-hash-map", self.position() - orig_pos));
res
}stat!("def-path-hash-map", || self.encode_def_path_hash_map());
766
767 let source_map = {
let orig_pos = self.position();
let res = (|| self.encode_source_map())();
stats.push(("source-map", self.position() - orig_pos));
res
}stat!("source-map", || self.encode_source_map());
770 let target_modifiers = {
let orig_pos = self.position();
let res = (|| self.encode_target_modifiers())();
stats.push(("target-modifiers", self.position() - orig_pos));
res
}stat!("target-modifiers", || self.encode_target_modifiers());
771 let denied_partial_mitigations = {
let orig_pos = self.position();
let res = (|| self.encode_enabled_denied_partial_mitigations())();
stats.push(("denied-partial-mitigations", self.position() - orig_pos));
res
}stat!("denied-partial-mitigations", || self
772 .encode_enabled_denied_partial_mitigations());
773
774 let root = {
let orig_pos = self.position();
let res =
(||
{
let attrs = tcx.hir_krate_attrs();
self.lazy(CrateRoot {
header: CrateHeader {
name: tcx.crate_name(LOCAL_CRATE),
triple: tcx.sess.opts.target_triple.clone(),
is_proc_macro_crate: proc_macro_data.is_some(),
is_stub: false,
},
stable_crate_id: tcx.stable_crate_id(LOCAL_CRATE),
required_panic_strategy: tcx.required_panic_strategy(LOCAL_CRATE),
panic_in_drop_strategy: tcx.sess.opts.unstable_opts.panic_in_drop,
edition: tcx.sess.edition(),
has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
has_alloc_error_handler: tcx.has_alloc_error_handler(LOCAL_CRATE),
has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
has_default_lib_allocator: {
{
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(DefaultLibAllocator) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
},
externally_implementable_items,
proc_macro_data,
debugger_visualizers,
compiler_builtins: {
{
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(CompilerBuiltins) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
},
needs_allocator: {
{
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(NeedsAllocator) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
},
needs_panic_runtime: {
{
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(NeedsPanicRuntime) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
},
no_builtins: {
{
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(NoBuiltins) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
},
panic_runtime: {
{
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(PanicRuntime) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
},
profiler_runtime: {
{
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(ProfilerRuntime) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
},
symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(),
crate_deps,
dylib_dependency_formats,
lib_features,
stability_implications,
lang_items,
diagnostic_items,
canonical_symbols,
fake_doc_items,
lang_items_missing,
stripped_cfg_items,
native_libraries,
foreign_modules,
source_map,
target_modifiers,
denied_partial_mitigations,
traits,
impls,
incoherent_impls,
exportable_items,
stable_order_of_exportable_impls,
exported_non_generic_symbols,
exported_generic_symbols,
interpret_alloc_index,
tables,
syntax_contexts,
expn_data,
expn_hashes,
def_path_hash_map,
specialization_enabled_in: tcx.specialization_enabled_in(LOCAL_CRATE),
})
})();
stats.push(("crate-root", self.position() - orig_pos));
res
}stat!("crate-root", || {
775 let attrs = tcx.hir_krate_attrs();
776 self.lazy(CrateRoot {
777 header: CrateHeader {
778 name: tcx.crate_name(LOCAL_CRATE),
779 triple: tcx.sess.opts.target_triple.clone(),
780 is_proc_macro_crate: proc_macro_data.is_some(),
781 is_stub: false,
782 },
783
784 stable_crate_id: tcx.stable_crate_id(LOCAL_CRATE),
785 required_panic_strategy: tcx.required_panic_strategy(LOCAL_CRATE),
786 panic_in_drop_strategy: tcx.sess.opts.unstable_opts.panic_in_drop,
787 edition: tcx.sess.edition(),
788 has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
789 has_alloc_error_handler: tcx.has_alloc_error_handler(LOCAL_CRATE),
790 has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
791 has_default_lib_allocator: find_attr!(attrs, DefaultLibAllocator),
792 externally_implementable_items,
793 proc_macro_data,
794 debugger_visualizers,
795 compiler_builtins: find_attr!(attrs, CompilerBuiltins),
796 needs_allocator: find_attr!(attrs, NeedsAllocator),
797 needs_panic_runtime: find_attr!(attrs, NeedsPanicRuntime),
798 no_builtins: find_attr!(attrs, NoBuiltins),
799 panic_runtime: find_attr!(attrs, PanicRuntime),
800 profiler_runtime: find_attr!(attrs, ProfilerRuntime),
801 symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(),
802
803 crate_deps,
804 dylib_dependency_formats,
805 lib_features,
806 stability_implications,
807 lang_items,
808 diagnostic_items,
809 canonical_symbols,
810 fake_doc_items,
811 lang_items_missing,
812 stripped_cfg_items,
813 native_libraries,
814 foreign_modules,
815 source_map,
816 target_modifiers,
817 denied_partial_mitigations,
818 traits,
819 impls,
820 incoherent_impls,
821 exportable_items,
822 stable_order_of_exportable_impls,
823 exported_non_generic_symbols,
824 exported_generic_symbols,
825 interpret_alloc_index,
826 tables,
827 syntax_contexts,
828 expn_data,
829 expn_hashes,
830 def_path_hash_map,
831 specialization_enabled_in: tcx.specialization_enabled_in(LOCAL_CRATE),
832 })
833 });
834
835 let hash = if tcx.sess.opts.unstable_opts.metadata_crate_hash {
839 self.opaque.flush();
840 Svh::new(Fingerprint::from_le_bytes(
841 self.metadata_hasher.lock().unwrap().finish_128().to_le_bytes(),
842 ))
843 } else {
844 tcx.crate_hash(LOCAL_CRATE)
845 };
846 tcx.untracked().local_crate_hash.set(hash).expect("local_crate_hash set twice");
847
848 let unhashed = {
let orig_pos = self.position();
let res =
(||
{
let mut dep_extra_filenames =
IndexVec::from_elem_n(String::new(), 1);
if !self.is_proc_macro {
for &cnum in tcx.crates(()).iter() {
let idx =
dep_extra_filenames.push(tcx.extra_filename(cnum).to_owned());
{
match (&idx, &cnum) {
(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::Some(format_args!("dep_extra_filenames must be indexed by CrateNum")));
}
}
}
};
}
}
self.lazy(CrateRootUnhashed {
extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
dep_extra_filenames,
})
})();
stats.push(("final", self.position() - orig_pos));
res
}stat!("final", || {
849 let mut dep_extra_filenames = IndexVec::from_elem_n(String::new(), 1);
852 if !self.is_proc_macro {
853 for &cnum in tcx.crates(()).iter() {
854 let idx = dep_extra_filenames.push(tcx.extra_filename(cnum).to_owned());
855 assert_eq!(idx, cnum, "dep_extra_filenames must be indexed by CrateNum");
856 }
857 }
858
859 self.lazy(CrateRootUnhashed {
860 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
861 dep_extra_filenames,
862 })
863 });
864
865 let total_bytes = self.position();
866
867 let computed_total_bytes: usize = stats.iter().map(|(_, size)| size).sum();
868 {
match (&total_bytes, &computed_total_bytes) {
(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!(total_bytes, computed_total_bytes);
869
870 if tcx.sess.opts.unstable_opts.meta_stats {
871 use std::fmt::Write;
872
873 self.opaque.flush();
874
875 let pos_before_rewind = self.opaque.file().stream_position().unwrap();
877 let mut zero_bytes = 0;
878 self.opaque.file().rewind().unwrap();
879 let file = std::io::BufReader::new(self.opaque.file());
880 for e in file.bytes() {
881 if e.unwrap() == 0 {
882 zero_bytes += 1;
883 }
884 }
885 {
match (&self.opaque.file().stream_position().unwrap(), &pos_before_rewind)
{
(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!(self.opaque.file().stream_position().unwrap(), pos_before_rewind);
886
887 stats.sort_by_key(|&(_, usize)| usize);
888 stats.reverse(); let prefix = "meta-stats";
891 let perc = |bytes| (bytes * 100) as f64 / total_bytes as f64;
892
893 let section_w = 23;
894 let size_w = 10;
895 let banner_w = 64;
896
897 let mut s = String::new();
903 _ = s.write_fmt(format_args!("{1} {0}\n", "=".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "=".repeat(banner_w));
904 _ = s.write_fmt(format_args!("{1} METADATA STATS: {0}\n",
tcx.crate_name(LOCAL_CRATE), prefix))writeln!(s, "{prefix} METADATA STATS: {}", tcx.crate_name(LOCAL_CRATE));
905 _ = s.write_fmt(format_args!("{2} {0:<3$}{1:>4$}\n", "Section", "Size", prefix,
section_w, size_w))writeln!(s, "{prefix} {:<section_w$}{:>size_w$}", "Section", "Size");
906 _ = s.write_fmt(format_args!("{1} {0}\n", "-".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "-".repeat(banner_w));
907 for (label, size) in stats {
908 _ = s.write_fmt(format_args!("{3} {0:<4$}{1:>5$} ({2:4.1}%)\n", label,
usize_with_underscores(size), perc(size), prefix, section_w, size_w))writeln!(
909 s,
910 "{prefix} {:<section_w$}{:>size_w$} ({:4.1}%)",
911 label,
912 usize_with_underscores(size),
913 perc(size)
914 );
915 }
916 _ = s.write_fmt(format_args!("{1} {0}\n", "-".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "-".repeat(banner_w));
917 _ = s.write_fmt(format_args!("{3} {0:<4$}{1:>5$} (of which {2:.1}% are zero bytes)\n",
"Total", usize_with_underscores(total_bytes), perc(zero_bytes),
prefix, section_w, size_w))writeln!(
918 s,
919 "{prefix} {:<section_w$}{:>size_w$} (of which {:.1}% are zero bytes)",
920 "Total",
921 usize_with_underscores(total_bytes),
922 perc(zero_bytes)
923 );
924 _ = s.write_fmt(format_args!("{1} {0}\n", "=".repeat(banner_w), prefix))writeln!(s, "{prefix} {}", "=".repeat(banner_w));
925 { ::std::io::_eprint(format_args!("{0}", s)); };eprint!("{s}");
926 }
927
928 (root, unhashed)
929 }
930}
931
932struct AnalyzeAttrState {
933 is_exported: bool,
934 is_doc_hidden: bool,
935}
936
937#[inline]
947fn analyze_attr(attr: &rustc_attr_ir::Attribute, state: &mut AnalyzeAttrState) -> bool {
948 match attr {
949 Attribute::Parsed(AttributeKind::DocComment { .. }) => {
950 state.is_exported
954 }
955 Attribute::Parsed(AttributeKind::Doc(d)) => {
956 if d.hidden.is_some() {
957 state.is_doc_hidden = true;
958 }
959 true
960 }
961 Attribute::Parsed(p) => p.encode_cross_crate() == EncodeCrossCrate::Yes,
962 Attribute::Tool(_) | Attribute::DeriveHelper(_) => true,
963 }
964}
965
966fn should_encode_span(def_kind: DefKind) -> bool {
967 match def_kind {
968 DefKind::Mod
969 | DefKind::Struct
970 | DefKind::Union
971 | DefKind::Enum
972 | DefKind::Variant
973 | DefKind::Trait
974 | DefKind::TyAlias
975 | DefKind::ForeignTy
976 | DefKind::TraitAlias
977 | DefKind::AssocTy
978 | DefKind::TyParam
979 | DefKind::ConstParam
980 | DefKind::LifetimeParam
981 | DefKind::Fn
982 | DefKind::Const
983 | DefKind::Static { .. }
984 | DefKind::Ctor(..)
985 | DefKind::AssocFn
986 | DefKind::AssocConst
987 | DefKind::Macro(_)
988 | DefKind::ExternCrate
989 | DefKind::Use
990 | DefKind::AnonConst
991 | DefKind::OpaqueTy
992 | DefKind::Field
993 | DefKind::Impl { .. }
994 | DefKind::Closure
995 | DefKind::SyntheticCoroutineBody => true,
996 DefKind::ForeignMod | DefKind::GlobalAsm | DefKind::TestBinderConstraints => false,
997 }
998}
999
1000fn should_encode_attrs(def_kind: DefKind) -> bool {
1001 match def_kind {
1002 DefKind::Mod
1003 | DefKind::Struct
1004 | DefKind::Union
1005 | DefKind::Enum
1006 | DefKind::Variant
1007 | DefKind::Trait
1008 | DefKind::TyAlias
1009 | DefKind::ForeignTy
1010 | DefKind::TraitAlias
1011 | DefKind::AssocTy
1012 | DefKind::Fn
1013 | DefKind::Const
1014 | DefKind::Static { nested: false, .. }
1015 | DefKind::AssocFn
1016 | DefKind::AssocConst
1017 | DefKind::Macro(_)
1018 | DefKind::Field
1019 | DefKind::ConstParam
1020 | DefKind::Impl { .. } => true,
1021 DefKind::Use => true,
1025 DefKind::Closure => true,
1030 DefKind::SyntheticCoroutineBody => false,
1031 DefKind::TyParam
1032 | DefKind::Ctor(..)
1033 | DefKind::ExternCrate
1034 | DefKind::ForeignMod
1035 | DefKind::AnonConst
1036 | DefKind::OpaqueTy
1037 | DefKind::LifetimeParam
1038 | DefKind::Static { nested: true, .. }
1039 | DefKind::GlobalAsm
1040 | DefKind::TestBinderConstraints => false,
1041 }
1042}
1043
1044fn should_encode_expn_that_defined(def_kind: DefKind) -> bool {
1045 match def_kind {
1046 DefKind::Mod
1047 | DefKind::Struct
1048 | DefKind::Union
1049 | DefKind::Enum
1050 | DefKind::Variant
1051 | DefKind::Trait
1052 | DefKind::Impl { .. } => true,
1053 DefKind::TyAlias
1054 | DefKind::ForeignTy
1055 | DefKind::TraitAlias
1056 | DefKind::AssocTy
1057 | DefKind::TyParam
1058 | DefKind::Fn
1059 | DefKind::Const
1060 | DefKind::ConstParam
1061 | DefKind::Static { .. }
1062 | DefKind::Ctor(..)
1063 | DefKind::AssocFn
1064 | DefKind::AssocConst
1065 | DefKind::Macro(_)
1066 | DefKind::ExternCrate
1067 | DefKind::Use
1068 | DefKind::ForeignMod
1069 | DefKind::AnonConst
1070 | DefKind::OpaqueTy
1071 | DefKind::Field
1072 | DefKind::LifetimeParam
1073 | DefKind::GlobalAsm
1074 | DefKind::Closure
1075 | DefKind::SyntheticCoroutineBody
1076 | DefKind::TestBinderConstraints => false,
1077 }
1078}
1079
1080fn should_encode_visibility(def_kind: DefKind) -> bool {
1081 match def_kind {
1082 DefKind::Mod
1083 | DefKind::Struct
1084 | DefKind::Union
1085 | DefKind::Enum
1086 | DefKind::Variant
1087 | DefKind::Trait
1088 | DefKind::TyAlias
1089 | DefKind::ForeignTy
1090 | DefKind::TraitAlias
1091 | DefKind::AssocTy
1092 | DefKind::Fn
1093 | DefKind::Const
1094 | DefKind::Static { nested: false, .. }
1095 | DefKind::Ctor(..)
1096 | DefKind::AssocFn
1097 | DefKind::AssocConst
1098 | DefKind::Macro(..)
1099 | DefKind::Field => true,
1100 DefKind::Use
1101 | DefKind::ForeignMod
1102 | DefKind::TyParam
1103 | DefKind::ConstParam
1104 | DefKind::LifetimeParam
1105 | DefKind::AnonConst
1106 | DefKind::Static { nested: true, .. }
1107 | DefKind::OpaqueTy
1108 | DefKind::GlobalAsm
1109 | DefKind::Impl { .. }
1110 | DefKind::Closure
1111 | DefKind::ExternCrate
1112 | DefKind::SyntheticCoroutineBody
1113 | DefKind::TestBinderConstraints => false,
1114 }
1115}
1116
1117fn should_encode_stability(def_kind: DefKind) -> bool {
1118 match def_kind {
1119 DefKind::Mod
1120 | DefKind::Ctor(..)
1121 | DefKind::Variant
1122 | DefKind::Field
1123 | DefKind::Struct
1124 | DefKind::AssocTy
1125 | DefKind::AssocFn
1126 | DefKind::AssocConst
1127 | DefKind::TyParam
1128 | DefKind::ConstParam
1129 | DefKind::Static { .. }
1130 | DefKind::Const
1131 | DefKind::Fn
1132 | DefKind::ForeignMod
1133 | DefKind::TyAlias
1134 | DefKind::OpaqueTy
1135 | DefKind::Enum
1136 | DefKind::Union
1137 | DefKind::Impl { .. }
1138 | DefKind::Trait
1139 | DefKind::TraitAlias
1140 | DefKind::Macro(..)
1141 | DefKind::ForeignTy => true,
1142 DefKind::Use
1143 | DefKind::LifetimeParam
1144 | DefKind::AnonConst
1145 | DefKind::GlobalAsm
1146 | DefKind::Closure
1147 | DefKind::ExternCrate
1148 | DefKind::SyntheticCoroutineBody
1149 | DefKind::TestBinderConstraints => false,
1150 }
1151}
1152
1153fn should_encode_mir(
1174 tcx: TyCtxt<'_>,
1175 reachable_set: &LocalDefIdSet,
1176 def_id: LocalDefId,
1177) -> (bool, bool) {
1178 match tcx.def_kind(def_id) {
1179 DefKind::Ctor(_, _) => (true, false),
1181 DefKind::AnonConst | DefKind::AssocConst | DefKind::Const => (true, false),
1183 DefKind::Closure if tcx.is_coroutine(def_id.to_def_id()) => (false, true),
1185 DefKind::SyntheticCoroutineBody => (false, true),
1186 DefKind::AssocFn | DefKind::Fn | DefKind::Closure => {
1188 let opt = tcx.sess.opts.unstable_opts.always_encode_mir
1189 || (tcx.sess.opts.output_types.should_codegen()
1190 && reachable_set.contains(&def_id)
1191 && (tcx.generics_of(def_id).requires_monomorphization(tcx)
1192 || tcx.cross_crate_inlinable(def_id)));
1193 let opt =
1195 opt && !#[allow(non_exhaustive_omitted_patterns)] match tcx.constness(def_id) {
hir::Constness::Const { always: true } => true,
_ => false,
}matches!(tcx.constness(def_id), hir::Constness::Const { always: true });
1196 let is_const_fn = tcx.is_const_fn(def_id.to_def_id());
1198 (is_const_fn, opt)
1199 }
1200 _ => (false, false),
1202 }
1203}
1204
1205fn should_encode_variances<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, def_kind: DefKind) -> bool {
1206 match def_kind {
1207 DefKind::Struct
1208 | DefKind::Union
1209 | DefKind::Enum
1210 | DefKind::OpaqueTy
1211 | DefKind::Fn
1212 | DefKind::Ctor(..)
1213 | DefKind::AssocFn => true,
1214 DefKind::AssocTy => {
1215 #[allow(non_exhaustive_omitted_patterns)] match tcx.opt_rpitit_info(def_id) {
Some(ty::ImplTraitInTraitData::Trait { .. }) => true,
_ => false,
}matches!(tcx.opt_rpitit_info(def_id), Some(ty::ImplTraitInTraitData::Trait { .. }))
1217 }
1218 DefKind::Mod
1219 | DefKind::Variant
1220 | DefKind::Field
1221 | DefKind::AssocConst
1222 | DefKind::TyParam
1223 | DefKind::ConstParam
1224 | DefKind::Static { .. }
1225 | DefKind::Const
1226 | DefKind::ForeignMod
1227 | DefKind::TyAlias
1228 | DefKind::Impl { .. }
1229 | DefKind::Trait
1230 | DefKind::TraitAlias
1231 | DefKind::Macro(..)
1232 | DefKind::ForeignTy
1233 | DefKind::Use
1234 | DefKind::LifetimeParam
1235 | DefKind::AnonConst
1236 | DefKind::GlobalAsm
1237 | DefKind::Closure
1238 | DefKind::ExternCrate
1239 | DefKind::SyntheticCoroutineBody
1240 | DefKind::TestBinderConstraints => false,
1241 }
1242}
1243
1244fn should_encode_generics(def_kind: DefKind) -> bool {
1245 match def_kind {
1246 DefKind::Struct
1247 | DefKind::Union
1248 | DefKind::Enum
1249 | DefKind::Variant
1250 | DefKind::Trait
1251 | DefKind::TyAlias
1252 | DefKind::ForeignTy
1253 | DefKind::TraitAlias
1254 | DefKind::AssocTy
1255 | DefKind::Fn
1256 | DefKind::Const
1257 | DefKind::Static { .. }
1258 | DefKind::Ctor(..)
1259 | DefKind::AssocFn
1260 | DefKind::AssocConst
1261 | DefKind::AnonConst
1262 | DefKind::OpaqueTy
1263 | DefKind::Impl { .. }
1264 | DefKind::Field
1265 | DefKind::TyParam
1266 | DefKind::Closure
1267 | DefKind::SyntheticCoroutineBody => true,
1268 DefKind::Mod
1269 | DefKind::ForeignMod
1270 | DefKind::ConstParam
1271 | DefKind::Macro(..)
1272 | DefKind::Use
1273 | DefKind::LifetimeParam
1274 | DefKind::GlobalAsm
1275 | DefKind::ExternCrate
1276 | DefKind::TestBinderConstraints => false,
1277 }
1278}
1279
1280fn should_encode_type(tcx: TyCtxt<'_>, def_id: LocalDefId, def_kind: DefKind) -> bool {
1281 match def_kind {
1282 DefKind::Struct
1283 | DefKind::Union
1284 | DefKind::Enum
1285 | DefKind::Variant
1286 | DefKind::Ctor(..)
1287 | DefKind::Field
1288 | DefKind::Fn
1289 | DefKind::Const
1290 | DefKind::Static { nested: false, .. }
1291 | DefKind::TyAlias
1292 | DefKind::ForeignTy
1293 | DefKind::Impl { .. }
1294 | DefKind::AssocFn
1295 | DefKind::AssocConst
1296 | DefKind::Closure
1297 | DefKind::ConstParam
1298 | DefKind::AnonConst
1299 | DefKind::SyntheticCoroutineBody => true,
1300
1301 DefKind::OpaqueTy => {
1302 let origin = tcx.local_opaque_ty_origin(def_id);
1303 if let hir::OpaqueTyOrigin::FnReturn { parent, .. }
1304 | hir::OpaqueTyOrigin::AsyncFn { parent, .. } = origin
1305 && let hir::Node::TraitItem(trait_item) = tcx.hir_node_by_def_id(parent)
1306 && let (_, hir::TraitFn::Required(..)) = trait_item.expect_fn()
1307 {
1308 false
1309 } else {
1310 true
1311 }
1312 }
1313
1314 DefKind::AssocTy => {
1315 let assoc_item = tcx.associated_item(def_id);
1316 match assoc_item.container {
1317 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => true,
1318 ty::AssocContainer::Trait => assoc_item.defaultness(tcx).has_value(),
1319 }
1320 }
1321 DefKind::TyParam => {
1322 let hir::Node::GenericParam(param) = tcx.hir_node_by_def_id(def_id) else { ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller())bug!() };
1323 let hir::GenericParamKind::Type { default, .. } = param.kind else { ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller())bug!() };
1324 default.is_some()
1325 }
1326
1327 DefKind::Trait
1328 | DefKind::TraitAlias
1329 | DefKind::Mod
1330 | DefKind::ForeignMod
1331 | DefKind::Macro(..)
1332 | DefKind::Static { nested: true, .. }
1333 | DefKind::Use
1334 | DefKind::LifetimeParam
1335 | DefKind::GlobalAsm
1336 | DefKind::ExternCrate
1337 | DefKind::TestBinderConstraints => false,
1338 }
1339}
1340
1341fn should_encode_fn_sig(def_kind: DefKind) -> bool {
1342 match def_kind {
1343 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) => true,
1344
1345 DefKind::Struct
1346 | DefKind::Union
1347 | DefKind::Enum
1348 | DefKind::Variant
1349 | DefKind::Field
1350 | DefKind::Const
1351 | DefKind::Static { .. }
1352 | DefKind::Ctor(..)
1353 | DefKind::TyAlias
1354 | DefKind::OpaqueTy
1355 | DefKind::ForeignTy
1356 | DefKind::Impl { .. }
1357 | DefKind::AssocConst
1358 | DefKind::Closure
1359 | DefKind::ConstParam
1360 | DefKind::AnonConst
1361 | DefKind::AssocTy
1362 | DefKind::TyParam
1363 | DefKind::Trait
1364 | DefKind::TraitAlias
1365 | DefKind::Mod
1366 | DefKind::ForeignMod
1367 | DefKind::Macro(..)
1368 | DefKind::Use
1369 | DefKind::LifetimeParam
1370 | DefKind::GlobalAsm
1371 | DefKind::ExternCrate
1372 | DefKind::SyntheticCoroutineBody
1373 | DefKind::TestBinderConstraints => false,
1374 }
1375}
1376
1377fn should_encode_constness(def_kind: DefKind) -> bool {
1378 match def_kind {
1379 DefKind::Fn
1380 | DefKind::AssocFn
1381 | DefKind::Closure
1382 | DefKind::Ctor(_, CtorKind::Fn)
1383 | DefKind::Impl { of_trait: false } => true,
1384
1385 DefKind::Struct
1386 | DefKind::Union
1387 | DefKind::Enum
1388 | DefKind::Field
1389 | DefKind::Const
1390 | DefKind::AssocConst
1391 | DefKind::AnonConst
1392 | DefKind::Static { .. }
1393 | DefKind::TyAlias
1394 | DefKind::OpaqueTy
1395 | DefKind::Impl { .. }
1396 | DefKind::ForeignTy
1397 | DefKind::ConstParam
1398 | DefKind::AssocTy
1399 | DefKind::TyParam
1400 | DefKind::Trait
1401 | DefKind::TraitAlias
1402 | DefKind::Mod
1403 | DefKind::ForeignMod
1404 | DefKind::Macro(..)
1405 | DefKind::Use
1406 | DefKind::LifetimeParam
1407 | DefKind::GlobalAsm
1408 | DefKind::ExternCrate
1409 | DefKind::Ctor(_, CtorKind::Const)
1410 | DefKind::Variant
1411 | DefKind::SyntheticCoroutineBody
1412 | DefKind::TestBinderConstraints => false,
1413 }
1414}
1415
1416fn should_encode_const(def_kind: DefKind) -> bool {
1417 match def_kind {
1418 DefKind::Const | DefKind::AssocConst | DefKind::AnonConst => true,
1420
1421 DefKind::Struct
1422 | DefKind::Union
1423 | DefKind::Enum
1424 | DefKind::Variant
1425 | DefKind::Ctor(..)
1426 | DefKind::Field
1427 | DefKind::Fn
1428 | DefKind::Static { .. }
1429 | DefKind::TyAlias
1430 | DefKind::OpaqueTy
1431 | DefKind::ForeignTy
1432 | DefKind::Impl { .. }
1433 | DefKind::AssocFn
1434 | DefKind::Closure
1435 | DefKind::ConstParam
1436 | DefKind::AssocTy
1437 | DefKind::TyParam
1438 | DefKind::Trait
1439 | DefKind::TraitAlias
1440 | DefKind::Mod
1441 | DefKind::ForeignMod
1442 | DefKind::Macro(..)
1443 | DefKind::Use
1444 | DefKind::LifetimeParam
1445 | DefKind::GlobalAsm
1446 | DefKind::ExternCrate
1447 | DefKind::SyntheticCoroutineBody
1448 | DefKind::TestBinderConstraints => false,
1449 }
1450}
1451
1452impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1453 fn encode_attrs(&mut self, def_id: LocalDefId) {
1454 let tcx = self.tcx;
1455 let mut state = AnalyzeAttrState {
1456 is_exported: tcx.effective_visibilities(()).is_exported(def_id),
1457 is_doc_hidden: false,
1458 };
1459 let attr_iter = tcx
1460 .hir_attrs(tcx.local_def_id_to_hir_id(def_id))
1461 .iter()
1462 .filter(|attr| analyze_attr(*attr, &mut state));
1463
1464 self.table_writer().attributes(def_id, attr_iter);
1465
1466 let mut attr_flags = AttrFlags::empty();
1467 if state.is_doc_hidden {
1468 attr_flags |= AttrFlags::IS_DOC_HIDDEN;
1469 }
1470
1471 self.table_writer().attr_flags(def_id, attr_flags);
1472 }
1473
1474 fn table_writer(&mut self) -> super::TableWriter<'a, 'tcx, '_> {
1480 super::TableWriter { encoder: self }
1481 }
1482
1483 fn encode_def_ids(&mut self) {
1484 self.encode_info_for_mod(CRATE_DEF_ID);
1485
1486 if self.is_proc_macro {
1489 return;
1490 }
1491
1492 let tcx = self.tcx;
1493 for local_id in self.local_defs_remapping.iter_sorted_local_ids() {
1494 let def_id = local_id.to_def_id();
1495 let def_kind = tcx.def_kind(local_id);
1496 self.table_writer().def_kind(local_id, def_kind);
1497
1498 if def_kind == DefKind::AnonConst
1504 && #[allow(non_exhaustive_omitted_patterns)] match tcx.hir_node_by_def_id(local_id)
{
hir::Node::ConstArg(_) |
hir::Node::Infer(hir::InferArg { kind: hir::InferArgKind::Const, .. })
=> true,
_ => false,
}matches!(
1505 tcx.hir_node_by_def_id(local_id),
1506 hir::Node::ConstArg(_)
1507 | hir::Node::Infer(hir::InferArg { kind: hir::InferArgKind::Const, .. })
1508 )
1509 {
1510 continue;
1511 }
1512
1513 if def_kind == DefKind::Field
1514 && let hir::Node::Field(field) = tcx.hir_node_by_def_id(local_id)
1515 && let Some(anon) = field.default
1516 {
1517 self.table_writer().default_fields(local_id, anon.def_id.to_def_id());
1518 }
1519
1520 if should_encode_span(def_kind) {
1521 let def_span = tcx.def_span(local_id);
1522 self.table_writer().def_span(local_id, def_span);
1523 }
1524 if should_encode_attrs(def_kind) {
1525 self.encode_attrs(local_id);
1526 }
1527 if should_encode_expn_that_defined(def_kind) {
1528 self.table_writer().expn_that_defined(local_id, tcx.expn_that_defined(def_id));
1529 }
1530 if should_encode_span(def_kind)
1531 && let Some(ident_span) = tcx.def_ident_span(def_id)
1532 {
1533 self.table_writer().def_ident_span(local_id, ident_span);
1534 }
1535 if def_kind.has_codegen_attrs() {
1536 self.table_writer().codegen_fn_attrs(local_id, tcx.codegen_fn_attrs(def_id));
1537 }
1538 if should_encode_visibility(def_kind) {
1539 let vis = tcx.local_visibility(local_id).map_id(|mod_id| mod_id.to_local_def_id());
1540 self.table_writer().visibility(local_id, vis);
1541 }
1542 if should_encode_stability(def_kind) {
1543 self.encode_stability(local_id);
1544 self.encode_const_stability(local_id);
1545 self.encode_default_body_stability(local_id);
1546 self.encode_deprecation(local_id);
1547 }
1548 if should_encode_variances(tcx, def_id, def_kind) {
1549 let v = tcx.variances_of(def_id);
1550 self.table_writer().variances_of(local_id, v);
1551 }
1552 if should_encode_fn_sig(def_kind) {
1553 self.table_writer().fn_sig(local_id, tcx.fn_sig(def_id));
1554 }
1555 if should_encode_generics(def_kind) {
1556 let g = tcx.generics_of(def_id);
1557 self.table_writer().generics_of(local_id, g);
1558 self.table_writer().explicit_clauses_of(local_id, tcx.explicit_clauses_of(def_id));
1559 let inferred_outlives = tcx.inferred_outlives_of(def_id);
1560 self.table_writer().inferred_outlives_of(local_id, inferred_outlives);
1561
1562 for param in &g.own_params {
1563 if let ty::GenericParamDefKind::Const { has_default: true, .. } = param.kind {
1564 let default = tcx.const_param_default(param.def_id);
1565 self.table_writer()
1566 .const_param_default(param.def_id.expect_local(), default);
1567 }
1568 }
1569 }
1570 if tcx.is_conditionally_const(def_id) {
1571 self.table_writer().const_conditions(local_id, tcx.const_conditions(def_id));
1572 }
1573 if should_encode_type(tcx, local_id, def_kind) {
1574 self.table_writer().type_of(local_id, tcx.type_of(def_id));
1575 }
1576 if should_encode_constness(def_kind) {
1577 let constness = tcx.constness(def_id);
1578 self.table_writer().constness(local_id, constness);
1579 }
1580 if let DefKind::Fn | DefKind::AssocFn = def_kind {
1581 let asyncness = tcx.asyncness(def_id);
1582 self.table_writer().asyncness(local_id, asyncness);
1583 self.table_writer().fn_arg_idents(local_id, tcx.fn_arg_idents(def_id));
1584 }
1585 self.table_writer().intrinsic(local_id, tcx.intrinsic(def_id));
1586 if let DefKind::TyParam | DefKind::Trait = def_kind {
1587 let default = tcx.object_lifetime_default(def_id);
1588 self.table_writer().object_lifetime_default(local_id, default);
1589 }
1590 if let DefKind::Trait = def_kind {
1591 self.table_writer().trait_def(local_id, tcx.trait_def(def_id));
1592 self.table_writer().explicit_super_clauses_of(
1593 local_id,
1594 tcx.explicit_super_clauses_of(def_id).skip_binder(),
1595 );
1596 self.table_writer().explicit_implied_clauses_of(
1597 local_id,
1598 tcx.explicit_implied_clauses_of(def_id).skip_binder(),
1599 );
1600 let module_children = tcx.module_children_local(local_id);
1601 self.table_writer().module_children_non_reexports(
1602 local_id,
1603 module_children.iter().map(|child| child.res.def_id().expect_local()),
1604 );
1605 if tcx.is_const_trait(def_id) {
1606 self.table_writer().explicit_implied_const_bounds(
1607 local_id,
1608 tcx.explicit_implied_const_bounds(def_id).skip_binder(),
1609 );
1610 }
1611 }
1612 if let DefKind::TraitAlias = def_kind {
1613 self.table_writer().trait_def(local_id, tcx.trait_def(def_id));
1614 self.table_writer().explicit_super_clauses_of(
1615 local_id,
1616 tcx.explicit_super_clauses_of(def_id).skip_binder(),
1617 );
1618 self.table_writer().explicit_implied_clauses_of(
1619 local_id,
1620 tcx.explicit_implied_clauses_of(def_id).skip_binder(),
1621 );
1622 }
1623 if let DefKind::Trait | DefKind::Impl { .. } = def_kind {
1624 let associated_item_def_ids = tcx.associated_item_def_ids(def_id);
1625 self.table_writer().associated_item_or_field_def_ids(
1626 local_id,
1627 associated_item_def_ids.iter().map(|&def_id| def_id.expect_local()),
1628 );
1629 for &def_id in associated_item_def_ids {
1630 self.encode_info_for_assoc_item(def_id.expect_local());
1631 }
1632 }
1633 if let DefKind::Closure | DefKind::SyntheticCoroutineBody = def_kind
1634 && let Some(coroutine_kind) = tcx.coroutine_kind(def_id)
1635 {
1636 self.table_writer().coroutine_kind(local_id, coroutine_kind);
1637 }
1638 if def_kind == DefKind::Closure
1639 && tcx.type_of(def_id).skip_binder().is_coroutine_closure()
1640 {
1641 let coroutine_for_closure = tcx.coroutine_for_closure(def_id);
1642 let remapped_id =
1643 RemappedRawDefId::create(coroutine_for_closure, &self.local_defs_remapping);
1644
1645 self.table_writer().coroutine_for_closure(local_id, remapped_id);
1646
1647 if tcx.needs_coroutine_by_move_body_def_id(coroutine_for_closure) {
1649 let id = tcx.coroutine_by_move_body_def_id(coroutine_for_closure);
1650 let id = RemappedRawDefId::create(id, &self.local_defs_remapping);
1651
1652 self.table_writer()
1653 .coroutine_by_move_body_def_id(coroutine_for_closure.expect_local(), id);
1654 }
1655 }
1656 if let DefKind::Static { .. } = def_kind {
1657 if !tcx.is_foreign_item(def_id) {
1658 match tcx.eval_static_initializer(def_id) {
1659 Ok(data) => {
1660 self.table_writer().eval_static_initializer(local_id, data);
1661 }
1662 Err(err) => match err {
1663 interpret::ErrorHandled::Reported(_, _) => {
1664 tcx.dcx().delayed_bug(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("eval_static_initializer returned an error in metadata emission"))
})format!(
1665 "eval_static_initializer returned an error in metadata emission"
1666 ));
1667 }
1668 interpret::ErrorHandled::TooGeneric(span) => {
1669 ::rustc_span::macros::bug_impl(Some(span), format_args!("generic static???"),
Location::caller());span_bug!(span, "generic static???");
1670 }
1671 },
1672 };
1673 }
1674 }
1675 if let DefKind::Enum | DefKind::Struct | DefKind::Union = def_kind {
1676 self.encode_info_for_adt(local_id);
1677 }
1678 if let DefKind::Mod = def_kind {
1679 self.encode_info_for_mod(local_id);
1680 }
1681 if let DefKind::Macro(_) = def_kind {
1682 self.encode_info_for_macro(local_id);
1683 }
1684 if let DefKind::TyAlias = def_kind {
1685 self.table_writer()
1686 .type_alias_is_checked(local_id, tcx.type_alias_is_checked(def_id));
1687
1688 if tcx.type_alias_is_checked(def_id) {
1689 self.table_writer().args_known_to_outlive_alias_params(
1690 local_id,
1691 tcx.args_known_to_outlive_alias_params(def_id),
1692 );
1693 }
1694 }
1695 if let DefKind::OpaqueTy = def_kind {
1696 self.encode_explicit_item_bounds(local_id);
1697 self.encode_explicit_item_self_bounds(local_id);
1698 self.table_writer().opaque_ty_origin(local_id, tcx.opaque_ty_origin(def_id));
1699 self.encode_precise_capturing_args(local_id);
1700 if tcx.is_conditionally_const(def_id) {
1701 self.table_writer().explicit_implied_const_bounds(
1702 local_id,
1703 tcx.explicit_implied_const_bounds(def_id).skip_binder(),
1704 );
1705 }
1706 self.table_writer().args_known_to_outlive_alias_params(
1707 local_id,
1708 tcx.args_known_to_outlive_alias_params(def_id),
1709 );
1710 }
1711 if let DefKind::AssocTy = def_kind {
1712 let assoc_item = tcx.associated_item(def_id);
1713 match assoc_item.container {
1714 ty::AssocContainer::Trait => {
1715 self.table_writer().args_known_to_outlive_alias_params(
1716 local_id,
1717 tcx.args_known_to_outlive_alias_params(def_id),
1718 );
1719 }
1720 ty::AssocContainer::InherentImpl => {
1721 self.table_writer().args_known_to_outlive_alias_params(
1722 local_id,
1723 tcx.args_known_to_outlive_alias_params(def_id),
1724 );
1725 }
1726 ty::AssocContainer::TraitImpl(_) => {}
1727 }
1728 }
1729 if let DefKind::AnonConst = def_kind {
1730 self.table_writer().anon_const_kind(local_id, tcx.anon_const_kind(def_id));
1731 }
1732 if let DefKind::Const | DefKind::AssocConst = def_kind {
1733 self.table_writer().const_of_item(local_id, tcx.const_of_item(def_id));
1734 }
1735 if tcx.impl_method_has_trait_impl_trait_tys(def_id)
1736 && let Ok(table) = tcx.collect_return_position_impl_trait_in_trait_tys(def_id)
1737 {
1738 self.table_writer()
1739 .collect_return_position_impl_trait_in_trait_tys(local_id, table);
1740 }
1741 if let DefKind::Impl { .. } | DefKind::Trait = def_kind {
1742 let table = tcx.associated_types_for_impl_traits_in_trait_or_impl(def_id);
1743 self.table_writer()
1744 .associated_types_for_impl_traits_in_trait_or_impl(local_id, table);
1745 }
1746 }
1747
1748 for (def_id, impls) in &tcx.crate_inherent_impls(()).0.inherent_impls {
1749 self.table_writer()
1750 .inherent_impls(*def_id, impls.iter().map(|def_id| def_id.expect_local()));
1751 }
1752
1753 for (def_id, res_map) in &tcx.resolutions(()).doc_link_resolutions {
1754 self.table_writer().doc_link_resolutions(def_id.to_local_def_id(), res_map);
1755 }
1756
1757 for (def_id, traits) in &tcx.resolutions(()).doc_link_traits_in_scope {
1758 self.table_writer().doc_link_traits_in_scope(def_id.to_local_def_id(), traits);
1759 }
1760 }
1761
1762 fn encode_externally_implementable_items(&mut self) -> LazyArray<EiiMapEncodedKeyValue> {
1763 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
1764 let externally_implementable_items = self.tcx.externally_implementable_items(LOCAL_CRATE);
1765
1766 self.lazy_array(externally_implementable_items.iter().map(
1767 |(foreign_item, (decl, impls))| {
1768 (
1769 *foreign_item,
1770 (decl.clone(), impls.iter().map(|(impl_did, i)| (*impl_did, *i)).collect()),
1771 )
1772 },
1773 ))
1774 }
1775
1776 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("encode_info_for_adt",
"rustc_metadata::rmeta::encoder", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(1776u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("local_def_id")
}> =
::tracing::__macro_support::FieldName::new("local_def_id");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&local_def_id)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let def_id = local_def_id.to_def_id();
let tcx = self.tcx;
let adt_def = tcx.adt_def(def_id);
self.table_writer().repr_options(local_def_id, adt_def.repr());
let params_in_repr = tcx.params_in_repr(def_id);
self.table_writer().params_in_repr(local_def_id, params_in_repr);
if adt_def.is_enum() {
let module_children = tcx.module_children_local(local_def_id);
self.table_writer().module_children_non_reexports(local_def_id,
module_children.iter().map(|child|
child.res.def_id().expect_local()));
} else {
if true {
{
match (&adt_def.variants().len(), &1) {
(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);
}
}
}
};
};
if true {
{
match (&adt_def.non_enum_variant().def_id, &def_id) {
(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);
}
}
}
};
};
}
for (idx, variant) in adt_def.variants().iter_enumerated() {
let variant_id = variant.def_id.expect_local();
let data =
VariantData {
discr: variant.discr,
idx,
ctor: variant.ctor.map(|(kind, def_id)|
(kind, def_id.expect_local())),
is_non_exhaustive: variant.is_field_list_non_exhaustive(),
};
self.table_writer().variant_data(variant_id, data);
self.table_writer().associated_item_or_field_def_ids(variant_id,
variant.fields.iter().map(|f| f.did.expect_local()));
for field in &variant.fields {
let field_id = field.did.expect_local();
self.table_writer().safety(field_id, field.safety);
self.table_writer().mut_restriction(field_id,
field.mut_restriction);
}
if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor {
let fn_sig = tcx.fn_sig(ctor_def_id);
self.table_writer().fn_sig(variant_id, fn_sig);
}
}
if let Some(destructor) = tcx.adt_destructor(local_def_id) {
self.table_writer().adt_destructor(local_def_id, destructor);
}
if let Some(destructor) = tcx.adt_async_destructor(local_def_id) {
self.table_writer().adt_async_destructor(local_def_id,
destructor);
}
}
}
}#[instrument(level = "trace", skip(self))]
1777 fn encode_info_for_adt(&mut self, local_def_id: LocalDefId) {
1778 let def_id = local_def_id.to_def_id();
1779 let tcx = self.tcx;
1780 let adt_def = tcx.adt_def(def_id);
1781 self.table_writer().repr_options(local_def_id, adt_def.repr());
1782
1783 let params_in_repr = tcx.params_in_repr(def_id);
1784 self.table_writer().params_in_repr(local_def_id, params_in_repr);
1785
1786 if adt_def.is_enum() {
1787 let module_children = tcx.module_children_local(local_def_id);
1788 self.table_writer().module_children_non_reexports(
1789 local_def_id,
1790 module_children.iter().map(|child| child.res.def_id().expect_local()),
1791 );
1792 } else {
1793 debug_assert_eq!(adt_def.variants().len(), 1);
1795 debug_assert_eq!(adt_def.non_enum_variant().def_id, def_id);
1796 }
1798
1799 for (idx, variant) in adt_def.variants().iter_enumerated() {
1800 let variant_id = variant.def_id.expect_local();
1801
1802 let data = VariantData {
1803 discr: variant.discr,
1804 idx,
1805 ctor: variant.ctor.map(|(kind, def_id)| (kind, def_id.expect_local())),
1806 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1807 };
1808 self.table_writer().variant_data(variant_id, data);
1809
1810 self.table_writer().associated_item_or_field_def_ids(
1811 variant_id,
1812 variant.fields.iter().map(|f| f.did.expect_local()),
1813 );
1814
1815 for field in &variant.fields {
1816 let field_id = field.did.expect_local();
1817 self.table_writer().safety(field_id, field.safety);
1818 self.table_writer().mut_restriction(field_id, field.mut_restriction);
1819 }
1820
1821 if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor {
1822 let fn_sig = tcx.fn_sig(ctor_def_id);
1823 self.table_writer().fn_sig(variant_id, fn_sig);
1825 }
1826 }
1827
1828 if let Some(destructor) = tcx.adt_destructor(local_def_id) {
1829 self.table_writer().adt_destructor(local_def_id, destructor);
1830 }
1831
1832 if let Some(destructor) = tcx.adt_async_destructor(local_def_id) {
1833 self.table_writer().adt_async_destructor(local_def_id, destructor);
1834 }
1835 }
1836
1837 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("encode_info_for_mod",
"rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(1837u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("local_def_id")
}> =
::tracing::__macro_support::FieldName::new("local_def_id");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&local_def_id)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = self.tcx;
if self.is_proc_macro {
self.table_writer().expn_that_defined(local_def_id,
tcx.expn_that_defined(local_def_id));
} else {
let module_children = tcx.module_children_local(local_def_id);
self.table_writer().module_children_non_reexports(local_def_id,
module_children.iter().filter(|child|
child.reexport_chain.is_empty()).map(|child|
child.res.def_id().expect_local()));
self.table_writer().module_children_reexports(local_def_id,
module_children.iter().filter(|child|
!child.reexport_chain.is_empty()));
let ambig_module_children =
tcx.resolutions(()).ambig_module_children.get(&local_def_id).map_or_default(|v|
&v[..]);
self.table_writer().ambig_module_children(local_def_id,
ambig_module_children);
}
}
}
}#[instrument(level = "debug", skip(self))]
1838 fn encode_info_for_mod(&mut self, local_def_id: LocalDefId) {
1839 let tcx = self.tcx;
1840
1841 if self.is_proc_macro {
1847 self.table_writer()
1849 .expn_that_defined(local_def_id, tcx.expn_that_defined(local_def_id));
1850 } else {
1851 let module_children = tcx.module_children_local(local_def_id);
1852
1853 self.table_writer().module_children_non_reexports(
1854 local_def_id,
1855 module_children
1856 .iter()
1857 .filter(|child| child.reexport_chain.is_empty())
1858 .map(|child| child.res.def_id().expect_local()),
1859 );
1860
1861 self.table_writer().module_children_reexports(
1862 local_def_id,
1863 module_children.iter().filter(|child| !child.reexport_chain.is_empty()),
1864 );
1865
1866 let ambig_module_children = tcx
1867 .resolutions(())
1868 .ambig_module_children
1869 .get(&local_def_id)
1870 .map_or_default(|v| &v[..]);
1871 self.table_writer().ambig_module_children(local_def_id, ambig_module_children);
1872 }
1873 }
1874
1875 fn encode_explicit_item_bounds(&mut self, def_id: LocalDefId) {
1876 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_metadata/src/rmeta/encoder.rs:1876",
"rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(1876u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("EncodeContext::encode_explicit_item_bounds({0:?})",
def_id) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id);
1877 let bounds = self.tcx.explicit_item_bounds(def_id).skip_binder();
1878 self.table_writer().explicit_item_bounds(def_id, bounds);
1879 }
1880
1881 fn encode_explicit_item_self_bounds(&mut self, def_id: LocalDefId) {
1882 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_metadata/src/rmeta/encoder.rs:1882",
"rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(1882u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("EncodeContext::encode_explicit_item_self_bounds({0:?})",
def_id) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("EncodeContext::encode_explicit_item_self_bounds({:?})", def_id);
1883 let bounds = self.tcx.explicit_item_self_bounds(def_id).skip_binder();
1884 self.table_writer().explicit_item_self_bounds(def_id, bounds);
1885 }
1886
1887 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("encode_info_for_assoc_item",
"rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(1887u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = self.tcx;
let item = tcx.associated_item(def_id);
if #[allow(non_exhaustive_omitted_patterns)] match item.container
{
AssocContainer::Trait | AssocContainer::TraitImpl(_) =>
true,
_ => false,
} {
self.table_writer().defaultness(def_id,
item.defaultness(tcx));
}
self.table_writer().assoc_container(def_id, item.container);
if let AssocContainer::Trait = item.container && item.is_type() {
self.encode_explicit_item_bounds(def_id);
self.encode_explicit_item_self_bounds(def_id);
if tcx.is_conditionally_const(def_id) {
self.table_writer().explicit_implied_const_bounds(def_id,
tcx.explicit_implied_const_bounds(def_id).skip_binder());
}
}
if let ty::AssocKind::Type {
data: ty::AssocTypeData::Rpitit(rpitit_info) } = item.kind {
self.table_writer().opt_rpitit_info(def_id, rpitit_info);
if #[allow(non_exhaustive_omitted_patterns)] match rpitit_info
{
ty::ImplTraitInTraitData::Trait { .. } => true,
_ => false,
} {
self.table_writer().assumed_wf_types_for_rpitit(def_id,
tcx.assumed_wf_types_for_rpitit(def_id));
self.encode_precise_capturing_args(def_id);
}
}
}
}
}#[instrument(level = "debug", skip(self))]
1888 fn encode_info_for_assoc_item(&mut self, def_id: LocalDefId) {
1889 let tcx = self.tcx;
1890 let item = tcx.associated_item(def_id);
1891
1892 if matches!(item.container, AssocContainer::Trait | AssocContainer::TraitImpl(_)) {
1893 self.table_writer().defaultness(def_id, item.defaultness(tcx));
1894 }
1895
1896 self.table_writer().assoc_container(def_id, item.container);
1897
1898 if let AssocContainer::Trait = item.container
1899 && item.is_type()
1900 {
1901 self.encode_explicit_item_bounds(def_id);
1902 self.encode_explicit_item_self_bounds(def_id);
1903 if tcx.is_conditionally_const(def_id) {
1904 self.table_writer().explicit_implied_const_bounds(
1905 def_id,
1906 tcx.explicit_implied_const_bounds(def_id).skip_binder(),
1907 );
1908 }
1909 }
1910 if let ty::AssocKind::Type { data: ty::AssocTypeData::Rpitit(rpitit_info) } = item.kind {
1911 self.table_writer().opt_rpitit_info(def_id, rpitit_info);
1912 if matches!(rpitit_info, ty::ImplTraitInTraitData::Trait { .. }) {
1913 self.table_writer()
1914 .assumed_wf_types_for_rpitit(def_id, tcx.assumed_wf_types_for_rpitit(def_id));
1915 self.encode_precise_capturing_args(def_id);
1916 }
1917 }
1918 }
1919
1920 fn encode_precise_capturing_args(&mut self, def_id: LocalDefId) {
1921 let Some(precise_capturing_args) = self.tcx.rendered_precise_capturing_args(def_id) else {
1922 return;
1923 };
1924
1925 self.table_writer().rendered_precise_capturing_args(def_id, precise_capturing_args);
1926 }
1927
1928 fn encode_mir(&mut self) {
1929 if self.is_proc_macro {
1930 return;
1931 }
1932
1933 let tcx = self.tcx;
1934 let reachable_set = tcx.reachable_set(());
1935
1936 let keys_and_jobs = tcx.mir_keys(()).iter().filter_map(|&def_id| {
1937 let (encode_const, encode_opt) = should_encode_mir(tcx, reachable_set, def_id);
1938 if encode_const || encode_opt { Some((def_id, encode_const, encode_opt)) } else { None }
1939 });
1940 for (def_id, encode_const, encode_opt) in keys_and_jobs {
1941 if true {
if !(encode_const || encode_opt) {
::core::panicking::panic("assertion failed: encode_const || encode_opt")
};
};debug_assert!(encode_const || encode_opt);
1942
1943 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_metadata/src/rmeta/encoder.rs:1943",
"rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(1943u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("EntryBuilder::encode_mir({0:?})",
def_id) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("EntryBuilder::encode_mir({:?})", def_id);
1944 if encode_opt {
1945 self.table_writer().optimized_mir(def_id, tcx.optimized_mir(def_id));
1946
1947 self.table_writer()
1948 .cross_crate_inlinable(def_id, tcx.cross_crate_inlinable(def_id));
1949
1950 self.table_writer().closure_saved_names_of_captured_variables(
1951 def_id,
1952 tcx.closure_saved_names_of_captured_variables(def_id),
1953 );
1954
1955 if tcx.is_coroutine(def_id.to_def_id())
1956 && let Some(witnesses) = tcx.mir_coroutine_witnesses(def_id)
1957 {
1958 self.table_writer().mir_coroutine_witnesses(def_id, witnesses);
1959 }
1960 }
1961 let mut is_trivial = false;
1962 if encode_const {
1963 if let Some((val, ty)) = tcx.trivial_const(def_id) {
1964 is_trivial = true;
1965 self.table_writer().trivial_const(def_id, (val, ty));
1966 } else {
1967 is_trivial = false;
1968 self.table_writer().mir_for_ctfe(def_id, tcx.mir_for_ctfe(def_id));
1969 }
1970
1971 let abstract_const = tcx.thir_abstract_const(def_id);
1973 if let Ok(Some(abstract_const)) = abstract_const {
1974 self.table_writer().thir_abstract_const(def_id, abstract_const);
1975 }
1976
1977 if should_encode_const(tcx.def_kind(def_id)) {
1978 let qualifs = tcx.mir_const_qualif(def_id);
1979 self.table_writer().mir_const_qualif(def_id, qualifs);
1980 let body = tcx.hir_maybe_body_owned_by(def_id);
1981 if let Some(body) = body {
1982 let const_data = rendered_const(tcx, &body, def_id);
1983 self.table_writer().rendered_const(def_id, const_data);
1984 }
1985 }
1986 }
1987 if !is_trivial {
1988 self.table_writer().promoted_mir(def_id, tcx.promoted_mir(def_id));
1989 }
1990
1991 if tcx.is_coroutine(def_id.to_def_id())
1992 && let Some(witnesses) = tcx.mir_coroutine_witnesses(def_id)
1993 {
1994 self.table_writer().mir_coroutine_witnesses(def_id, witnesses);
1995 }
1996 }
1997
1998 if tcx.sess.opts.output_types.should_codegen()
2002 && tcx.sess.opts.optimize != OptLevel::No
2003 && tcx.sess.opts.incremental.is_none()
2004 {
2005 for &local_def_id in tcx.mir_keys(()) {
2006 if let DefKind::AssocFn | DefKind::Fn = tcx.def_kind(local_def_id) {
2007 self.table_writer().deduced_param_attrs(
2008 local_def_id,
2009 tcx.deduced_param_attrs(local_def_id.to_def_id()),
2010 );
2011 }
2012 }
2013 }
2014 }
2015
2016 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("encode_stability",
"rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(2016u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
if self.feat.staged_api() ||
self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked
{
if let Some(stab) = self.tcx.lookup_stability(def_id) {
self.table_writer().lookup_stability(def_id, stab);
}
}
}
}
}#[instrument(level = "debug", skip(self))]
2017 fn encode_stability(&mut self, def_id: LocalDefId) {
2018 if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
2021 if let Some(stab) = self.tcx.lookup_stability(def_id) {
2022 self.table_writer().lookup_stability(def_id, stab);
2023 }
2024 }
2025 }
2026
2027 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("encode_const_stability",
"rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(2027u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
if self.feat.staged_api() ||
self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked
{
if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
self.table_writer().lookup_const_stability(def_id, stab);
}
}
}
}
}#[instrument(level = "debug", skip(self))]
2028 fn encode_const_stability(&mut self, def_id: LocalDefId) {
2029 if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
2032 if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
2033 self.table_writer().lookup_const_stability(def_id, stab);
2034 }
2035 }
2036 }
2037
2038 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("encode_default_body_stability",
"rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(2038u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
if self.feat.staged_api() ||
self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked
{
if let Some(stab) =
self.tcx.lookup_default_body_stability(def_id) {
self.table_writer().lookup_default_body_stability(def_id,
stab);
}
}
}
}
}#[instrument(level = "debug", skip(self))]
2039 fn encode_default_body_stability(&mut self, def_id: LocalDefId) {
2040 if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
2043 if let Some(stab) = self.tcx.lookup_default_body_stability(def_id) {
2044 self.table_writer().lookup_default_body_stability(def_id, stab);
2045 }
2046 }
2047 }
2048
2049 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("encode_deprecation",
"rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(2049u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
if let Some(depr) =
self.tcx.lookup_deprecation(def_id.to_def_id()) {
self.table_writer().lookup_deprecation_entry(def_id, depr);
}
}
}
}#[instrument(level = "debug", skip(self))]
2050 fn encode_deprecation(&mut self, def_id: LocalDefId) {
2051 if let Some(depr) = self.tcx.lookup_deprecation(def_id.to_def_id()) {
2052 self.table_writer().lookup_deprecation_entry(def_id, depr);
2053 }
2054 }
2055
2056 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("encode_info_for_macro",
"rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(2056u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = self.tcx;
let (_, macro_def, _) =
tcx.hir_expect_item(def_id).expect_macro();
self.table_writer().is_macro_rules(def_id, macro_def.macro_rules);
self.table_writer().macro_definition(def_id, &*macro_def.body);
}
}
}#[instrument(level = "debug", skip(self))]
2057 fn encode_info_for_macro(&mut self, def_id: LocalDefId) {
2058 let tcx = self.tcx;
2059
2060 let (_, macro_def, _) = tcx.hir_expect_item(def_id).expect_macro();
2061 self.table_writer().is_macro_rules(def_id, macro_def.macro_rules);
2062 self.table_writer().macro_definition(def_id, &*macro_def.body);
2063 }
2064
2065 fn encode_native_libraries(&mut self) -> LazyArray<NativeLib> {
2066 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2067 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
2068 self.lazy_array(used_libraries.iter())
2069 }
2070
2071 fn encode_foreign_modules(&mut self) -> LazyArray<ForeignModule> {
2072 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2073 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
2074 self.lazy_array(foreign_modules.iter().map(|(_, m)| m).cloned())
2075 }
2076
2077 fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) {
2078 let mut syntax_contexts: TableBuilder<_, _, _> = Default::default();
2079 let mut expn_data_table: TableBuilder<_, _, _> = Default::default();
2080 let mut expn_hash_table: TableBuilder<_, _, _> = Default::default();
2081
2082 HygieneEncodeContext::encode(
2083 &Rc::clone(&self.hygiene_ctxt),
2084 &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table),
2085 |(this, syntax_contexts, _, _), ctxt, ctxt_data| {
2086 let ctxt = this.syntax_context_remapping.map_id(ctxt);
2087 syntax_contexts.set_some(ctxt, this.lazy(ctxt_data));
2088 },
2089 |(this, _, expn_data_table, expn_hash_table), expn_id, expn_data, hash| {
2090 if let Some(expn_id) = expn_id.as_local() {
2091 let expn_index = this.local_expn_id_remapping.map_id(expn_id);
2092
2093 expn_data_table.set_some(expn_index, this.lazy(expn_data.expect("local expn")));
2094 expn_hash_table.set_some(expn_index, this.lazy(hash));
2095 }
2096 },
2097 );
2098
2099 (
2100 syntax_contexts.encode(&mut self.opaque),
2101 expn_data_table.encode(&mut self.opaque),
2102 expn_hash_table.encode(&mut self.opaque),
2103 )
2104 }
2105
2106 fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
2107 let is_proc_macro = self.tcx.crate_types().contains(&CrateType::ProcMacro);
2108 if is_proc_macro {
2109 let tcx = self.tcx;
2110 let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap();
2111 let proc_macro_decls_static = self.lazy(proc_macro_decls_static);
2112
2113 let stability = tcx.lookup_stability(CRATE_DEF_ID);
2114
2115 self.table_writer().def_kind(CRATE_DEF_ID, DefKind::Mod);
2116 self.table_writer().def_span(CRATE_DEF_ID, tcx.def_span(CRATE_DEF_ID.to_def_id()));
2117 self.encode_attrs(CRATE_DEF_ID);
2118 let vis = tcx.local_visibility(CRATE_DEF_ID).map_id(|mod_id| mod_id.to_local_def_id());
2119 self.table_writer().visibility(CRATE_DEF_ID, vis);
2120 if let Some(stability) = stability {
2121 self.table_writer().lookup_stability(CRATE_DEF_ID, stability);
2122 }
2123 self.encode_deprecation(CRATE_DEF_ID);
2124 if let Some(res_map) = tcx.resolutions(()).doc_link_resolutions.get(&CRATE_MOD_ID) {
2125 self.table_writer().doc_link_resolutions(CRATE_DEF_ID, res_map);
2126 }
2127 if let Some(traits) = tcx.resolutions(()).doc_link_traits_in_scope.get(&CRATE_MOD_ID) {
2128 self.table_writer().doc_link_traits_in_scope(CRATE_DEF_ID, traits);
2129 }
2130
2131 let mut macros = ::alloc::vec::Vec::new()vec![];
2132
2133 for &proc_macro in &tcx.resolutions(()).proc_macros {
2137 let id = proc_macro;
2138 let proc_macro = tcx.local_def_id_to_hir_id(proc_macro);
2139 let mut name = tcx.hir_name(proc_macro);
2140 let span = tcx.hir_span(proc_macro);
2141 let attrs = tcx.hir_attrs(proc_macro);
2144 let (macro_kind, kind) = if {
{
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(ProcMacro) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
}find_attr!(attrs, ProcMacro) {
2145 (MacroKind::Bang, ProcMacroKind::Bang { name: name.as_str().to_owned() })
2146 } else if {
{
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(ProcMacroAttribute) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
}find_attr!(attrs, ProcMacroAttribute) {
2147 (MacroKind::Attr, ProcMacroKind::Attr { name: name.as_str().to_owned() })
2148 } else if let Some((trait_name, helper_attrs)) = {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(ProcMacroDerive {
trait_name, helper_attrs }) => {
break 'done Some((trait_name, helper_attrs));
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs,
2149 ProcMacroDerive { trait_name, helper_attrs } => (trait_name, helper_attrs))
2150 {
2151 name = *trait_name;
2152 (
2153 MacroKind::Derive,
2154 ProcMacroKind::CustomDerive {
2155 trait_name: name.as_str().to_owned(),
2156 attributes: helper_attrs
2157 .iter()
2158 .map(|attr| attr.as_str().to_owned())
2159 .collect(),
2160 },
2161 )
2162 } else {
2163 ::rustc_span::macros::bug_impl(None,
format_args!("Unknown proc-macro type for item {0:?}", id),
Location::caller());bug!("Unknown proc-macro type for item {:?}", id);
2164 };
2165
2166 macros.push((id, self.lazy(kind)));
2167
2168 let mut def_key = tcx.hir_def_key(id);
2169 def_key.disambiguated_data.data = DefPathData::MacroNs(name);
2170
2171 self.table_writer().def_kind(id, DefKind::Macro(macro_kind.into()));
2172
2173 self.encode_attrs(id);
2174 self.table_writer().def_keys(id, def_key);
2175 self.table_writer().def_ident_span(id, span);
2176 self.table_writer().def_span(id, span);
2177 self.table_writer().visibility(id, ty::Visibility::Public);
2178 if let Some(stability) = stability {
2179 self.table_writer().lookup_stability(id, stability);
2180 }
2181 }
2182
2183 let macros = self.lazy_array(macros);
2184
2185 let mut proc_macro_quoted_spans = TableBuilder::default();
2186 for (i, span) in tcx.sess.proc_macro_quoted_spans() {
2187 proc_macro_quoted_spans.set_some(i, self.lazy(span));
2188 }
2189
2190 let proc_macro_quoted_spans = proc_macro_quoted_spans.encode(&mut self.opaque);
2191
2192 Some(ProcMacroData {
2193 proc_macro_decls_static,
2194 stability,
2195 macros,
2196 proc_macro_quoted_spans,
2197 })
2198 } else {
2199 None
2200 }
2201 }
2202
2203 fn encode_debugger_visualizers(&mut self) -> LazyArray<DebuggerVisualizerFile> {
2204 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2205 self.lazy_array(
2206 self.tcx
2207 .debugger_visualizers(LOCAL_CRATE)
2208 .iter()
2209 .map(DebuggerVisualizerFile::path_erased),
2214 )
2215 }
2216
2217 fn encode_crate_deps(&mut self) -> LazyArray<CrateDep> {
2218 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2219
2220 let deps = self
2221 .tcx
2222 .crates(())
2223 .iter()
2224 .map(|&cnum| {
2225 let dep = CrateDep {
2226 name: self.tcx.crate_name(cnum),
2227 hash: self.tcx.crate_hash(cnum),
2228 host_hash: self.tcx.crate_host_hash(cnum),
2229 kind: self.tcx.crate_dep_kind(cnum),
2230 is_private: self.tcx.is_private_dep(cnum),
2231 };
2232 (cnum, dep)
2233 })
2234 .collect::<Vec<_>>();
2235
2236 {
2237 let mut expected_cnum = 1;
2239 for &(n, _) in &deps {
2240 {
match (&n, &CrateNum::new(expected_cnum)) {
(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!(n, CrateNum::new(expected_cnum));
2241 expected_cnum += 1;
2242 }
2243 }
2244
2245 self.lazy_array(deps.iter().map(|(_, dep)| dep))
2250 }
2251
2252 fn encode_target_modifiers(&mut self) -> LazyArray<TargetModifier> {
2253 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2254 let tcx = self.tcx;
2255 self.lazy_array(tcx.sess.opts.gather_target_modifiers())
2256 }
2257
2258 fn encode_enabled_denied_partial_mitigations(&mut self) -> LazyArray<DeniedPartialMitigation> {
2259 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2260 let tcx = self.tcx;
2261 self.lazy_array(tcx.sess.gather_enabled_denied_partial_mitigations())
2262 }
2263
2264 fn encode_lib_features(&mut self) -> LazyArray<(Symbol, FeatureStability)> {
2265 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2266 let tcx = self.tcx;
2267 let lib_features = tcx.lib_features(LOCAL_CRATE);
2268 self.lazy_array(lib_features.to_sorted_vec())
2269 }
2270
2271 fn encode_stability_implications(&mut self) -> LazyArray<(Symbol, Symbol)> {
2272 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2273 let tcx = self.tcx;
2274 let implications = tcx.stability_implications(LOCAL_CRATE);
2275 let sorted = implications.to_sorted_stable_ord();
2276 self.lazy_array(sorted.into_iter().map(|(k, v)| (*k, *v)))
2277 }
2278
2279 fn encode_canonical_symbols(&mut self) -> LazyArray<(Symbol, LocalDefId)> {
2280 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2281 let tcx = self.tcx;
2282 let canonical_symbols = &tcx.canonical_symbols(LOCAL_CRATE);
2283 self.lazy_array(canonical_symbols.iter().map(|cs| (cs.symbol, cs.def_id.expect_local())))
2284 }
2285
2286 fn encode_diagnostic_items(&mut self) -> LazyArray<(Symbol, LocalDefId)> {
2287 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2288 let tcx = self.tcx;
2289 let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id;
2290 self.lazy_array(
2291 diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.expect_local())),
2292 )
2293 }
2294
2295 fn encode_fake_doc_items(&mut self) -> LazyArray<LocalDefId> {
2296 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2297 let tcx = self.tcx;
2298 let fake_doc_items = &tcx.fake_doc_items(LOCAL_CRATE);
2299 self.lazy_array(fake_doc_items.iter().map(|cs| cs.expect_local()))
2300 }
2301
2302 fn encode_lang_items(&mut self) -> LazyArray<(LocalDefId, LangItem)> {
2303 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2304 let lang_items = self.tcx.lang_items().iter();
2305 self.lazy_array(
2306 lang_items
2307 .filter_map(|(lang_item, def_id)| def_id.as_local().map(|id| (id, lang_item))),
2308 )
2309 }
2310
2311 fn encode_lang_items_missing(&mut self) -> LazyArray<LangItem> {
2312 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2313 let tcx = self.tcx;
2314 self.lazy_array(&tcx.lang_items().missing)
2315 }
2316
2317 fn encode_stripped_cfg_items(&mut self) -> LazyArray<StrippedCfgItem<LocalDefId>> {
2318 self.lazy_array(
2319 self.tcx
2320 .stripped_cfg_items(LOCAL_CRATE)
2321 .into_iter()
2322 .map(|item| item.clone().map_scope_id(|def_id| def_id.expect_local())),
2323 )
2324 }
2325
2326 fn encode_traits(&mut self) -> LazyArray<LocalDefId> {
2327 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2328 self.lazy_array(self.tcx.traits(LOCAL_CRATE).iter().map(|def_id| def_id.expect_local()))
2329 }
2330
2331 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("encode_impls",
"rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(2332u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set_all(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: LazyArray<TraitImpls> = loop {};
return __tracing_attr_fake_return;
}
{
if self.is_proc_macro { return LazyArray::default(); };
let tcx = self.tcx;
let mut trait_impls:
FxIndexMap<DefId,
Vec<(LocalDefId, Option<SimplifiedType>)>> =
FxIndexMap::default();
for id in tcx.hir_free_items() {
let DefKind::Impl { of_trait } =
tcx.def_kind(id.owner_id) else { continue; };
let local_id = id.owner_id.def_id;
if of_trait {
let header = tcx.impl_trait_header(local_id);
self.table_writer().impl_trait_header(local_id, header);
let impl_is_fully_generic_for_reflection =
tcx.impl_is_fully_generic_for_reflection(local_id);
self.table_writer().impl_is_fully_generic_for_reflection(local_id,
impl_is_fully_generic_for_reflection);
self.table_writer().defaultness(local_id,
tcx.defaultness(local_id));
let trait_ref =
header.trait_ref.instantiate_identity().skip_norm_wip();
let simplified_self_ty =
fast_reject::simplify_type(tcx, trait_ref.self_ty(),
TreatParams::InstantiateWithInfer);
trait_impls.entry(trait_ref.def_id).or_default().push((local_id,
simplified_self_ty));
let trait_def = tcx.trait_def(trait_ref.def_id);
if let Ok(mut an) =
trait_def.ancestors(tcx, local_id.to_def_id()) &&
let Some(specialization_graph::Node::Impl(parent)) =
an.nth(1) {
let parent =
RemappedRawDefId::create(parent,
&self.local_defs_remapping);
self.table_writer().impl_parent(local_id, parent);
}
if tcx.is_lang_item(trait_ref.def_id,
LangItem::CoerceUnsized) {
let coerce_unsized_info =
tcx.coerce_unsized_info(local_id).unwrap();
self.table_writer().coerce_unsized_info(local_id,
coerce_unsized_info);
}
}
}
let trait_impls: Vec<_> =
trait_impls.into_iter().map(|(trait_def_id, impls)|
TraitImpls {
trait_id: RemappedRawDefId::create(trait_def_id,
&self.local_defs_remapping),
impls: self.lazy_array(&impls),
}).collect();
self.lazy_array(&trait_impls)
}
}
}#[instrument(level = "debug", skip(self))]
2333 fn encode_impls(&mut self) -> LazyArray<TraitImpls> {
2334 empty_proc_macro!(self);
2335 let tcx = self.tcx;
2336 let mut trait_impls: FxIndexMap<DefId, Vec<(LocalDefId, Option<SimplifiedType>)>> =
2337 FxIndexMap::default();
2338
2339 for id in tcx.hir_free_items() {
2340 let DefKind::Impl { of_trait } = tcx.def_kind(id.owner_id) else {
2341 continue;
2342 };
2343 let local_id = id.owner_id.def_id;
2344
2345 if of_trait {
2346 let header = tcx.impl_trait_header(local_id);
2347 self.table_writer().impl_trait_header(local_id, header);
2348
2349 let impl_is_fully_generic_for_reflection =
2350 tcx.impl_is_fully_generic_for_reflection(local_id);
2351
2352 self.table_writer().impl_is_fully_generic_for_reflection(
2353 local_id,
2354 impl_is_fully_generic_for_reflection,
2355 );
2356 self.table_writer().defaultness(local_id, tcx.defaultness(local_id));
2357
2358 let trait_ref = header.trait_ref.instantiate_identity().skip_norm_wip();
2359 let simplified_self_ty = fast_reject::simplify_type(
2360 tcx,
2361 trait_ref.self_ty(),
2362 TreatParams::InstantiateWithInfer,
2363 );
2364 trait_impls
2365 .entry(trait_ref.def_id)
2366 .or_default()
2367 .push((local_id, simplified_self_ty));
2368
2369 let trait_def = tcx.trait_def(trait_ref.def_id);
2370 if let Ok(mut an) = trait_def.ancestors(tcx, local_id.to_def_id())
2371 && let Some(specialization_graph::Node::Impl(parent)) = an.nth(1)
2372 {
2373 let parent = RemappedRawDefId::create(parent, &self.local_defs_remapping);
2374 self.table_writer().impl_parent(local_id, parent);
2375 }
2376
2377 if tcx.is_lang_item(trait_ref.def_id, LangItem::CoerceUnsized) {
2380 let coerce_unsized_info = tcx.coerce_unsized_info(local_id).unwrap();
2381 self.table_writer().coerce_unsized_info(local_id, coerce_unsized_info);
2382 }
2383 }
2384 }
2385
2386 let trait_impls: Vec<_> = trait_impls
2387 .into_iter()
2388 .map(|(trait_def_id, impls)| TraitImpls {
2389 trait_id: RemappedRawDefId::create(trait_def_id, &self.local_defs_remapping),
2390 impls: self.lazy_array(&impls),
2391 })
2392 .collect();
2393
2394 self.lazy_array(&trait_impls)
2395 }
2396
2397 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("encode_incoherent_impls",
"rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(2397u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set_all(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: LazyArray<IncoherentImpls> =
loop {};
return __tracing_attr_fake_return;
}
{
if self.is_proc_macro { return LazyArray::default(); };
let tcx = self.tcx;
let all_impls: Vec<_> =
tcx.crate_inherent_impls(()).0.incoherent_impls.iter().map(|(&simp,
impls)|
IncoherentImpls {
self_ty: self.lazy(simp),
impls: self.lazy_array(impls.iter().map(|def_id| *def_id)),
}).collect();
self.lazy_array(&all_impls)
}
}
}#[instrument(level = "debug", skip(self))]
2398 fn encode_incoherent_impls(&mut self) -> LazyArray<IncoherentImpls> {
2399 empty_proc_macro!(self);
2400 let tcx = self.tcx;
2401
2402 let all_impls: Vec<_> = tcx
2403 .crate_inherent_impls(())
2404 .0
2405 .incoherent_impls
2406 .iter()
2407 .map(|(&simp, impls)| IncoherentImpls {
2408 self_ty: self.lazy(simp),
2409 impls: self.lazy_array(impls.iter().map(|def_id| *def_id)),
2410 })
2411 .collect();
2412
2413 self.lazy_array(&all_impls)
2414 }
2415
2416 fn encode_exportable_items(&mut self) -> LazyArray<LocalDefId> {
2417 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2418 self.lazy_array(
2419 self.tcx.exportable_items(LOCAL_CRATE).iter().map(|def_id| def_id.expect_local()),
2420 )
2421 }
2422
2423 fn encode_stable_order_of_exportable_impls(&mut self) -> LazyArray<(LocalDefId, usize)> {
2424 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2425 let stable_order_of_exportable_impls =
2426 self.tcx.stable_order_of_exportable_impls(LOCAL_CRATE);
2427 self.lazy_array(
2428 stable_order_of_exportable_impls
2429 .iter()
2430 .map(|(def_id, idx)| (def_id.expect_local(), *idx)),
2431 )
2432 }
2433
2434 fn encode_exported_symbols(
2441 &mut self,
2442 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportInfo)],
2443 ) -> LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)> {
2444 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2445
2446 self.lazy_array(exported_symbols.iter().cloned())
2447 }
2448
2449 fn encode_dylib_dependency_formats(&mut self) -> LazyArray<Option<LinkagePreference>> {
2450 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2451 let formats = self.tcx.dependency_formats(());
2452 if let Some(arr) = formats.get(&CrateType::Dylib) {
2453 return self.lazy_array(arr.iter().skip(1 ).map(
2454 |slot| match *slot {
2455 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
2456
2457 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
2458 Linkage::Static => Some(LinkagePreference::RequireStatic),
2459 },
2460 ));
2461 }
2462 LazyArray::default()
2463 }
2464}
2465
2466fn prefetch_mir(tcx: TyCtxt<'_>) {
2469 if !tcx.sess.opts.output_types.should_codegen() {
2470 return;
2472 }
2473
2474 let reachable_set = tcx.reachable_set(());
2475 par_for_each_in(tcx.mir_keys(()).as_slice(), |&def_id| {
2476 if tcx.is_trivial_const(def_id) {
2477 return;
2478 }
2479 let (encode_const, encode_opt) = should_encode_mir(tcx, reachable_set, def_id);
2480
2481 if encode_const {
2482 tcx.ensure_done().mir_for_ctfe(def_id);
2483 }
2484 if encode_opt {
2485 tcx.ensure_done().optimized_mir(def_id);
2486 }
2487 if encode_opt || encode_const {
2488 tcx.ensure_done().promoted_mir(def_id);
2489 }
2490 })
2491}
2492
2493pub struct EncodedMetadata {
2517 full_metadata: Option<Mmap>,
2520 stub_metadata: Option<Vec<u8>>,
2523 path: Option<Box<Path>>,
2525 _temp_dir: Option<MaybeTempDir>,
2528}
2529
2530impl EncodedMetadata {
2531 #[inline]
2532 pub fn from_path(
2533 path: PathBuf,
2534 stub_path: Option<PathBuf>,
2535 temp_dir: Option<MaybeTempDir>,
2536 ) -> std::io::Result<Self> {
2537 let file = std::fs::File::open(&path)?;
2538 let file_metadata = file.metadata()?;
2539 if file_metadata.len() == 0 {
2540 return Ok(Self {
2541 full_metadata: None,
2542 stub_metadata: None,
2543 path: None,
2544 _temp_dir: None,
2545 });
2546 }
2547 let full_mmap = unsafe { Some(Mmap::map(file)?) };
2548
2549 let stub =
2550 if let Some(stub_path) = stub_path { Some(std::fs::read(stub_path)?) } else { None };
2551
2552 Ok(Self {
2553 full_metadata: full_mmap,
2554 stub_metadata: stub,
2555 path: Some(path.into()),
2556 _temp_dir: temp_dir,
2557 })
2558 }
2559
2560 #[inline]
2561 pub fn full(&self) -> &[u8] {
2562 &self.full_metadata.as_deref().unwrap_or_default()
2563 }
2564
2565 #[inline]
2566 pub fn stub_or_full(&self) -> &[u8] {
2567 self.stub_metadata.as_deref().unwrap_or(self.full())
2568 }
2569
2570 #[inline]
2571 pub fn path(&self) -> Option<&Path> {
2572 self.path.as_deref()
2573 }
2574}
2575
2576impl<S: Encoder> Encodable<S> for EncodedMetadata {
2577 fn encode(&self, s: &mut S) {
2578 self.stub_metadata.encode(s);
2579
2580 let slice = self.full();
2581 slice.encode(s)
2582 }
2583}
2584
2585impl<D: Decoder> Decodable<D> for EncodedMetadata {
2586 fn decode(d: &mut D) -> Self {
2587 let stub = <Option<Vec<u8>>>::decode(d);
2588
2589 let len = d.read_usize();
2590 let full_metadata = if len > 0 {
2591 let mut mmap = MmapMut::map_anon(len).unwrap();
2592 mmap.copy_from_slice(d.read_raw_bytes(len));
2593 Some(mmap.make_read_only().unwrap())
2594 } else {
2595 None
2596 };
2597
2598 Self { full_metadata, stub_metadata: stub, path: None, _temp_dir: None }
2599 }
2600}
2601
2602{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("encode_metadata",
"rustc_metadata::rmeta::encoder", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(2602u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("path")
}> =
::tracing::__macro_support::FieldName::new("path");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ref_path")
}> =
::tracing::__macro_support::FieldName::new("ref_path");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ref_path)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
tcx.dep_graph.assert_ignored();
let _prof_timer =
tcx.prof.verbose_generic_activity("generate_crate_metadata");
let dep_node = tcx.metadata_dep_node();
if tcx.dep_graph.is_fully_enabled() &&
let incr_comp_session = tcx.incr_comp_session.unwrap() &&
let Some(old_incr_comp_session_dir) =
&incr_comp_session.old_session_directory &&
let work_product_id =
WorkProductId::from_cgu_name(WorkProduct::METADATA_WORKPRODUCT_CGU_NAME)
&&
let Some(work_product) =
tcx.dep_graph.previous_work_product(&work_product_id) &&
tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some() {
let saved_path =
&work_product.saved_files[OutputType::Metadata.extension()];
let source_file_in_incr_dir =
&old_incr_comp_session_dir.join(saved_path);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_metadata/src/rmeta/encoder.rs:2623",
"rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0377038f98d734a74468b6b0f48dd1a9351ed328/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(2623u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::encoder"),
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("copying preexisting metadata from {0:?} to {1:?}",
source_file_in_incr_dir, path) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};
match rustc_fs_util::link_or_copy(&source_file_in_incr_dir,
path) {
Ok(_) => {}
Err(err) =>
tcx.dcx().emit_fatal(FailCreateFileEncoder { err }),
};
let file =
std::fs::File::open(&source_file_in_incr_dir).unwrap();
let mmap = unsafe { Mmap::map(file) }.unwrap();
let owned = slice_owned(mmap, Deref::deref);
let blob = MetadataBlob::new(owned);
let hash =
blob.expect("file already created").get_crate_hash();
tcx.untracked().local_crate_hash.set(hash).expect("local_crate_hash set twice");
if let Some(ref_path) = ref_path {
let _prof_timer =
tcx.prof.verbose_generic_activity("generate_crate_metadata_stub");
with_encode_metadata_header(tcx, ref_path,
|ecx|
{
let header: LazyValue<CrateHeader> =
ecx.lazy(CrateHeader {
name: tcx.crate_name(LOCAL_CRATE),
triple: tcx.sess.opts.target_triple.clone(),
is_proc_macro_crate: false,
is_stub: true,
});
(header.position.get(), 0)
})
}
return;
};
if tcx.sess.opts.jobs.frontend.is_parallel() {
par_join(|| prefetch_mir(tcx),
||
{
let _ = tcx.exported_non_generic_symbols(LOCAL_CRATE);
let _ = tcx.exported_generic_symbols(LOCAL_CRATE);
});
}
tcx.dep_graph.with_task(dep_node, tcx,
||
{
with_encode_metadata_header(tcx, path,
|ecx|
{
let (root, unhashed) = ecx.encode_crate_root();
ecx.opaque.flush();
tcx.prof.artifact_size("crate_metadata", "crate_metadata",
ecx.opaque.file().metadata().unwrap().len());
(root.position.get(), unhashed.position.get())
})
}, None);
if let Some(ref_path) = ref_path {
let _prof_timer =
tcx.prof.verbose_generic_activity("generate_crate_metadata_stub");
with_encode_metadata_header(tcx, ref_path,
|ecx|
{
let header: LazyValue<CrateHeader> =
ecx.lazy(CrateHeader {
name: tcx.crate_name(LOCAL_CRATE),
triple: tcx.sess.opts.target_triple.clone(),
is_proc_macro_crate: false,
is_stub: true,
});
(header.position.get(), 0)
})
}
}
}
}#[instrument(level = "trace", skip(tcx))]
2603pub fn encode_metadata(tcx: TyCtxt<'_>, path: &Path, ref_path: Option<&Path>) {
2604 tcx.dep_graph.assert_ignored();
2607
2608 let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata");
2609
2610 let dep_node = tcx.metadata_dep_node();
2611
2612 if tcx.dep_graph.is_fully_enabled()
2614 && let incr_comp_session = tcx.incr_comp_session.unwrap()
2615 && let Some(old_incr_comp_session_dir) = &incr_comp_session.old_session_directory
2616 && let work_product_id =
2617 WorkProductId::from_cgu_name(WorkProduct::METADATA_WORKPRODUCT_CGU_NAME)
2618 && let Some(work_product) = tcx.dep_graph.previous_work_product(&work_product_id)
2619 && tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some()
2620 {
2621 let saved_path = &work_product.saved_files[OutputType::Metadata.extension()];
2622 let source_file_in_incr_dir = &old_incr_comp_session_dir.join(saved_path);
2623 debug!("copying preexisting metadata from {source_file_in_incr_dir:?} to {path:?}");
2624 match rustc_fs_util::link_or_copy(&source_file_in_incr_dir, path) {
2625 Ok(_) => {}
2626 Err(err) => tcx.dcx().emit_fatal(FailCreateFileEncoder { err }),
2627 };
2628
2629 let file = std::fs::File::open(&source_file_in_incr_dir).unwrap();
2631 let mmap = unsafe { Mmap::map(file) }.unwrap();
2632 let owned = slice_owned(mmap, Deref::deref);
2633 let blob = MetadataBlob::new(owned);
2634 let hash = blob.expect("file already created").get_crate_hash();
2635 tcx.untracked().local_crate_hash.set(hash).expect("local_crate_hash set twice");
2636
2637 if let Some(ref_path) = ref_path {
2639 let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata_stub");
2640
2641 with_encode_metadata_header(tcx, ref_path, |ecx| {
2642 let header: LazyValue<CrateHeader> = ecx.lazy(CrateHeader {
2643 name: tcx.crate_name(LOCAL_CRATE),
2644 triple: tcx.sess.opts.target_triple.clone(),
2645 is_proc_macro_crate: false,
2646 is_stub: true,
2647 });
2648 (header.position.get(), 0)
2649 })
2650 }
2651
2652 return;
2653 };
2654
2655 if tcx.sess.opts.jobs.frontend.is_parallel() {
2656 par_join(
2660 || prefetch_mir(tcx),
2661 || {
2662 let _ = tcx.exported_non_generic_symbols(LOCAL_CRATE);
2663 let _ = tcx.exported_generic_symbols(LOCAL_CRATE);
2664 },
2665 );
2666 }
2667
2668 tcx.dep_graph.with_task(
2671 dep_node,
2672 tcx,
2673 || {
2674 with_encode_metadata_header(tcx, path, |ecx| {
2675 let (root, unhashed) = ecx.encode_crate_root();
2678
2679 ecx.opaque.flush();
2681 tcx.prof.artifact_size(
2683 "crate_metadata",
2684 "crate_metadata",
2685 ecx.opaque.file().metadata().unwrap().len(),
2686 );
2687
2688 (root.position.get(), unhashed.position.get())
2689 })
2690 },
2691 None,
2692 );
2693
2694 if let Some(ref_path) = ref_path {
2696 let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata_stub");
2697
2698 with_encode_metadata_header(tcx, ref_path, |ecx| {
2699 let header: LazyValue<CrateHeader> = ecx.lazy(CrateHeader {
2700 name: tcx.crate_name(LOCAL_CRATE),
2701 triple: tcx.sess.opts.target_triple.clone(),
2702 is_proc_macro_crate: false,
2703 is_stub: true,
2704 });
2705 (header.position.get(), 0)
2706 })
2707 }
2708}
2709
2710fn with_encode_metadata_header(
2711 tcx: TyCtxt<'_>,
2712 path: &Path,
2713 f: impl FnOnce(&mut EncodeContext<'_, '_>) -> (usize, usize),
2714) {
2715 let metadata_crate_hash = tcx.sess.opts.unstable_opts.metadata_crate_hash;
2719 let metadata_hasher = Arc::new(Mutex::new(XxHash3_128::new()));
2724 if metadata_crate_hash {
2725 let hir_body_hash = compute_hir_hash(tcx);
2728 let supplement: Fingerprint = tcx.with_stable_hashing_context(|mut hcx| {
2729 let mut hasher = StableHasher::new();
2730 tcx.sess.opts.dep_tracking_hash(true).stable_hash(&mut hcx, &mut hasher);
2732 hir_body_hash.stable_hash(&mut hcx, &mut hasher);
2734 hasher.finish()
2735 });
2736 metadata_hasher.lock().unwrap().write(&supplement.to_le_bytes());
2737 }
2738
2739 let mut flush_strategy = {
2741 let metadata_hasher = Arc::clone(&metadata_hasher);
2742 move |bytes: &[u8]| metadata_hasher.lock().unwrap().write(bytes)
2743 };
2744
2745 let mut encoder = if metadata_crate_hash {
2746 FileEncoder::with_flush_strategy(path, &mut flush_strategy)
2747 } else {
2748 FileEncoder::new(path)
2749 }
2750 .unwrap_or_else(|err| tcx.dcx().emit_fatal(FailCreateFileEncoder { err }));
2751 encoder.emit_raw_bytes(METADATA_HEADER);
2752
2753 encoder.emit_raw_bytes(&0u64.to_le_bytes());
2755
2756 encoder.emit_raw_bytes(&0u64.to_le_bytes());
2758
2759 encoder.emit_raw_bytes(&Fingerprint::ZERO.to_le_bytes());
2761
2762 let source_map_files = tcx.sess.source_map().files();
2763 let source_file_cache = (Arc::clone(&source_map_files[0]), 0);
2764 let required_source_files = Some(FxIndexSet::default());
2765 drop(source_map_files);
2766
2767 let mut ecx = EncodeContext {
2768 opaque: encoder,
2769 metadata_hasher: Arc::clone(&metadata_hasher),
2770 tcx,
2771 feat: tcx.features(),
2772 tables: Default::default(),
2773 lazy_state: LazyState::NoNode,
2774 span_shorthands: Default::default(),
2775 type_shorthands: Default::default(),
2776 predicate_shorthands: Default::default(),
2777 source_file_cache,
2778 interpret_allocs: Default::default(),
2779 required_source_files,
2780 is_proc_macro: tcx.crate_types().contains(&CrateType::ProcMacro),
2781 hygiene_ctxt: Default::default(),
2782 symbol_index_table: Default::default(),
2783 local_defs_remapping: Default::default(),
2784 syntax_context_remapping: Default::default(),
2785 local_expn_id_remapping: Default::default(),
2786 };
2787
2788 rustc_version(tcx.sess.cfg_version).encode(&mut ecx);
2790
2791 let (root_position, unhashed_position) = f(&mut ecx);
2792
2793 if let Err((path, err)) = ecx.opaque.finish() {
2797 tcx.dcx().emit_fatal(FailWriteFile { path: &path, err });
2798 }
2799
2800 let mut file = ecx.opaque.file();
2801 let pos_before_seek = file.stream_position().unwrap();
2803
2804 if let Err(err) = encode_root_position(file, root_position) {
2805 tcx.dcx().emit_fatal(FailWriteFile { path: ecx.opaque.path(), err });
2806 }
2807
2808 if let Err(err) = encode_unhashed_position(file, unhashed_position) {
2809 tcx.dcx().emit_fatal(FailWriteFile { path: ecx.opaque.path(), err });
2810 }
2811
2812 let hash = tcx
2813 .untracked()
2814 .local_crate_hash
2815 .get()
2816 .copied()
2817 .expect("local_crate_hash set during encoding");
2818 if let Err(err) = encode_crate_hash(file, hash) {
2819 tcx.dcx().emit_fatal(FailWriteFile { path: ecx.opaque.path(), err });
2820 }
2821
2822 if let Err(err) = file.seek(SeekFrom::Start(pos_before_seek)) {
2823 tcx.dcx().emit_fatal(FailWriteFile { path: ecx.opaque.path(), err });
2824 }
2825}
2826
2827fn encode_root_position(mut file: &File, pos: usize) -> Result<(), std::io::Error> {
2828 file.seek(SeekFrom::Start(ROOT_POS_OFFSET as u64))?;
2829 file.write_all(&pos.to_le_bytes())?;
2830 Ok(())
2831}
2832
2833fn encode_unhashed_position(mut file: &File, pos: usize) -> Result<(), std::io::Error> {
2834 file.seek(SeekFrom::Start(UNHASHED_POS_OFFSET as u64))?;
2835 file.write_all(&pos.to_le_bytes())?;
2836 Ok(())
2837}
2838
2839fn encode_crate_hash(mut file: &File, hash: Svh) -> Result<(), std::io::Error> {
2840 file.seek(SeekFrom::Start(CRATE_HASH_OFFSET as u64))?;
2841 file.write_all(&hash.as_fingerprint().to_le_bytes())?;
2842 Ok(())
2843}
2844
2845pub(crate) fn provide(providers: &mut Providers) {
2846 *providers = Providers {
2847 doc_link_resolutions: |tcx, def_id| {
2848 tcx.resolutions(())
2849 .doc_link_resolutions
2850 .get(&def_id)
2851 .unwrap_or_else(|| ::rustc_span::macros::bug_impl(Some(tcx.def_span(def_id)),
format_args!("no resolutions for a doc link"), Location::caller())span_bug!(tcx.def_span(def_id), "no resolutions for a doc link"))
2852 },
2853 doc_link_traits_in_scope: |tcx, def_id| {
2854 tcx.resolutions(()).doc_link_traits_in_scope.get(&def_id).unwrap_or_else(|| {
2855 ::rustc_span::macros::bug_impl(Some(tcx.def_span(def_id)),
format_args!("no traits in scope for a doc link"), Location::caller())span_bug!(tcx.def_span(def_id), "no traits in scope for a doc link")
2856 })
2857 },
2858
2859 ..*providers
2860 }
2861}
2862
2863pub fn rendered_const<'tcx>(tcx: TyCtxt<'tcx>, body: &hir::Body<'_>, def_id: LocalDefId) -> String {
2891 let value = body.value;
2892
2893 #[derive(#[automatically_derived]impl ::core::marker::StructuralPartialEq for
Classification {
}
#[automatically_derived]impl ::core::cmp::PartialEq for Classification {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for Classification { }Eq)]
2894 enum Classification {
2895 Literal,
2896 Simple,
2897 Complex,
2898 }
2899
2900 use Classification::*;
2901
2902 fn classify(expr: &hir::Expr<'_>) -> Classification {
2903 match &expr.kind {
2904 hir::ExprKind::Unary(hir::UnOp::Neg, expr) => {
2905 if #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
hir::ExprKind::Lit(_) => true,
_ => false,
}matches!(expr.kind, hir::ExprKind::Lit(_)) { Literal } else { Complex }
2906 }
2907 hir::ExprKind::Lit(_) => Literal,
2908 hir::ExprKind::Tup([]) => Simple,
2909 hir::ExprKind::Block(hir::Block { stmts: [], expr: Some(expr), .. }, _) => {
2910 if classify(expr) == Complex { Complex } else { Simple }
2911 }
2912 hir::ExprKind::Path(hir::QPath::Resolved(_, hir::Path { segments, .. })) => {
2917 if segments.iter().all(|segment| segment.args.is_none()) { Simple } else { Complex }
2918 }
2919 hir::ExprKind::Path(hir::QPath::TypeRelative(..)) => Simple,
2922 _ => Complex,
2923 }
2924 }
2925
2926 match classify(value) {
2927 Literal
2937 if !value.span.from_expansion()
2938 && let Ok(snippet) = tcx.sess.source_map().span_to_snippet(value.span) =>
2939 {
2940 snippet
2941 }
2942
2943 Literal | Simple => id_to_string(&tcx, body.id().hir_id),
2946
2947 Complex => {
2951 if tcx.def_kind(def_id) == DefKind::AnonConst {
2952 "{ _ }".to_owned()
2953 } else {
2954 "_".to_owned()
2955 }
2956 }
2957 }
2958}