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