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