1use std::marker::PhantomData;
2use std::num::NonZero;
3
4pub(crate) use decoder::{CrateMetadata, CrateNumMap, MetadataBlob, TargetModifiers};
5use decoder::{DecodeContext, Metadata};
6use def_path_hash_map::DefPathHashMapRef;
7use encoder::EncodeContext;
8pub use encoder::{EncodedMetadata, encode_metadata, rendered_const};
9pub(crate) use parameterized::ParameterizedOverTcx;
10use rustc_abi::{FieldIdx, ReprOptions, VariantIdx};
11use rustc_data_structures::fx::FxHashMap;
12use rustc_data_structures::svh::Svh;
13use rustc_hir::attrs::StrippedCfgItem;
14use rustc_hir::def::{CtorKind, DefKind, DocLinkResMap, MacroKinds};
15use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, DefIndex, DefPathHash, StableCrateId};
16use rustc_hir::definitions::DefKey;
17use rustc_hir::lang_items::LangItem;
18use rustc_hir::{PreciseCapturingArgKind, attrs};
19use rustc_index::IndexVec;
20use rustc_index::bit_set::DenseBitSet;
21use rustc_macros::{
22 Decodable, Encodable, MetadataDecodable, MetadataEncodable, TyDecodable, TyEncodable,
23};
24use rustc_middle::metadata::ModChild;
25use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
26use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
27use rustc_middle::middle::deduced_param_attrs::DeducedParamAttrs;
28use rustc_middle::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo};
29use rustc_middle::middle::lib_features::FeatureStability;
30use rustc_middle::middle::resolve_bound_vars::ObjectLifetimeDefault;
31use rustc_middle::mir;
32use rustc_middle::mir::ConstValue;
33use rustc_middle::ty::fast_reject::SimplifiedType;
34use rustc_middle::ty::{self, Ty, TyCtxt, UnusedGenericParams};
35use rustc_middle::util::Providers;
36use rustc_serialize::opaque::FileEncoder;
37use rustc_session::config::{SymbolManglingVersion, TargetModifier};
38use rustc_session::cstore::{CrateDepKind, ForeignModule, LinkagePreference, NativeLib};
39use rustc_span::edition::Edition;
40use rustc_span::hygiene::{ExpnIndex, MacroKind, SyntaxContextKey};
41use rustc_span::{self, ExpnData, ExpnHash, ExpnId, Ident, Span, Symbol};
42use rustc_target::spec::{PanicStrategy, TargetTuple};
43use table::TableBuilder;
44use {rustc_ast as ast, rustc_hir as hir};
45
46use crate::creader::CrateMetadataRef;
47
48mod decoder;
49mod def_path_hash_map;
50mod encoder;
51mod parameterized;
52mod table;
53
54pub(crate) fn rustc_version(cfg_version: &'static str) -> String {
55 format!("rustc {cfg_version}")
56}
57
58const METADATA_VERSION: u8 = 10;
62
63pub const METADATA_HEADER: &[u8] = &[b'r', b'u', b's', b't', 0, 0, 0, METADATA_VERSION];
69
70#[must_use]
86struct LazyValue<T> {
87 position: NonZero<usize>,
88 _marker: PhantomData<fn() -> T>,
89}
90
91impl<T> LazyValue<T> {
92 fn from_position(position: NonZero<usize>) -> LazyValue<T> {
93 LazyValue { position, _marker: PhantomData }
94 }
95}
96
97struct LazyArray<T> {
108 position: NonZero<usize>,
109 num_elems: usize,
110 _marker: PhantomData<fn() -> T>,
111}
112
113impl<T> Default for LazyArray<T> {
114 fn default() -> LazyArray<T> {
115 LazyArray::from_position_and_num_elems(NonZero::new(1).unwrap(), 0)
116 }
117}
118
119impl<T> LazyArray<T> {
120 fn from_position_and_num_elems(position: NonZero<usize>, num_elems: usize) -> LazyArray<T> {
121 LazyArray { position, num_elems, _marker: PhantomData }
122 }
123}
124
125struct LazyTable<I, T> {
131 position: NonZero<usize>,
132 width: usize,
135 len: usize,
137 _marker: PhantomData<fn(I) -> T>,
138}
139
140impl<I, T> LazyTable<I, T> {
141 fn from_position_and_encoded_size(
142 position: NonZero<usize>,
143 width: usize,
144 len: usize,
145 ) -> LazyTable<I, T> {
146 LazyTable { position, width, len, _marker: PhantomData }
147 }
148}
149
150impl<T> Copy for LazyValue<T> {}
151impl<T> Clone for LazyValue<T> {
152 fn clone(&self) -> Self {
153 *self
154 }
155}
156
157impl<T> Copy for LazyArray<T> {}
158impl<T> Clone for LazyArray<T> {
159 fn clone(&self) -> Self {
160 *self
161 }
162}
163
164impl<I, T> Copy for LazyTable<I, T> {}
165impl<I, T> Clone for LazyTable<I, T> {
166 fn clone(&self) -> Self {
167 *self
168 }
169}
170
171#[derive(Copy, Clone, PartialEq, Eq, Debug)]
173enum LazyState {
174 NoNode,
176
177 NodeStart(NonZero<usize>),
180
181 Previous(NonZero<usize>),
184}
185
186type SyntaxContextTable = LazyTable<u32, Option<LazyValue<SyntaxContextKey>>>;
187type ExpnDataTable = LazyTable<ExpnIndex, Option<LazyValue<ExpnData>>>;
188type ExpnHashTable = LazyTable<ExpnIndex, Option<LazyValue<ExpnHash>>>;
189
190#[derive(MetadataEncodable, MetadataDecodable)]
191pub(crate) struct ProcMacroData {
192 proc_macro_decls_static: DefIndex,
193 stability: Option<hir::Stability>,
194 macros: LazyArray<DefIndex>,
195}
196
197#[derive(MetadataEncodable, MetadataDecodable)]
205pub(crate) struct CrateHeader {
206 pub(crate) triple: TargetTuple,
207 pub(crate) hash: Svh,
208 pub(crate) name: Symbol,
209 pub(crate) is_proc_macro_crate: bool,
214 pub(crate) is_stub: bool,
220}
221
222#[derive(MetadataEncodable, MetadataDecodable)]
240pub(crate) struct CrateRoot {
241 header: CrateHeader,
243
244 extra_filename: String,
245 stable_crate_id: StableCrateId,
246 required_panic_strategy: Option<PanicStrategy>,
247 panic_in_drop_strategy: PanicStrategy,
248 edition: Edition,
249 has_global_allocator: bool,
250 has_alloc_error_handler: bool,
251 has_panic_handler: bool,
252 has_default_lib_allocator: bool,
253
254 crate_deps: LazyArray<CrateDep>,
255 dylib_dependency_formats: LazyArray<Option<LinkagePreference>>,
256 lib_features: LazyArray<(Symbol, FeatureStability)>,
257 stability_implications: LazyArray<(Symbol, Symbol)>,
258 lang_items: LazyArray<(DefIndex, LangItem)>,
259 lang_items_missing: LazyArray<LangItem>,
260 stripped_cfg_items: LazyArray<StrippedCfgItem<DefIndex>>,
261 diagnostic_items: LazyArray<(Symbol, DefIndex)>,
262 native_libraries: LazyArray<NativeLib>,
263 foreign_modules: LazyArray<ForeignModule>,
264 traits: LazyArray<DefIndex>,
265 impls: LazyArray<TraitImpls>,
266 incoherent_impls: LazyArray<IncoherentImpls>,
267 interpret_alloc_index: LazyArray<u64>,
268 proc_macro_data: Option<ProcMacroData>,
269
270 tables: LazyTables,
271 debugger_visualizers: LazyArray<DebuggerVisualizerFile>,
272
273 exportable_items: LazyArray<DefIndex>,
274 stable_order_of_exportable_impls: LazyArray<(DefIndex, usize)>,
275 exported_non_generic_symbols: LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)>,
276 exported_generic_symbols: LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)>,
277
278 syntax_contexts: SyntaxContextTable,
279 expn_data: ExpnDataTable,
280 expn_hashes: ExpnHashTable,
281
282 def_path_hash_map: LazyValue<DefPathHashMapRef<'static>>,
283
284 source_map: LazyTable<u32, Option<LazyValue<rustc_span::SourceFile>>>,
285 target_modifiers: LazyArray<TargetModifier>,
286
287 compiler_builtins: bool,
288 needs_allocator: bool,
289 needs_panic_runtime: bool,
290 no_builtins: bool,
291 panic_runtime: bool,
292 profiler_runtime: bool,
293 symbol_mangling_version: SymbolManglingVersion,
294
295 specialization_enabled_in: bool,
296}
297
298#[derive(Copy, Clone)]
302pub(crate) struct RawDefId {
303 krate: u32,
304 index: u32,
305}
306
307impl From<DefId> for RawDefId {
308 fn from(val: DefId) -> Self {
309 RawDefId { krate: val.krate.as_u32(), index: val.index.as_u32() }
310 }
311}
312
313impl RawDefId {
314 fn decode(self, meta: (CrateMetadataRef<'_>, TyCtxt<'_>)) -> DefId {
316 self.decode_from_cdata(meta.0)
317 }
318
319 fn decode_from_cdata(self, cdata: CrateMetadataRef<'_>) -> DefId {
320 let krate = CrateNum::from_u32(self.krate);
321 let krate = cdata.map_encoded_cnum_to_current(krate);
322 DefId { krate, index: DefIndex::from_u32(self.index) }
323 }
324}
325
326#[derive(Encodable, Decodable)]
327pub(crate) struct CrateDep {
328 pub name: Symbol,
329 pub hash: Svh,
330 pub host_hash: Option<Svh>,
331 pub kind: CrateDepKind,
332 pub extra_filename: String,
333 pub is_private: bool,
334}
335
336#[derive(MetadataEncodable, MetadataDecodable)]
337pub(crate) struct TraitImpls {
338 trait_id: (u32, DefIndex),
339 impls: LazyArray<(DefIndex, Option<SimplifiedType>)>,
340}
341
342#[derive(MetadataEncodable, MetadataDecodable)]
343pub(crate) struct IncoherentImpls {
344 self_ty: SimplifiedType,
345 impls: LazyArray<DefIndex>,
346}
347
348macro_rules! define_tables {
350 (
351 - defaulted: $($name1:ident: Table<$IDX1:ty, $T1:ty>,)+
352 - optional: $($name2:ident: Table<$IDX2:ty, $T2:ty>,)+
353 ) => {
354 #[derive(MetadataEncodable, MetadataDecodable)]
355 pub(crate) struct LazyTables {
356 $($name1: LazyTable<$IDX1, $T1>,)+
357 $($name2: LazyTable<$IDX2, Option<$T2>>,)+
358 }
359
360 #[derive(Default)]
361 struct TableBuilders {
362 $($name1: TableBuilder<$IDX1, $T1>,)+
363 $($name2: TableBuilder<$IDX2, Option<$T2>>,)+
364 }
365
366 impl TableBuilders {
367 fn encode(&self, buf: &mut FileEncoder) -> LazyTables {
368 LazyTables {
369 $($name1: self.$name1.encode(buf),)+
370 $($name2: self.$name2.encode(buf),)+
371 }
372 }
373 }
374 }
375}
376
377define_tables! {
378- defaulted:
379 intrinsic: Table<DefIndex, Option<LazyValue<ty::IntrinsicDef>>>,
380 is_macro_rules: Table<DefIndex, bool>,
381 type_alias_is_lazy: Table<DefIndex, bool>,
382 attr_flags: Table<DefIndex, AttrFlags>,
383 def_path_hashes: Table<DefIndex, u64>,
389 explicit_item_bounds: Table<DefIndex, LazyArray<(ty::Clause<'static>, Span)>>,
390 explicit_item_self_bounds: Table<DefIndex, LazyArray<(ty::Clause<'static>, Span)>>,
391 inferred_outlives_of: Table<DefIndex, LazyArray<(ty::Clause<'static>, Span)>>,
392 explicit_super_predicates_of: Table<DefIndex, LazyArray<(ty::Clause<'static>, Span)>>,
393 explicit_implied_predicates_of: Table<DefIndex, LazyArray<(ty::Clause<'static>, Span)>>,
394 explicit_implied_const_bounds: Table<DefIndex, LazyArray<(ty::PolyTraitRef<'static>, Span)>>,
395 inherent_impls: Table<DefIndex, LazyArray<DefIndex>>,
396 opt_rpitit_info: Table<DefIndex, Option<LazyValue<ty::ImplTraitInTraitData>>>,
397 module_children_reexports: Table<DefIndex, LazyArray<ModChild>>,
402 cross_crate_inlinable: Table<DefIndex, bool>,
403
404- optional:
405 attributes: Table<DefIndex, LazyArray<hir::Attribute>>,
406 module_children_non_reexports: Table<DefIndex, LazyArray<DefIndex>>,
409 associated_item_or_field_def_ids: Table<DefIndex, LazyArray<DefIndex>>,
410 def_kind: Table<DefIndex, DefKind>,
411 visibility: Table<DefIndex, LazyValue<ty::Visibility<DefIndex>>>,
412 safety: Table<DefIndex, hir::Safety>,
413 def_span: Table<DefIndex, LazyValue<Span>>,
414 def_ident_span: Table<DefIndex, LazyValue<Span>>,
415 lookup_stability: Table<DefIndex, LazyValue<hir::Stability>>,
416 lookup_const_stability: Table<DefIndex, LazyValue<hir::ConstStability>>,
417 lookup_default_body_stability: Table<DefIndex, LazyValue<hir::DefaultBodyStability>>,
418 lookup_deprecation_entry: Table<DefIndex, LazyValue<attrs::Deprecation>>,
419 explicit_predicates_of: Table<DefIndex, LazyValue<ty::GenericPredicates<'static>>>,
420 generics_of: Table<DefIndex, LazyValue<ty::Generics>>,
421 type_of: Table<DefIndex, LazyValue<ty::EarlyBinder<'static, Ty<'static>>>>,
422 variances_of: Table<DefIndex, LazyArray<ty::Variance>>,
423 fn_sig: Table<DefIndex, LazyValue<ty::EarlyBinder<'static, ty::PolyFnSig<'static>>>>,
424 codegen_fn_attrs: Table<DefIndex, LazyValue<CodegenFnAttrs>>,
425 impl_trait_header: Table<DefIndex, LazyValue<ty::ImplTraitHeader<'static>>>,
426 const_param_default: Table<DefIndex, LazyValue<ty::EarlyBinder<'static, rustc_middle::ty::Const<'static>>>>,
427 object_lifetime_default: Table<DefIndex, LazyValue<ObjectLifetimeDefault>>,
428 optimized_mir: Table<DefIndex, LazyValue<mir::Body<'static>>>,
429 mir_for_ctfe: Table<DefIndex, LazyValue<mir::Body<'static>>>,
430 trivial_const: Table<DefIndex, LazyValue<(ConstValue, Ty<'static>)>>,
431 closure_saved_names_of_captured_variables: Table<DefIndex, LazyValue<IndexVec<FieldIdx, Symbol>>>,
432 mir_coroutine_witnesses: Table<DefIndex, LazyValue<mir::CoroutineLayout<'static>>>,
433 promoted_mir: Table<DefIndex, LazyValue<IndexVec<mir::Promoted, mir::Body<'static>>>>,
434 thir_abstract_const: Table<DefIndex, LazyValue<ty::EarlyBinder<'static, ty::Const<'static>>>>,
435 impl_parent: Table<DefIndex, RawDefId>,
436 constness: Table<DefIndex, hir::Constness>,
437 const_conditions: Table<DefIndex, LazyValue<ty::ConstConditions<'static>>>,
438 defaultness: Table<DefIndex, hir::Defaultness>,
439 coerce_unsized_info: Table<DefIndex, LazyValue<ty::adjustment::CoerceUnsizedInfo>>,
441 mir_const_qualif: Table<DefIndex, LazyValue<mir::ConstQualifs>>,
442 rendered_const: Table<DefIndex, LazyValue<String>>,
443 rendered_precise_capturing_args: Table<DefIndex, LazyArray<PreciseCapturingArgKind<Symbol, Symbol>>>,
444 asyncness: Table<DefIndex, ty::Asyncness>,
445 fn_arg_idents: Table<DefIndex, LazyArray<Option<Ident>>>,
446 coroutine_kind: Table<DefIndex, hir::CoroutineKind>,
447 coroutine_for_closure: Table<DefIndex, RawDefId>,
448 adt_destructor: Table<DefIndex, LazyValue<ty::Destructor>>,
449 adt_async_destructor: Table<DefIndex, LazyValue<ty::AsyncDestructor>>,
450 coroutine_by_move_body_def_id: Table<DefIndex, RawDefId>,
451 eval_static_initializer: Table<DefIndex, LazyValue<mir::interpret::ConstAllocation<'static>>>,
452 trait_def: Table<DefIndex, LazyValue<ty::TraitDef>>,
453 expn_that_defined: Table<DefIndex, LazyValue<ExpnId>>,
454 default_fields: Table<DefIndex, LazyValue<DefId>>,
455 params_in_repr: Table<DefIndex, LazyValue<DenseBitSet<u32>>>,
456 repr_options: Table<DefIndex, LazyValue<ReprOptions>>,
457 def_keys: Table<DefIndex, LazyValue<DefKey>>,
462 proc_macro_quoted_spans: Table<usize, LazyValue<Span>>,
463 variant_data: Table<DefIndex, LazyValue<VariantData>>,
464 assoc_container: Table<DefIndex, LazyValue<ty::AssocContainer>>,
465 macro_definition: Table<DefIndex, LazyValue<ast::DelimArgs>>,
466 proc_macro: Table<DefIndex, MacroKind>,
467 deduced_param_attrs: Table<DefIndex, LazyArray<DeducedParamAttrs>>,
468 trait_impl_trait_tys: Table<DefIndex, LazyValue<DefIdMap<ty::EarlyBinder<'static, Ty<'static>>>>>,
469 doc_link_resolutions: Table<DefIndex, LazyValue<DocLinkResMap>>,
470 doc_link_traits_in_scope: Table<DefIndex, LazyArray<DefId>>,
471 assumed_wf_types_for_rpitit: Table<DefIndex, LazyArray<(Ty<'static>, Span)>>,
472 opaque_ty_origin: Table<DefIndex, LazyValue<hir::OpaqueTyOrigin<DefId>>>,
473 anon_const_kind: Table<DefIndex, LazyValue<ty::AnonConstKind>>,
474 associated_types_for_impl_traits_in_trait_or_impl: Table<DefIndex, LazyValue<DefIdMap<Vec<DefId>>>>,
475}
476
477#[derive(TyEncodable, TyDecodable)]
478struct VariantData {
479 idx: VariantIdx,
480 discr: ty::VariantDiscr,
481 ctor: Option<(CtorKind, DefIndex)>,
483 is_non_exhaustive: bool,
484}
485
486bitflags::bitflags! {
487 #[derive(Default)]
488 pub struct AttrFlags: u8 {
489 const IS_DOC_HIDDEN = 1 << 0;
490 }
491}
492
493#[derive(Encodable, Decodable, Copy, Clone)]
510struct SpanTag(u8);
511
512#[derive(Debug, Copy, Clone, PartialEq, Eq)]
513enum SpanKind {
514 Local = 0b00,
515 Foreign = 0b01,
516 Partial = 0b10,
517 Indirect = 0b11,
521}
522
523impl SpanTag {
524 fn new(kind: SpanKind, context: rustc_span::SyntaxContext, length: usize) -> SpanTag {
525 let mut data = 0u8;
526 data |= kind as u8;
527 if context.is_root() {
528 data |= 0b100;
529 }
530 let all_1s_len = (0xffu8 << 3) >> 3;
531 if length < all_1s_len as usize {
533 data |= (length as u8) << 3;
534 } else {
535 data |= all_1s_len << 3;
536 }
537
538 SpanTag(data)
539 }
540
541 fn indirect(relative: bool, length_bytes: u8) -> SpanTag {
542 let mut tag = SpanTag(SpanKind::Indirect as u8);
543 if relative {
544 tag.0 |= 0b100;
545 }
546 assert!(length_bytes <= 8);
547 tag.0 |= length_bytes << 3;
548 tag
549 }
550
551 fn kind(self) -> SpanKind {
552 let masked = self.0 & 0b11;
553 match masked {
554 0b00 => SpanKind::Local,
555 0b01 => SpanKind::Foreign,
556 0b10 => SpanKind::Partial,
557 0b11 => SpanKind::Indirect,
558 _ => unreachable!(),
559 }
560 }
561
562 fn is_relative_offset(self) -> bool {
563 debug_assert_eq!(self.kind(), SpanKind::Indirect);
564 self.0 & 0b100 != 0
565 }
566
567 fn context(self) -> Option<rustc_span::SyntaxContext> {
568 if self.0 & 0b100 != 0 { Some(rustc_span::SyntaxContext::root()) } else { None }
569 }
570
571 fn length(self) -> Option<rustc_span::BytePos> {
572 let all_1s_len = (0xffu8 << 3) >> 3;
573 let len = self.0 >> 3;
574 if len != all_1s_len { Some(rustc_span::BytePos(u32::from(len))) } else { None }
575 }
576}
577
578const SYMBOL_STR: u8 = 0;
580const SYMBOL_OFFSET: u8 = 1;
581const SYMBOL_PREDEFINED: u8 = 2;
582
583pub fn provide(providers: &mut Providers) {
584 encoder::provide(providers);
585 decoder::provide(providers);
586}