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/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/rmeta/encoder.rs:713",
"rustc_metadata::rmeta::encoder", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/65ce8611fed3142053320be6996ef00e9992671f/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/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/rmeta/encoder.rs:721",
"rustc_metadata::rmeta::encoder", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/65ce8611fed3142053320be6996ef00e9992671f/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(
1176 tcx: TyCtxt<'_>,
1177 reachable_set: Option<&LocalDefIdSet>,
1178 def_id: LocalDefId,
1179) -> (bool, bool) {
1180 {
match (&reachable_set.is_some(),
&tcx.sess.opts.output_types.should_codegen()) {
(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!(reachable_set.is_some(), tcx.sess.opts.output_types.should_codegen());
1181
1182 match tcx.def_kind(def_id) {
1183 DefKind::Ctor(_, _) => (true, false),
1185 DefKind::AnonConst | DefKind::AssocConst | DefKind::Const => (true, false),
1187 DefKind::Closure if tcx.is_coroutine(def_id.to_def_id()) => (false, true),
1189 DefKind::SyntheticCoroutineBody => (false, true),
1190 DefKind::AssocFn | DefKind::Fn | DefKind::Closure => {
1192 let opt = tcx.sess.opts.unstable_opts.always_encode_mir
1193 || (reachable_set.is_some_and(|reachable_set| reachable_set.contains(&def_id))
1194 && (tcx.generics_of(def_id).requires_monomorphization(tcx)
1195 || tcx.cross_crate_inlinable(def_id)));
1196 let opt =
1198 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 });
1199 let is_const_fn = tcx.is_const_fn(def_id.to_def_id());
1201 (is_const_fn, opt)
1202 }
1203 _ => (false, false),
1205 }
1206}
1207
1208fn should_encode_variances<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, def_kind: DefKind) -> bool {
1209 match def_kind {
1210 DefKind::Struct
1211 | DefKind::Union
1212 | DefKind::Enum
1213 | DefKind::OpaqueTy
1214 | DefKind::Fn
1215 | DefKind::Ctor(..)
1216 | DefKind::AssocFn => true,
1217 DefKind::AssocTy => {
1218 #[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 { .. }))
1220 }
1221 DefKind::Mod
1222 | DefKind::Variant
1223 | DefKind::Field
1224 | DefKind::AssocConst
1225 | DefKind::TyParam
1226 | DefKind::ConstParam
1227 | DefKind::Static { .. }
1228 | DefKind::Const
1229 | DefKind::ForeignMod
1230 | DefKind::TyAlias
1231 | DefKind::Impl { .. }
1232 | DefKind::Trait
1233 | DefKind::TraitAlias
1234 | DefKind::Macro(..)
1235 | DefKind::ForeignTy
1236 | DefKind::Use
1237 | DefKind::LifetimeParam
1238 | DefKind::AnonConst
1239 | DefKind::GlobalAsm
1240 | DefKind::Closure
1241 | DefKind::ExternCrate
1242 | DefKind::SyntheticCoroutineBody
1243 | DefKind::TestBinderConstraints => false,
1244 }
1245}
1246
1247fn should_encode_generics(def_kind: DefKind) -> bool {
1248 match def_kind {
1249 DefKind::Struct
1250 | DefKind::Union
1251 | DefKind::Enum
1252 | DefKind::Variant
1253 | DefKind::Trait
1254 | DefKind::TyAlias
1255 | DefKind::ForeignTy
1256 | DefKind::TraitAlias
1257 | DefKind::AssocTy
1258 | DefKind::Fn
1259 | DefKind::Const
1260 | DefKind::Static { .. }
1261 | DefKind::Ctor(..)
1262 | DefKind::AssocFn
1263 | DefKind::AssocConst
1264 | DefKind::AnonConst
1265 | DefKind::OpaqueTy
1266 | DefKind::Impl { .. }
1267 | DefKind::Field
1268 | DefKind::TyParam
1269 | DefKind::Closure
1270 | DefKind::SyntheticCoroutineBody => true,
1271 DefKind::Mod
1272 | DefKind::ForeignMod
1273 | DefKind::ConstParam
1274 | DefKind::Macro(..)
1275 | DefKind::Use
1276 | DefKind::LifetimeParam
1277 | DefKind::GlobalAsm
1278 | DefKind::ExternCrate
1279 | DefKind::TestBinderConstraints => false,
1280 }
1281}
1282
1283fn should_encode_type(tcx: TyCtxt<'_>, def_id: LocalDefId, def_kind: DefKind) -> bool {
1284 match def_kind {
1285 DefKind::Struct
1286 | DefKind::Union
1287 | DefKind::Enum
1288 | DefKind::Variant
1289 | DefKind::Ctor(..)
1290 | DefKind::Field
1291 | DefKind::Fn
1292 | DefKind::Const
1293 | DefKind::Static { nested: false, .. }
1294 | DefKind::TyAlias
1295 | DefKind::ForeignTy
1296 | DefKind::Impl { .. }
1297 | DefKind::AssocFn
1298 | DefKind::AssocConst
1299 | DefKind::Closure
1300 | DefKind::ConstParam
1301 | DefKind::AnonConst
1302 | DefKind::SyntheticCoroutineBody => true,
1303
1304 DefKind::OpaqueTy => {
1305 let origin = tcx.local_opaque_ty_origin(def_id);
1306 if let hir::OpaqueTyOrigin::FnReturn { parent, .. }
1307 | hir::OpaqueTyOrigin::AsyncFn { parent, .. } = origin
1308 && let hir::Node::TraitItem(trait_item) = tcx.hir_node_by_def_id(parent)
1309 && let (_, hir::TraitFn::Required(..)) = trait_item.expect_fn()
1310 {
1311 false
1312 } else {
1313 true
1314 }
1315 }
1316
1317 DefKind::AssocTy => {
1318 let assoc_item = tcx.associated_item(def_id);
1319 match assoc_item.container {
1320 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => true,
1321 ty::AssocContainer::Trait => assoc_item.defaultness(tcx).has_value(),
1322 }
1323 }
1324 DefKind::TyParam => {
1325 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!() };
1326 let hir::GenericParamKind::Type { default, .. } = param.kind else { ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller())bug!() };
1327 default.is_some()
1328 }
1329
1330 DefKind::Trait
1331 | DefKind::TraitAlias
1332 | DefKind::Mod
1333 | DefKind::ForeignMod
1334 | DefKind::Macro(..)
1335 | DefKind::Static { nested: true, .. }
1336 | DefKind::Use
1337 | DefKind::LifetimeParam
1338 | DefKind::GlobalAsm
1339 | DefKind::ExternCrate
1340 | DefKind::TestBinderConstraints => false,
1341 }
1342}
1343
1344fn should_encode_fn_sig(def_kind: DefKind) -> bool {
1345 match def_kind {
1346 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) => true,
1347
1348 DefKind::Struct
1349 | DefKind::Union
1350 | DefKind::Enum
1351 | DefKind::Variant
1352 | DefKind::Field
1353 | DefKind::Const
1354 | DefKind::Static { .. }
1355 | DefKind::Ctor(..)
1356 | DefKind::TyAlias
1357 | DefKind::OpaqueTy
1358 | DefKind::ForeignTy
1359 | DefKind::Impl { .. }
1360 | DefKind::AssocConst
1361 | DefKind::Closure
1362 | DefKind::ConstParam
1363 | DefKind::AnonConst
1364 | DefKind::AssocTy
1365 | DefKind::TyParam
1366 | DefKind::Trait
1367 | DefKind::TraitAlias
1368 | DefKind::Mod
1369 | DefKind::ForeignMod
1370 | DefKind::Macro(..)
1371 | DefKind::Use
1372 | DefKind::LifetimeParam
1373 | DefKind::GlobalAsm
1374 | DefKind::ExternCrate
1375 | DefKind::SyntheticCoroutineBody
1376 | DefKind::TestBinderConstraints => false,
1377 }
1378}
1379
1380fn should_encode_constness(def_kind: DefKind) -> bool {
1381 match def_kind {
1382 DefKind::Fn
1383 | DefKind::AssocFn
1384 | DefKind::Closure
1385 | DefKind::Ctor(_, CtorKind::Fn)
1386 | DefKind::Impl { of_trait: false } => true,
1387
1388 DefKind::Struct
1389 | DefKind::Union
1390 | DefKind::Enum
1391 | DefKind::Field
1392 | DefKind::Const
1393 | DefKind::AssocConst
1394 | DefKind::AnonConst
1395 | DefKind::Static { .. }
1396 | DefKind::TyAlias
1397 | DefKind::OpaqueTy
1398 | DefKind::Impl { .. }
1399 | DefKind::ForeignTy
1400 | DefKind::ConstParam
1401 | DefKind::AssocTy
1402 | DefKind::TyParam
1403 | DefKind::Trait
1404 | DefKind::TraitAlias
1405 | DefKind::Mod
1406 | DefKind::ForeignMod
1407 | DefKind::Macro(..)
1408 | DefKind::Use
1409 | DefKind::LifetimeParam
1410 | DefKind::GlobalAsm
1411 | DefKind::ExternCrate
1412 | DefKind::Ctor(_, CtorKind::Const)
1413 | DefKind::Variant
1414 | DefKind::SyntheticCoroutineBody
1415 | DefKind::TestBinderConstraints => false,
1416 }
1417}
1418
1419fn should_encode_const(def_kind: DefKind) -> bool {
1420 match def_kind {
1421 DefKind::Const | DefKind::AssocConst | DefKind::AnonConst => true,
1423
1424 DefKind::Struct
1425 | DefKind::Union
1426 | DefKind::Enum
1427 | DefKind::Variant
1428 | DefKind::Ctor(..)
1429 | DefKind::Field
1430 | DefKind::Fn
1431 | DefKind::Static { .. }
1432 | DefKind::TyAlias
1433 | DefKind::OpaqueTy
1434 | DefKind::ForeignTy
1435 | DefKind::Impl { .. }
1436 | DefKind::AssocFn
1437 | DefKind::Closure
1438 | DefKind::ConstParam
1439 | DefKind::AssocTy
1440 | DefKind::TyParam
1441 | DefKind::Trait
1442 | DefKind::TraitAlias
1443 | DefKind::Mod
1444 | DefKind::ForeignMod
1445 | DefKind::Macro(..)
1446 | DefKind::Use
1447 | DefKind::LifetimeParam
1448 | DefKind::GlobalAsm
1449 | DefKind::ExternCrate
1450 | DefKind::SyntheticCoroutineBody
1451 | DefKind::TestBinderConstraints => false,
1452 }
1453}
1454
1455impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1456 fn encode_attrs(&mut self, def_id: LocalDefId) {
1457 let tcx = self.tcx;
1458 let mut state = AnalyzeAttrState {
1459 is_exported: tcx.effective_visibilities(()).is_exported(def_id),
1460 is_doc_hidden: false,
1461 };
1462 let attr_iter = tcx
1463 .hir_attrs(tcx.local_def_id_to_hir_id(def_id))
1464 .iter()
1465 .filter(|attr| analyze_attr(*attr, &mut state));
1466
1467 self.table_writer().attributes(def_id, attr_iter);
1468
1469 let mut attr_flags = AttrFlags::empty();
1470 if state.is_doc_hidden {
1471 attr_flags |= AttrFlags::IS_DOC_HIDDEN;
1472 }
1473
1474 self.table_writer().attr_flags(def_id, attr_flags);
1475 }
1476
1477 fn table_writer(&mut self) -> super::TableWriter<'a, 'tcx, '_> {
1483 super::TableWriter { encoder: self }
1484 }
1485
1486 fn encode_def_ids(&mut self) {
1487 self.encode_info_for_mod(CRATE_DEF_ID);
1488
1489 if self.is_proc_macro {
1492 return;
1493 }
1494
1495 let tcx = self.tcx;
1496 for local_id in self.local_defs_remapping.iter_sorted_local_ids() {
1497 let def_id = local_id.to_def_id();
1498 let def_kind = tcx.def_kind(local_id);
1499 self.table_writer().def_kind(local_id, def_kind);
1500
1501 if def_kind == DefKind::AnonConst
1507 && #[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!(
1508 tcx.hir_node_by_def_id(local_id),
1509 hir::Node::ConstArg(_)
1510 | hir::Node::Infer(hir::InferArg { kind: hir::InferArgKind::Const, .. })
1511 )
1512 {
1513 continue;
1514 }
1515
1516 if def_kind == DefKind::Field
1517 && let hir::Node::Field(field) = tcx.hir_node_by_def_id(local_id)
1518 && let Some(anon) = field.default
1519 {
1520 self.table_writer().default_fields(local_id, anon.def_id.to_def_id());
1521 }
1522
1523 if should_encode_span(def_kind) {
1524 let def_span = tcx.def_span(local_id);
1525 self.table_writer().def_span(local_id, def_span);
1526 }
1527 if should_encode_attrs(def_kind) {
1528 self.encode_attrs(local_id);
1529 }
1530 if should_encode_expn_that_defined(def_kind) {
1531 self.table_writer().expn_that_defined(local_id, tcx.expn_that_defined(def_id));
1532 }
1533 if should_encode_span(def_kind)
1534 && let Some(ident_span) = tcx.def_ident_span(def_id)
1535 {
1536 self.table_writer().def_ident_span(local_id, ident_span);
1537 }
1538 if def_kind.has_codegen_attrs() {
1539 self.table_writer().codegen_fn_attrs(local_id, tcx.codegen_fn_attrs(def_id));
1540 }
1541 if should_encode_visibility(def_kind) {
1542 let vis = tcx.local_visibility(local_id).map_id(|mod_id| mod_id.to_local_def_id());
1543 self.table_writer().visibility(local_id, vis);
1544 }
1545 if should_encode_stability(def_kind) {
1546 self.encode_stability(local_id);
1547 self.encode_const_stability(local_id);
1548 self.encode_default_body_stability(local_id);
1549 self.encode_deprecation(local_id);
1550 }
1551 if should_encode_variances(tcx, def_id, def_kind) {
1552 let v = tcx.variances_of(def_id);
1553 self.table_writer().variances_of(local_id, v);
1554 }
1555 if should_encode_fn_sig(def_kind) {
1556 self.table_writer().fn_sig(local_id, tcx.fn_sig(def_id));
1557 }
1558 if should_encode_generics(def_kind) {
1559 let g = tcx.generics_of(def_id);
1560 self.table_writer().generics_of(local_id, g);
1561 self.table_writer().explicit_clauses_of(local_id, tcx.explicit_clauses_of(def_id));
1562 let inferred_outlives = tcx.inferred_outlives_of(def_id);
1563 self.table_writer().inferred_outlives_of(local_id, inferred_outlives);
1564
1565 for param in &g.own_params {
1566 if let ty::GenericParamDefKind::Const { has_default: true, .. } = param.kind {
1567 let default = tcx.const_param_default(param.def_id);
1568 self.table_writer()
1569 .const_param_default(param.def_id.expect_local(), default);
1570 }
1571 }
1572 }
1573 if tcx.is_conditionally_const(def_id) {
1574 self.table_writer().const_conditions(local_id, tcx.const_conditions(def_id));
1575 }
1576 if should_encode_type(tcx, local_id, def_kind) {
1577 self.table_writer().type_of(local_id, tcx.type_of(def_id));
1578 }
1579 if should_encode_constness(def_kind) {
1580 let constness = tcx.constness(def_id);
1581 self.table_writer().constness(local_id, constness);
1582 }
1583 if let DefKind::Fn | DefKind::AssocFn = def_kind {
1584 let asyncness = tcx.asyncness(def_id);
1585 self.table_writer().asyncness(local_id, asyncness);
1586 self.table_writer().fn_arg_idents(local_id, tcx.fn_arg_idents(def_id));
1587 }
1588 self.table_writer().intrinsic(local_id, tcx.intrinsic(def_id));
1589 if let DefKind::TyParam | DefKind::Trait = def_kind {
1590 let default = tcx.object_lifetime_default(def_id);
1591 self.table_writer().object_lifetime_default(local_id, default);
1592 }
1593 if let DefKind::Trait = def_kind {
1594 self.table_writer().trait_def(local_id, tcx.trait_def(def_id));
1595 self.table_writer().explicit_super_clauses_of(
1596 local_id,
1597 tcx.explicit_super_clauses_of(def_id).skip_binder(),
1598 );
1599 self.table_writer().explicit_implied_clauses_of(
1600 local_id,
1601 tcx.explicit_implied_clauses_of(def_id).skip_binder(),
1602 );
1603 let module_children = tcx.module_children_local(local_id);
1604 self.table_writer().module_children_non_reexports(
1605 local_id,
1606 module_children.iter().map(|child| child.res.def_id().expect_local()),
1607 );
1608 if tcx.is_const_trait(def_id) {
1609 self.table_writer().explicit_implied_const_bounds(
1610 local_id,
1611 tcx.explicit_implied_const_bounds(def_id).skip_binder(),
1612 );
1613 }
1614 }
1615 if let DefKind::TraitAlias = def_kind {
1616 self.table_writer().trait_def(local_id, tcx.trait_def(def_id));
1617 self.table_writer().explicit_super_clauses_of(
1618 local_id,
1619 tcx.explicit_super_clauses_of(def_id).skip_binder(),
1620 );
1621 self.table_writer().explicit_implied_clauses_of(
1622 local_id,
1623 tcx.explicit_implied_clauses_of(def_id).skip_binder(),
1624 );
1625 }
1626 if let DefKind::Trait | DefKind::Impl { .. } = def_kind {
1627 let associated_item_def_ids = tcx.associated_item_def_ids(def_id);
1628 self.table_writer().associated_item_or_field_def_ids(
1629 local_id,
1630 associated_item_def_ids.iter().map(|&def_id| def_id.expect_local()),
1631 );
1632 for &def_id in associated_item_def_ids {
1633 self.encode_info_for_assoc_item(def_id.expect_local());
1634 }
1635 }
1636 if let DefKind::Closure | DefKind::SyntheticCoroutineBody = def_kind
1637 && let Some(coroutine_kind) = tcx.coroutine_kind(def_id)
1638 {
1639 self.table_writer().coroutine_kind(local_id, coroutine_kind);
1640 }
1641 if def_kind == DefKind::Closure
1642 && tcx.type_of(def_id).skip_binder().is_coroutine_closure()
1643 {
1644 let coroutine_for_closure = tcx.coroutine_for_closure(def_id);
1645 let remapped_id =
1646 RemappedRawDefId::create(coroutine_for_closure, &self.local_defs_remapping);
1647
1648 self.table_writer().coroutine_for_closure(local_id, remapped_id);
1649
1650 if tcx.needs_coroutine_by_move_body_def_id(coroutine_for_closure) {
1652 let id = tcx.coroutine_by_move_body_def_id(coroutine_for_closure);
1653 let id = RemappedRawDefId::create(id, &self.local_defs_remapping);
1654
1655 self.table_writer()
1656 .coroutine_by_move_body_def_id(coroutine_for_closure.expect_local(), id);
1657 }
1658 }
1659 if let DefKind::Static { .. } = def_kind {
1660 if !tcx.is_foreign_item(def_id) {
1661 match tcx.eval_static_initializer(def_id) {
1662 Ok(data) => {
1663 self.table_writer().eval_static_initializer(local_id, data);
1664 }
1665 Err(err) => match err {
1666 interpret::ErrorHandled::Reported(_, _) => {
1667 tcx.dcx().delayed_bug(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("eval_static_initializer returned an error in metadata emission"))
})format!(
1668 "eval_static_initializer returned an error in metadata emission"
1669 ));
1670 }
1671 interpret::ErrorHandled::TooGeneric(span) => {
1672 ::rustc_span::macros::bug_impl(Some(span), format_args!("generic static???"),
Location::caller());span_bug!(span, "generic static???");
1673 }
1674 },
1675 };
1676 }
1677 }
1678 if let DefKind::Enum | DefKind::Struct | DefKind::Union = def_kind {
1679 self.encode_info_for_adt(local_id);
1680 }
1681 if let DefKind::Mod = def_kind {
1682 self.encode_info_for_mod(local_id);
1683 }
1684 if let DefKind::Macro(_) = def_kind {
1685 self.encode_info_for_macro(local_id);
1686 }
1687 if let DefKind::TyAlias = def_kind {
1688 self.table_writer()
1689 .type_alias_is_checked(local_id, tcx.type_alias_is_checked(def_id));
1690
1691 if tcx.type_alias_is_checked(def_id) {
1692 self.table_writer().args_known_to_outlive_alias_params(
1693 local_id,
1694 tcx.args_known_to_outlive_alias_params(def_id),
1695 );
1696 }
1697 }
1698 if let DefKind::OpaqueTy = def_kind {
1699 self.encode_explicit_item_bounds(local_id);
1700 self.encode_explicit_item_self_bounds(local_id);
1701 self.table_writer().opaque_ty_origin(local_id, tcx.opaque_ty_origin(def_id));
1702 self.encode_precise_capturing_args(local_id);
1703 if tcx.is_conditionally_const(def_id) {
1704 self.table_writer().explicit_implied_const_bounds(
1705 local_id,
1706 tcx.explicit_implied_const_bounds(def_id).skip_binder(),
1707 );
1708 }
1709 self.table_writer().args_known_to_outlive_alias_params(
1710 local_id,
1711 tcx.args_known_to_outlive_alias_params(def_id),
1712 );
1713 }
1714 if let DefKind::AssocTy = def_kind {
1715 let assoc_item = tcx.associated_item(def_id);
1716 match assoc_item.container {
1717 ty::AssocContainer::Trait => {
1718 self.table_writer().args_known_to_outlive_alias_params(
1719 local_id,
1720 tcx.args_known_to_outlive_alias_params(def_id),
1721 );
1722 }
1723 ty::AssocContainer::InherentImpl => {
1724 self.table_writer().args_known_to_outlive_alias_params(
1725 local_id,
1726 tcx.args_known_to_outlive_alias_params(def_id),
1727 );
1728 }
1729 ty::AssocContainer::TraitImpl(_) => {}
1730 }
1731 }
1732 if let DefKind::AnonConst = def_kind {
1733 self.table_writer().anon_const_kind(local_id, tcx.anon_const_kind(def_id));
1734 }
1735 if let DefKind::Const | DefKind::AssocConst = def_kind {
1736 self.table_writer().const_of_item(local_id, tcx.const_of_item(def_id));
1737 }
1738 if tcx.impl_method_has_trait_impl_trait_tys(def_id)
1739 && let Ok(table) = tcx.collect_return_position_impl_trait_in_trait_tys(def_id)
1740 {
1741 self.table_writer()
1742 .collect_return_position_impl_trait_in_trait_tys(local_id, table);
1743 }
1744 if let DefKind::Impl { .. } | DefKind::Trait = def_kind {
1745 let table = tcx.associated_types_for_impl_traits_in_trait_or_impl(def_id);
1746 self.table_writer()
1747 .associated_types_for_impl_traits_in_trait_or_impl(local_id, table);
1748 }
1749 }
1750
1751 for (def_id, impls) in &tcx.crate_inherent_impls(()).0.inherent_impls {
1752 self.table_writer()
1753 .inherent_impls(*def_id, impls.iter().map(|def_id| def_id.expect_local()));
1754 }
1755
1756 for (def_id, res_map) in &tcx.resolutions(()).doc_link_resolutions {
1757 self.table_writer().doc_link_resolutions(def_id.to_local_def_id(), res_map);
1758 }
1759
1760 for (def_id, traits) in &tcx.resolutions(()).doc_link_traits_in_scope {
1761 self.table_writer().doc_link_traits_in_scope(def_id.to_local_def_id(), traits);
1762 }
1763 }
1764
1765 fn encode_externally_implementable_items(&mut self) -> LazyArray<EiiMapEncodedKeyValue> {
1766 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
1767 let externally_implementable_items = self.tcx.externally_implementable_items(LOCAL_CRATE);
1768
1769 self.lazy_array(externally_implementable_items.iter().map(
1770 |(foreign_item, (decl, impls))| {
1771 (
1772 *foreign_item,
1773 (decl.clone(), impls.iter().map(|(impl_did, i)| (*impl_did, *i)).collect()),
1774 )
1775 },
1776 ))
1777 }
1778
1779 {}
#[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/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(1779u32),
::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))]
1780 fn encode_info_for_adt(&mut self, local_def_id: LocalDefId) {
1781 let def_id = local_def_id.to_def_id();
1782 let tcx = self.tcx;
1783 let adt_def = tcx.adt_def(def_id);
1784 self.table_writer().repr_options(local_def_id, adt_def.repr());
1785
1786 let params_in_repr = tcx.params_in_repr(def_id);
1787 self.table_writer().params_in_repr(local_def_id, params_in_repr);
1788
1789 if adt_def.is_enum() {
1790 let module_children = tcx.module_children_local(local_def_id);
1791 self.table_writer().module_children_non_reexports(
1792 local_def_id,
1793 module_children.iter().map(|child| child.res.def_id().expect_local()),
1794 );
1795 } else {
1796 debug_assert_eq!(adt_def.variants().len(), 1);
1798 debug_assert_eq!(adt_def.non_enum_variant().def_id, def_id);
1799 }
1801
1802 for (idx, variant) in adt_def.variants().iter_enumerated() {
1803 let variant_id = variant.def_id.expect_local();
1804
1805 let data = VariantData {
1806 discr: variant.discr,
1807 idx,
1808 ctor: variant.ctor.map(|(kind, def_id)| (kind, def_id.expect_local())),
1809 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1810 };
1811 self.table_writer().variant_data(variant_id, data);
1812
1813 self.table_writer().associated_item_or_field_def_ids(
1814 variant_id,
1815 variant.fields.iter().map(|f| f.did.expect_local()),
1816 );
1817
1818 for field in &variant.fields {
1819 let field_id = field.did.expect_local();
1820 self.table_writer().safety(field_id, field.safety);
1821 self.table_writer().mut_restriction(field_id, field.mut_restriction);
1822 }
1823
1824 if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor {
1825 let fn_sig = tcx.fn_sig(ctor_def_id);
1826 self.table_writer().fn_sig(variant_id, fn_sig);
1828 }
1829 }
1830
1831 if let Some(destructor) = tcx.adt_destructor(local_def_id) {
1832 self.table_writer().adt_destructor(local_def_id, destructor);
1833 }
1834
1835 if let Some(destructor) = tcx.adt_async_destructor(local_def_id) {
1836 self.table_writer().adt_async_destructor(local_def_id, destructor);
1837 }
1838 }
1839
1840 {}
#[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/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(1840u32),
::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))]
1841 fn encode_info_for_mod(&mut self, local_def_id: LocalDefId) {
1842 let tcx = self.tcx;
1843
1844 if self.is_proc_macro {
1850 self.table_writer()
1852 .expn_that_defined(local_def_id, tcx.expn_that_defined(local_def_id));
1853 } else {
1854 let module_children = tcx.module_children_local(local_def_id);
1855
1856 self.table_writer().module_children_non_reexports(
1857 local_def_id,
1858 module_children
1859 .iter()
1860 .filter(|child| child.reexport_chain.is_empty())
1861 .map(|child| child.res.def_id().expect_local()),
1862 );
1863
1864 self.table_writer().module_children_reexports(
1865 local_def_id,
1866 module_children.iter().filter(|child| !child.reexport_chain.is_empty()),
1867 );
1868
1869 let ambig_module_children = tcx
1870 .resolutions(())
1871 .ambig_module_children
1872 .get(&local_def_id)
1873 .map_or_default(|v| &v[..]);
1874 self.table_writer().ambig_module_children(local_def_id, ambig_module_children);
1875 }
1876 }
1877
1878 fn encode_explicit_item_bounds(&mut self, def_id: LocalDefId) {
1879 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/rmeta/encoder.rs:1879",
"rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(1879u32),
::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);
1880 let bounds = self.tcx.explicit_item_bounds(def_id).skip_binder();
1881 self.table_writer().explicit_item_bounds(def_id, bounds);
1882 }
1883
1884 fn encode_explicit_item_self_bounds(&mut self, def_id: LocalDefId) {
1885 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/rmeta/encoder.rs:1885",
"rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(1885u32),
::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);
1886 let bounds = self.tcx.explicit_item_self_bounds(def_id).skip_binder();
1887 self.table_writer().explicit_item_self_bounds(def_id, bounds);
1888 }
1889
1890 {}
#[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/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(1890u32),
::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 Some(item_name) = item.opt_name() {
self.table_writer().opt_item_name(def_id, Some(item_name));
}
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))]
1891 fn encode_info_for_assoc_item(&mut self, def_id: LocalDefId) {
1892 let tcx = self.tcx;
1893 let item = tcx.associated_item(def_id);
1894
1895 if matches!(item.container, AssocContainer::Trait | AssocContainer::TraitImpl(_)) {
1896 self.table_writer().defaultness(def_id, item.defaultness(tcx));
1897 }
1898
1899 self.table_writer().assoc_container(def_id, item.container);
1900
1901 if let Some(item_name) = item.opt_name() {
1902 self.table_writer().opt_item_name(def_id, Some(item_name));
1903 }
1904
1905 if let AssocContainer::Trait = item.container
1906 && item.is_type()
1907 {
1908 self.encode_explicit_item_bounds(def_id);
1909 self.encode_explicit_item_self_bounds(def_id);
1910 if tcx.is_conditionally_const(def_id) {
1911 self.table_writer().explicit_implied_const_bounds(
1912 def_id,
1913 tcx.explicit_implied_const_bounds(def_id).skip_binder(),
1914 );
1915 }
1916 }
1917 if let ty::AssocKind::Type { data: ty::AssocTypeData::Rpitit(rpitit_info) } = item.kind {
1918 self.table_writer().opt_rpitit_info(def_id, rpitit_info);
1919 if matches!(rpitit_info, ty::ImplTraitInTraitData::Trait { .. }) {
1920 self.table_writer()
1921 .assumed_wf_types_for_rpitit(def_id, tcx.assumed_wf_types_for_rpitit(def_id));
1922 self.encode_precise_capturing_args(def_id);
1923 }
1924 }
1925 }
1926
1927 fn encode_precise_capturing_args(&mut self, def_id: LocalDefId) {
1928 let Some(precise_capturing_args) = self.tcx.rendered_precise_capturing_args(def_id) else {
1929 return;
1930 };
1931
1932 self.table_writer().rendered_precise_capturing_args(def_id, precise_capturing_args);
1933 }
1934
1935 fn encode_mir(&mut self) {
1936 if self.is_proc_macro {
1937 return;
1938 }
1939
1940 let tcx = self.tcx;
1941 let reachable_set =
1944 tcx.sess.opts.output_types.should_codegen().then(|| tcx.reachable_set(()));
1945
1946 let keys_and_jobs = tcx.mir_keys(()).iter().filter_map(|&def_id| {
1947 let (encode_const, encode_opt) = should_encode_mir(tcx, reachable_set, def_id);
1948 if encode_const || encode_opt { Some((def_id, encode_const, encode_opt)) } else { None }
1949 });
1950 for (def_id, encode_const, encode_opt) in keys_and_jobs {
1951 if true {
if !(encode_const || encode_opt) {
::core::panicking::panic("assertion failed: encode_const || encode_opt")
};
};debug_assert!(encode_const || encode_opt);
1952
1953 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/rmeta/encoder.rs:1953",
"rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(1953u32),
::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);
1954 if encode_opt {
1955 self.table_writer().optimized_mir(def_id, tcx.optimized_mir(def_id));
1956
1957 self.table_writer()
1958 .cross_crate_inlinable(def_id, tcx.cross_crate_inlinable(def_id));
1959
1960 self.table_writer().closure_saved_names_of_captured_variables(
1961 def_id,
1962 tcx.closure_saved_names_of_captured_variables(def_id),
1963 );
1964
1965 if tcx.is_coroutine(def_id.to_def_id())
1966 && let Some(witnesses) = tcx.mir_coroutine_witnesses(def_id)
1967 {
1968 self.table_writer().mir_coroutine_witnesses(def_id, witnesses);
1969 }
1970 }
1971 let mut is_trivial = false;
1972 if encode_const {
1973 if let Some((val, ty)) = tcx.trivial_const(def_id) {
1974 is_trivial = true;
1975 self.table_writer().trivial_const(def_id, (val, ty));
1976 } else {
1977 is_trivial = false;
1978 self.table_writer().mir_for_ctfe(def_id, tcx.mir_for_ctfe(def_id));
1979 }
1980
1981 let abstract_const = tcx.thir_abstract_const(def_id);
1983 if let Ok(Some(abstract_const)) = abstract_const {
1984 self.table_writer().thir_abstract_const(def_id, abstract_const);
1985 }
1986
1987 if should_encode_const(tcx.def_kind(def_id)) {
1988 let qualifs = tcx.mir_const_qualif(def_id);
1989 self.table_writer().mir_const_qualif(def_id, qualifs);
1990 let body = tcx.hir_maybe_body_owned_by(def_id);
1991 if let Some(body) = body {
1992 let const_data = rendered_const(tcx, &body, def_id);
1993 self.table_writer().rendered_const(def_id, const_data);
1994 }
1995 }
1996 }
1997 if !is_trivial {
1998 self.table_writer().promoted_mir(def_id, tcx.promoted_mir(def_id));
1999 }
2000
2001 if tcx.is_coroutine(def_id.to_def_id())
2002 && let Some(witnesses) = tcx.mir_coroutine_witnesses(def_id)
2003 {
2004 self.table_writer().mir_coroutine_witnesses(def_id, witnesses);
2005 }
2006 }
2007
2008 if tcx.sess.opts.output_types.should_codegen()
2012 && tcx.sess.opts.optimize != OptLevel::No
2013 && tcx.sess.opts.incremental.is_none()
2014 {
2015 for &local_def_id in tcx.mir_keys(()) {
2016 if let DefKind::AssocFn | DefKind::Fn = tcx.def_kind(local_def_id) {
2017 self.table_writer().deduced_param_attrs(
2018 local_def_id,
2019 tcx.deduced_param_attrs(local_def_id.to_def_id()),
2020 );
2021 }
2022 }
2023 }
2024 }
2025
2026 {}
#[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/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(2026u32),
::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))]
2027 fn encode_stability(&mut self, def_id: LocalDefId) {
2028 if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
2031 if let Some(stab) = self.tcx.lookup_stability(def_id) {
2032 self.table_writer().lookup_stability(def_id, stab);
2033 }
2034 }
2035 }
2036
2037 {}
#[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/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(2037u32),
::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))]
2038 fn encode_const_stability(&mut self, def_id: LocalDefId) {
2039 if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
2042 if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
2043 self.table_writer().lookup_const_stability(def_id, stab);
2044 }
2045 }
2046 }
2047
2048 {}
#[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/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(2048u32),
::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))]
2049 fn encode_default_body_stability(&mut self, def_id: LocalDefId) {
2050 if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
2053 if let Some(stab) = self.tcx.lookup_default_body_stability(def_id) {
2054 self.table_writer().lookup_default_body_stability(def_id, stab);
2055 }
2056 }
2057 }
2058
2059 {}
#[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/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(2059u32),
::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))]
2060 fn encode_deprecation(&mut self, def_id: LocalDefId) {
2061 if let Some(depr) = self.tcx.lookup_deprecation(def_id.to_def_id()) {
2062 self.table_writer().lookup_deprecation_entry(def_id, depr);
2063 }
2064 }
2065
2066 {}
#[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/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(2066u32),
::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))]
2067 fn encode_info_for_macro(&mut self, def_id: LocalDefId) {
2068 let tcx = self.tcx;
2069
2070 let (_, macro_def, _) = tcx.hir_expect_item(def_id).expect_macro();
2071 self.table_writer().is_macro_rules(def_id, macro_def.macro_rules);
2072 self.table_writer().macro_definition(def_id, &*macro_def.body);
2073 }
2074
2075 fn encode_native_libraries(&mut self) -> LazyArray<NativeLib> {
2076 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2077 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
2078 self.lazy_array(used_libraries.iter())
2079 }
2080
2081 fn encode_foreign_modules(&mut self) -> LazyArray<ForeignModule> {
2082 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2083 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
2084 self.lazy_array(foreign_modules.iter().map(|(_, m)| m).cloned())
2085 }
2086
2087 fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) {
2088 let mut syntax_contexts: TableBuilder<_, _, _> = Default::default();
2089 let mut expn_data_table: TableBuilder<_, _, _> = Default::default();
2090 let mut expn_hash_table: TableBuilder<_, _, _> = Default::default();
2091
2092 HygieneEncodeContext::encode(
2093 &Rc::clone(&self.hygiene_ctxt),
2094 &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table),
2095 |(this, syntax_contexts, _, _), ctxt, ctxt_data| {
2096 let ctxt = this.syntax_context_remapping.map_id(ctxt);
2097 syntax_contexts.set_some(ctxt, this.lazy(ctxt_data));
2098 },
2099 |(this, _, expn_data_table, expn_hash_table), expn_id, expn_data, hash| {
2100 if let Some(expn_id) = expn_id.as_local() {
2101 let expn_index = this.local_expn_id_remapping.map_id(expn_id);
2102
2103 expn_data_table.set_some(expn_index, this.lazy(expn_data.expect("local expn")));
2104 expn_hash_table.set_some(expn_index, this.lazy(hash));
2105 }
2106 },
2107 );
2108
2109 (
2110 syntax_contexts.encode(&mut self.opaque),
2111 expn_data_table.encode(&mut self.opaque),
2112 expn_hash_table.encode(&mut self.opaque),
2113 )
2114 }
2115
2116 fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
2117 let is_proc_macro = self.tcx.crate_types().contains(&CrateType::ProcMacro);
2118 if is_proc_macro {
2119 let tcx = self.tcx;
2120 let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap();
2121 let proc_macro_decls_static = self.lazy(proc_macro_decls_static);
2122
2123 let stability = tcx.lookup_stability(CRATE_DEF_ID);
2124
2125 self.table_writer().def_kind(CRATE_DEF_ID, DefKind::Mod);
2126 self.table_writer().def_span(CRATE_DEF_ID, tcx.def_span(CRATE_DEF_ID.to_def_id()));
2127 self.encode_attrs(CRATE_DEF_ID);
2128 let vis = tcx.local_visibility(CRATE_DEF_ID).map_id(|mod_id| mod_id.to_local_def_id());
2129 self.table_writer().visibility(CRATE_DEF_ID, vis);
2130 if let Some(stability) = stability {
2131 self.table_writer().lookup_stability(CRATE_DEF_ID, stability);
2132 }
2133 self.encode_deprecation(CRATE_DEF_ID);
2134 if let Some(res_map) = tcx.resolutions(()).doc_link_resolutions.get(&CRATE_MOD_ID) {
2135 self.table_writer().doc_link_resolutions(CRATE_DEF_ID, res_map);
2136 }
2137 if let Some(traits) = tcx.resolutions(()).doc_link_traits_in_scope.get(&CRATE_MOD_ID) {
2138 self.table_writer().doc_link_traits_in_scope(CRATE_DEF_ID, traits);
2139 }
2140
2141 let mut macros = ::alloc::vec::Vec::new()vec![];
2142
2143 for &proc_macro in &tcx.resolutions(()).proc_macros {
2147 let id = proc_macro;
2148 let proc_macro = tcx.local_def_id_to_hir_id(proc_macro);
2149 let mut name = tcx.hir_name(proc_macro);
2150 let span = tcx.hir_span(proc_macro);
2151 let attrs = tcx.hir_attrs(proc_macro);
2154 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) {
2155 (MacroKind::Bang, ProcMacroKind::Bang { name: name.as_str().to_owned() })
2156 } 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) {
2157 (MacroKind::Attr, ProcMacroKind::Attr { name: name.as_str().to_owned() })
2158 } 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,
2159 ProcMacroDerive { trait_name, helper_attrs } => (trait_name, helper_attrs))
2160 {
2161 name = *trait_name;
2162 (
2163 MacroKind::Derive,
2164 ProcMacroKind::CustomDerive {
2165 trait_name: name.as_str().to_owned(),
2166 attributes: helper_attrs
2167 .iter()
2168 .map(|attr| attr.as_str().to_owned())
2169 .collect(),
2170 },
2171 )
2172 } else {
2173 ::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);
2174 };
2175
2176 macros.push((id, self.lazy(kind)));
2177
2178 let mut def_key = tcx.hir_def_key(id);
2179 def_key.disambiguated_data.data = DefPathData::MacroNs(name);
2180
2181 self.table_writer().def_kind(id, DefKind::Macro(macro_kind.into()));
2182
2183 self.encode_attrs(id);
2184 self.table_writer().def_keys(id, def_key);
2185 self.table_writer().def_ident_span(id, span);
2186 self.table_writer().def_span(id, span);
2187 self.table_writer().visibility(id, ty::Visibility::Public);
2188 if let Some(stability) = stability {
2189 self.table_writer().lookup_stability(id, stability);
2190 }
2191 }
2192
2193 let macros = self.lazy_array(macros);
2194
2195 let mut proc_macro_quoted_spans = TableBuilder::default();
2196 for (i, span) in tcx.sess.proc_macro_quoted_spans() {
2197 proc_macro_quoted_spans.set_some(i, self.lazy(span));
2198 }
2199
2200 let proc_macro_quoted_spans = proc_macro_quoted_spans.encode(&mut self.opaque);
2201
2202 Some(ProcMacroData {
2203 proc_macro_decls_static,
2204 stability,
2205 macros,
2206 proc_macro_quoted_spans,
2207 })
2208 } else {
2209 None
2210 }
2211 }
2212
2213 fn encode_debugger_visualizers(&mut self) -> LazyArray<DebuggerVisualizerFile> {
2214 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2215 self.lazy_array(
2216 self.tcx
2217 .debugger_visualizers(LOCAL_CRATE)
2218 .iter()
2219 .map(DebuggerVisualizerFile::path_erased),
2224 )
2225 }
2226
2227 fn encode_crate_deps(&mut self) -> LazyArray<CrateDep> {
2228 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2229
2230 let deps = self
2231 .tcx
2232 .crates(())
2233 .iter()
2234 .map(|&cnum| {
2235 let dep = CrateDep {
2236 name: self.tcx.crate_name(cnum),
2237 hash: self.tcx.crate_hash(cnum),
2238 host_hash: self.tcx.crate_host_hash(cnum),
2239 kind: self.tcx.crate_dep_kind(cnum),
2240 is_private: self.tcx.is_private_dep(cnum),
2241 };
2242 (cnum, dep)
2243 })
2244 .collect::<Vec<_>>();
2245
2246 {
2247 let mut expected_cnum = 1;
2249 for &(n, _) in &deps {
2250 {
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));
2251 expected_cnum += 1;
2252 }
2253 }
2254
2255 self.lazy_array(deps.iter().map(|(_, dep)| dep))
2260 }
2261
2262 fn encode_target_modifiers(&mut self) -> LazyArray<TargetModifier> {
2263 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2264 let tcx = self.tcx;
2265 self.lazy_array(tcx.sess.opts.gather_target_modifiers())
2266 }
2267
2268 fn encode_enabled_denied_partial_mitigations(&mut self) -> LazyArray<DeniedPartialMitigation> {
2269 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2270 let tcx = self.tcx;
2271 self.lazy_array(tcx.sess.gather_enabled_denied_partial_mitigations())
2272 }
2273
2274 fn encode_lib_features(&mut self) -> LazyArray<(Symbol, FeatureStability)> {
2275 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2276 let tcx = self.tcx;
2277 let lib_features = tcx.lib_features(LOCAL_CRATE);
2278 self.lazy_array(lib_features.to_sorted_vec())
2279 }
2280
2281 fn encode_stability_implications(&mut self) -> LazyArray<(Symbol, Symbol)> {
2282 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2283 let tcx = self.tcx;
2284 let implications = tcx.stability_implications(LOCAL_CRATE);
2285 let sorted = implications.to_sorted_stable_ord();
2286 self.lazy_array(sorted.into_iter().map(|(k, v)| (*k, *v)))
2287 }
2288
2289 fn encode_canonical_symbols(&mut self) -> LazyArray<(Symbol, LocalDefId)> {
2290 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2291 let tcx = self.tcx;
2292 let canonical_symbols = &tcx.canonical_symbols(LOCAL_CRATE);
2293 self.lazy_array(canonical_symbols.iter().map(|cs| (cs.symbol, cs.def_id.expect_local())))
2294 }
2295
2296 fn encode_diagnostic_items(&mut self) -> LazyArray<(Symbol, LocalDefId)> {
2297 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2298 let tcx = self.tcx;
2299 let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id;
2300 self.lazy_array(
2301 diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.expect_local())),
2302 )
2303 }
2304
2305 fn encode_fake_doc_items(&mut self) -> LazyArray<LocalDefId> {
2306 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2307 let tcx = self.tcx;
2308 let fake_doc_items = &tcx.fake_doc_items(LOCAL_CRATE);
2309 self.lazy_array(fake_doc_items.iter().map(|cs| cs.expect_local()))
2310 }
2311
2312 fn encode_lang_items(&mut self) -> LazyArray<(LocalDefId, LangItem)> {
2313 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2314 let lang_items = self.tcx.lang_items().iter();
2315 self.lazy_array(
2316 lang_items
2317 .filter_map(|(lang_item, def_id)| def_id.as_local().map(|id| (id, lang_item))),
2318 )
2319 }
2320
2321 fn encode_lang_items_missing(&mut self) -> LazyArray<LangItem> {
2322 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2323 let tcx = self.tcx;
2324 self.lazy_array(&tcx.lang_items().missing)
2325 }
2326
2327 fn encode_stripped_cfg_items(&mut self) -> LazyArray<StrippedCfgItem<LocalDefId>> {
2328 self.lazy_array(
2329 self.tcx
2330 .stripped_cfg_items(LOCAL_CRATE)
2331 .into_iter()
2332 .map(|item| item.clone().map_scope_id(|def_id| def_id.expect_local())),
2333 )
2334 }
2335
2336 fn encode_traits(&mut self) -> LazyArray<LocalDefId> {
2337 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2338 self.lazy_array(self.tcx.traits(LOCAL_CRATE).iter().map(|def_id| def_id.expect_local()))
2339 }
2340
2341 {}
#[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/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(2342u32),
::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))]
2343 fn encode_impls(&mut self) -> LazyArray<TraitImpls> {
2344 empty_proc_macro!(self);
2345 let tcx = self.tcx;
2346 let mut trait_impls: FxIndexMap<DefId, Vec<(LocalDefId, Option<SimplifiedType>)>> =
2347 FxIndexMap::default();
2348
2349 for id in tcx.hir_free_items() {
2350 let DefKind::Impl { of_trait } = tcx.def_kind(id.owner_id) else {
2351 continue;
2352 };
2353 let local_id = id.owner_id.def_id;
2354
2355 if of_trait {
2356 let header = tcx.impl_trait_header(local_id);
2357 self.table_writer().impl_trait_header(local_id, header);
2358
2359 let impl_is_fully_generic_for_reflection =
2360 tcx.impl_is_fully_generic_for_reflection(local_id);
2361
2362 self.table_writer().impl_is_fully_generic_for_reflection(
2363 local_id,
2364 impl_is_fully_generic_for_reflection,
2365 );
2366 self.table_writer().defaultness(local_id, tcx.defaultness(local_id));
2367
2368 let trait_ref = header.trait_ref.instantiate_identity().skip_norm_wip();
2369 let simplified_self_ty = fast_reject::simplify_type(
2370 tcx,
2371 trait_ref.self_ty(),
2372 TreatParams::InstantiateWithInfer,
2373 );
2374 trait_impls
2375 .entry(trait_ref.def_id)
2376 .or_default()
2377 .push((local_id, simplified_self_ty));
2378
2379 let trait_def = tcx.trait_def(trait_ref.def_id);
2380 if let Ok(mut an) = trait_def.ancestors(tcx, local_id.to_def_id())
2381 && let Some(specialization_graph::Node::Impl(parent)) = an.nth(1)
2382 {
2383 let parent = RemappedRawDefId::create(parent, &self.local_defs_remapping);
2384 self.table_writer().impl_parent(local_id, parent);
2385 }
2386
2387 if tcx.is_lang_item(trait_ref.def_id, LangItem::CoerceUnsized) {
2390 let coerce_unsized_info = tcx.coerce_unsized_info(local_id).unwrap();
2391 self.table_writer().coerce_unsized_info(local_id, coerce_unsized_info);
2392 }
2393 }
2394 }
2395
2396 let trait_impls: Vec<_> = trait_impls
2397 .into_iter()
2398 .map(|(trait_def_id, impls)| TraitImpls {
2399 trait_id: RemappedRawDefId::create(trait_def_id, &self.local_defs_remapping),
2400 impls: self.lazy_array(&impls),
2401 })
2402 .collect();
2403
2404 self.lazy_array(&trait_impls)
2405 }
2406
2407 {}
#[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/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(2407u32),
::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))]
2408 fn encode_incoherent_impls(&mut self) -> LazyArray<IncoherentImpls> {
2409 empty_proc_macro!(self);
2410 let tcx = self.tcx;
2411
2412 let all_impls: Vec<_> = tcx
2413 .crate_inherent_impls(())
2414 .0
2415 .incoherent_impls
2416 .iter()
2417 .map(|(&simp, impls)| IncoherentImpls {
2418 self_ty: self.lazy(simp),
2419 impls: self.lazy_array(impls.iter().map(|def_id| *def_id)),
2420 })
2421 .collect();
2422
2423 self.lazy_array(&all_impls)
2424 }
2425
2426 fn encode_exportable_items(&mut self) -> LazyArray<LocalDefId> {
2427 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2428 self.lazy_array(
2429 self.tcx.exportable_items(LOCAL_CRATE).iter().map(|def_id| def_id.expect_local()),
2430 )
2431 }
2432
2433 fn encode_stable_order_of_exportable_impls(&mut self) -> LazyArray<(LocalDefId, usize)> {
2434 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2435 let stable_order_of_exportable_impls =
2436 self.tcx.stable_order_of_exportable_impls(LOCAL_CRATE);
2437 self.lazy_array(
2438 stable_order_of_exportable_impls
2439 .iter()
2440 .map(|(def_id, idx)| (def_id.expect_local(), *idx)),
2441 )
2442 }
2443
2444 fn encode_exported_symbols(
2451 &mut self,
2452 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportInfo)],
2453 ) -> LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)> {
2454 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2455
2456 self.lazy_array(exported_symbols.iter().cloned())
2457 }
2458
2459 fn encode_dylib_dependency_formats(&mut self) -> LazyArray<Option<LinkagePreference>> {
2460 if self.is_proc_macro { return LazyArray::default(); };empty_proc_macro!(self);
2461 let formats = self.tcx.dependency_formats(());
2462 if let Some(arr) = formats.get(&CrateType::Dylib) {
2463 return self.lazy_array(arr.iter().skip(1 ).map(
2464 |slot| match *slot {
2465 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
2466
2467 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
2468 Linkage::Static => Some(LinkagePreference::RequireStatic),
2469 },
2470 ));
2471 }
2472 LazyArray::default()
2473 }
2474}
2475
2476fn prefetch_mir(tcx: TyCtxt<'_>) {
2479 if !tcx.sess.opts.output_types.should_codegen() {
2480 return;
2482 }
2483
2484 let reachable_set = tcx.reachable_set(());
2485 par_for_each_in(tcx.mir_keys(()).as_slice(), |&def_id| {
2486 if tcx.is_trivial_const(def_id) {
2487 return;
2488 }
2489 let (encode_const, encode_opt) = should_encode_mir(tcx, Some(reachable_set), def_id);
2490
2491 if encode_const {
2492 tcx.ensure_done().mir_for_ctfe(def_id);
2493 }
2494 if encode_opt {
2495 tcx.ensure_done().optimized_mir(def_id);
2496 }
2497 if encode_opt || encode_const {
2498 tcx.ensure_done().promoted_mir(def_id);
2499 }
2500 })
2501}
2502
2503pub struct EncodedMetadata {
2527 full_metadata: Option<Mmap>,
2530 stub_metadata: Option<Vec<u8>>,
2533 path: Option<Box<Path>>,
2535 _temp_dir: Option<MaybeTempDir>,
2538}
2539
2540impl EncodedMetadata {
2541 #[inline]
2542 pub fn from_path(
2543 path: PathBuf,
2544 stub_path: Option<PathBuf>,
2545 temp_dir: Option<MaybeTempDir>,
2546 ) -> std::io::Result<Self> {
2547 let file = std::fs::File::open(&path)?;
2548 let file_metadata = file.metadata()?;
2549 if file_metadata.len() == 0 {
2550 return Ok(Self {
2551 full_metadata: None,
2552 stub_metadata: None,
2553 path: None,
2554 _temp_dir: None,
2555 });
2556 }
2557 let full_mmap = unsafe { Some(Mmap::map(file)?) };
2558
2559 let stub =
2560 if let Some(stub_path) = stub_path { Some(std::fs::read(stub_path)?) } else { None };
2561
2562 Ok(Self {
2563 full_metadata: full_mmap,
2564 stub_metadata: stub,
2565 path: Some(path.into()),
2566 _temp_dir: temp_dir,
2567 })
2568 }
2569
2570 #[inline]
2571 pub fn full(&self) -> &[u8] {
2572 &self.full_metadata.as_deref().unwrap_or_default()
2573 }
2574
2575 #[inline]
2576 pub fn stub_or_full(&self) -> &[u8] {
2577 self.stub_metadata.as_deref().unwrap_or(self.full())
2578 }
2579
2580 #[inline]
2581 pub fn path(&self) -> Option<&Path> {
2582 self.path.as_deref()
2583 }
2584}
2585
2586impl<S: Encoder> Encodable<S> for EncodedMetadata {
2587 fn encode(&self, s: &mut S) {
2588 self.stub_metadata.encode(s);
2589
2590 let slice = self.full();
2591 slice.encode(s)
2592 }
2593}
2594
2595impl<D: Decoder> Decodable<D> for EncodedMetadata {
2596 fn decode(d: &mut D) -> Self {
2597 let stub = <Option<Vec<u8>>>::decode(d);
2598
2599 let len = d.read_usize();
2600 let full_metadata = if len > 0 {
2601 let mut mmap = MmapMut::map_anon(len).unwrap();
2602 mmap.copy_from_slice(d.read_raw_bytes(len));
2603 Some(mmap.make_read_only().unwrap())
2604 } else {
2605 None
2606 };
2607
2608 Self { full_metadata, stub_metadata: stub, path: None, _temp_dir: None }
2609 }
2610}
2611
2612{}
#[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/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(2612u32),
::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/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/rmeta/encoder.rs:2633",
"rustc_metadata::rmeta::encoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/rmeta/encoder.rs"),
::tracing_core::__macro_support::Option::Some(2633u32),
::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))]
2613pub fn encode_metadata(tcx: TyCtxt<'_>, path: &Path, ref_path: Option<&Path>) {
2614 tcx.dep_graph.assert_ignored();
2617
2618 let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata");
2619
2620 let dep_node = tcx.metadata_dep_node();
2621
2622 if tcx.dep_graph.is_fully_enabled()
2624 && let incr_comp_session = tcx.incr_comp_session.unwrap()
2625 && let Some(old_incr_comp_session_dir) = &incr_comp_session.old_session_directory
2626 && let work_product_id =
2627 WorkProductId::from_cgu_name(WorkProduct::METADATA_WORKPRODUCT_CGU_NAME)
2628 && let Some(work_product) = tcx.dep_graph.previous_work_product(&work_product_id)
2629 && tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some()
2630 {
2631 let saved_path = &work_product.saved_files[OutputType::Metadata.extension()];
2632 let source_file_in_incr_dir = &old_incr_comp_session_dir.join(saved_path);
2633 debug!("copying preexisting metadata from {source_file_in_incr_dir:?} to {path:?}");
2634 match rustc_fs_util::link_or_copy(&source_file_in_incr_dir, path) {
2635 Ok(_) => {}
2636 Err(err) => tcx.dcx().emit_fatal(FailCreateFileEncoder { err }),
2637 };
2638
2639 let file = std::fs::File::open(&source_file_in_incr_dir).unwrap();
2641 let mmap = unsafe { Mmap::map(file) }.unwrap();
2642 let owned = slice_owned(mmap, Deref::deref);
2643 let blob = MetadataBlob::new(owned);
2644 let hash = blob.expect("file already created").get_crate_hash();
2645 tcx.untracked().local_crate_hash.set(hash).expect("local_crate_hash set twice");
2646
2647 if let Some(ref_path) = ref_path {
2649 let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata_stub");
2650
2651 with_encode_metadata_header(tcx, ref_path, |ecx| {
2652 let header: LazyValue<CrateHeader> = ecx.lazy(CrateHeader {
2653 name: tcx.crate_name(LOCAL_CRATE),
2654 triple: tcx.sess.opts.target_triple.clone(),
2655 is_proc_macro_crate: false,
2656 is_stub: true,
2657 });
2658 (header.position.get(), 0)
2659 })
2660 }
2661
2662 return;
2663 };
2664
2665 if tcx.sess.opts.jobs.frontend.is_parallel() {
2666 par_join(
2670 || prefetch_mir(tcx),
2671 || {
2672 let _ = tcx.exported_non_generic_symbols(LOCAL_CRATE);
2673 let _ = tcx.exported_generic_symbols(LOCAL_CRATE);
2674 },
2675 );
2676 }
2677
2678 tcx.dep_graph.with_task(
2681 dep_node,
2682 tcx,
2683 || {
2684 with_encode_metadata_header(tcx, path, |ecx| {
2685 let (root, unhashed) = ecx.encode_crate_root();
2688
2689 ecx.opaque.flush();
2691 tcx.prof.artifact_size(
2693 "crate_metadata",
2694 "crate_metadata",
2695 ecx.opaque.file().metadata().unwrap().len(),
2696 );
2697
2698 (root.position.get(), unhashed.position.get())
2699 })
2700 },
2701 None,
2702 );
2703
2704 if let Some(ref_path) = ref_path {
2706 let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata_stub");
2707
2708 with_encode_metadata_header(tcx, ref_path, |ecx| {
2709 let header: LazyValue<CrateHeader> = ecx.lazy(CrateHeader {
2710 name: tcx.crate_name(LOCAL_CRATE),
2711 triple: tcx.sess.opts.target_triple.clone(),
2712 is_proc_macro_crate: false,
2713 is_stub: true,
2714 });
2715 (header.position.get(), 0)
2716 })
2717 }
2718}
2719
2720fn with_encode_metadata_header(
2721 tcx: TyCtxt<'_>,
2722 path: &Path,
2723 f: impl FnOnce(&mut EncodeContext<'_, '_>) -> (usize, usize),
2724) {
2725 let metadata_crate_hash = tcx.sess.opts.unstable_opts.metadata_crate_hash;
2729 let metadata_hasher = Arc::new(Mutex::new(XxHash3_128::new()));
2734 if metadata_crate_hash {
2735 let hir_body_hash = compute_hir_hash(tcx);
2738 let supplement: Fingerprint = tcx.with_stable_hashing_context(|mut hcx| {
2739 let mut hasher = StableHasher::new();
2740 tcx.sess.opts.dep_tracking_hash(true).stable_hash(&mut hcx, &mut hasher);
2742 hir_body_hash.stable_hash(&mut hcx, &mut hasher);
2744 hasher.finish()
2745 });
2746 metadata_hasher.lock().unwrap().write(&supplement.to_le_bytes());
2747 }
2748
2749 let mut flush_strategy = {
2751 let metadata_hasher = Arc::clone(&metadata_hasher);
2752 move |bytes: &[u8]| metadata_hasher.lock().unwrap().write(bytes)
2753 };
2754
2755 let mut encoder = if metadata_crate_hash {
2756 FileEncoder::with_flush_strategy(path, &mut flush_strategy)
2757 } else {
2758 FileEncoder::new(path)
2759 }
2760 .unwrap_or_else(|err| tcx.dcx().emit_fatal(FailCreateFileEncoder { err }));
2761 encoder.emit_raw_bytes(METADATA_HEADER);
2762
2763 encoder.emit_raw_bytes(&0u64.to_le_bytes());
2765
2766 encoder.emit_raw_bytes(&0u64.to_le_bytes());
2768
2769 encoder.emit_raw_bytes(&Fingerprint::ZERO.to_le_bytes());
2771
2772 let source_map_files = tcx.sess.source_map().files();
2773 let source_file_cache = (Arc::clone(&source_map_files[0]), 0);
2774 let required_source_files = Some(FxIndexSet::default());
2775 drop(source_map_files);
2776
2777 let mut ecx = EncodeContext {
2778 opaque: encoder,
2779 metadata_hasher: Arc::clone(&metadata_hasher),
2780 tcx,
2781 feat: tcx.features(),
2782 tables: Default::default(),
2783 lazy_state: LazyState::NoNode,
2784 span_shorthands: Default::default(),
2785 type_shorthands: Default::default(),
2786 predicate_shorthands: Default::default(),
2787 source_file_cache,
2788 interpret_allocs: Default::default(),
2789 required_source_files,
2790 is_proc_macro: tcx.crate_types().contains(&CrateType::ProcMacro),
2791 hygiene_ctxt: Default::default(),
2792 symbol_index_table: Default::default(),
2793 local_defs_remapping: Default::default(),
2794 syntax_context_remapping: Default::default(),
2795 local_expn_id_remapping: Default::default(),
2796 };
2797
2798 rustc_version(tcx.sess.cfg_version).encode(&mut ecx);
2800
2801 let (root_position, unhashed_position) = f(&mut ecx);
2802
2803 if let Err((path, err)) = ecx.opaque.finish() {
2807 tcx.dcx().emit_fatal(FailWriteFile { path: &path, err });
2808 }
2809
2810 let mut file = ecx.opaque.file();
2811 let pos_before_seek = file.stream_position().unwrap();
2813
2814 if let Err(err) = encode_root_position(file, root_position) {
2815 tcx.dcx().emit_fatal(FailWriteFile { path: ecx.opaque.path(), err });
2816 }
2817
2818 if let Err(err) = encode_unhashed_position(file, unhashed_position) {
2819 tcx.dcx().emit_fatal(FailWriteFile { path: ecx.opaque.path(), err });
2820 }
2821
2822 let hash = tcx
2823 .untracked()
2824 .local_crate_hash
2825 .get()
2826 .copied()
2827 .expect("local_crate_hash set during encoding");
2828 if let Err(err) = encode_crate_hash(file, hash) {
2829 tcx.dcx().emit_fatal(FailWriteFile { path: ecx.opaque.path(), err });
2830 }
2831
2832 if let Err(err) = file.seek(SeekFrom::Start(pos_before_seek)) {
2833 tcx.dcx().emit_fatal(FailWriteFile { path: ecx.opaque.path(), err });
2834 }
2835}
2836
2837fn encode_root_position(mut file: &File, pos: usize) -> Result<(), std::io::Error> {
2838 file.seek(SeekFrom::Start(ROOT_POS_OFFSET as u64))?;
2839 file.write_all(&pos.to_le_bytes())?;
2840 Ok(())
2841}
2842
2843fn encode_unhashed_position(mut file: &File, pos: usize) -> Result<(), std::io::Error> {
2844 file.seek(SeekFrom::Start(UNHASHED_POS_OFFSET as u64))?;
2845 file.write_all(&pos.to_le_bytes())?;
2846 Ok(())
2847}
2848
2849fn encode_crate_hash(mut file: &File, hash: Svh) -> Result<(), std::io::Error> {
2850 file.seek(SeekFrom::Start(CRATE_HASH_OFFSET as u64))?;
2851 file.write_all(&hash.as_fingerprint().to_le_bytes())?;
2852 Ok(())
2853}
2854
2855pub(crate) fn provide(providers: &mut Providers) {
2856 *providers = Providers {
2857 doc_link_resolutions: |tcx, def_id| {
2858 tcx.resolutions(())
2859 .doc_link_resolutions
2860 .get(&def_id)
2861 .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"))
2862 },
2863 doc_link_traits_in_scope: |tcx, def_id| {
2864 tcx.resolutions(()).doc_link_traits_in_scope.get(&def_id).unwrap_or_else(|| {
2865 ::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")
2866 })
2867 },
2868
2869 ..*providers
2870 }
2871}
2872
2873pub fn rendered_const<'tcx>(tcx: TyCtxt<'tcx>, body: &hir::Body<'_>, def_id: LocalDefId) -> String {
2901 let value = body.value;
2902
2903 #[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)]
2904 enum Classification {
2905 Literal,
2906 Simple,
2907 Complex,
2908 }
2909
2910 use Classification::*;
2911
2912 fn classify(expr: &hir::Expr<'_>) -> Classification {
2913 match &expr.kind {
2914 hir::ExprKind::Unary(hir::UnOp::Neg, expr) => {
2915 if #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
hir::ExprKind::Lit(_) => true,
_ => false,
}matches!(expr.kind, hir::ExprKind::Lit(_)) { Literal } else { Complex }
2916 }
2917 hir::ExprKind::Lit(_) => Literal,
2918 hir::ExprKind::Tup([]) => Simple,
2919 hir::ExprKind::Block(hir::Block { stmts: [], expr: Some(expr), .. }, _) => {
2920 if classify(expr) == Complex { Complex } else { Simple }
2921 }
2922 hir::ExprKind::Path(hir::QPath::Resolved(_, hir::Path { segments, .. })) => {
2927 if segments.iter().all(|segment| segment.args.is_none()) { Simple } else { Complex }
2928 }
2929 hir::ExprKind::Path(hir::QPath::TypeRelative(..)) => Simple,
2932 _ => Complex,
2933 }
2934 }
2935
2936 match classify(value) {
2937 Literal
2947 if !value.span.from_expansion()
2948 && let Ok(snippet) = tcx.sess.source_map().span_to_snippet(value.span) =>
2949 {
2950 snippet
2951 }
2952
2953 Literal | Simple => id_to_string(&tcx, body.id().hir_id),
2956
2957 Complex => {
2961 if tcx.def_kind(def_id) == DefKind::AnonConst {
2962 "{ _ }".to_owned()
2963 } else {
2964 "_".to_owned()
2965 }
2966 }
2967 }
2968}