2 use def_path_hash_map::DefPathHashMapRef;
3 use table::{Table, TableBuilder};
6 use rustc_attr as attr;
7 use rustc_data_structures::svh::Svh;
8 use rustc_data_structures::sync::MetadataRef;
10 use rustc_hir::def::{CtorKind, DefKind};
11 use rustc_hir::def_id::{DefId, DefIndex, DefPathHash, StableCrateId};
12 use rustc_hir::definitions::DefKey;
13 use rustc_hir::lang_items;
14 use rustc_index::{bit_set::FiniteBitSet, vec::IndexVec};
15 use rustc_middle::metadata::ModChild;
16 use rustc_middle::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel};
17 use rustc_middle::mir;
18 use rustc_middle::thir;
19 use rustc_middle::ty::fast_reject::SimplifiedType;
20 use rustc_middle::ty::query::Providers;
21 use rustc_middle::ty::{self, ReprOptions, Ty};
22 use rustc_serialize::opaque::Encoder;
23 use rustc_session::config::SymbolManglingVersion;
24 use rustc_session::cstore::{CrateDepKind, ForeignModule, LinkagePreference, NativeLib};
25 use rustc_span::edition::Edition;
26 use rustc_span::hygiene::{ExpnIndex, MacroKind};
27 use rustc_span::symbol::{Ident, Symbol};
28 use rustc_span::{self, ExpnData, ExpnHash, ExpnId, Span};
29 use rustc_target::spec::{PanicStrategy, TargetTriple};
31 use std::marker::PhantomData;
32 use std::num::NonZeroUsize;
34 pub use decoder::provide_extern;
35 use decoder::DecodeContext;
36 crate use decoder::{CrateMetadata, CrateNumMap, MetadataBlob};
37 use encoder::EncodeContext;
38 pub use encoder::{encode_metadata, EncodedMetadata};
39 use rustc_span::hygiene::SyntaxContextData;
42 mod def_path_hash_map;
46 crate fn rustc_version() -> String {
47 format!("rustc {}", option_env!("CFG_VERSION").unwrap_or("unknown version"))
50 /// Metadata encoding version.
51 /// N.B., increment this if you change the format of metadata such that
52 /// the rustc version can't be found to compare with `rustc_version()`.
53 const METADATA_VERSION: u8 = 6;
55 /// Metadata header which includes `METADATA_VERSION`.
57 /// This header is followed by the position of the `CrateRoot`,
58 /// which is encoded as a 32-bit big-endian unsigned integer,
59 /// and further followed by the rustc version string.
60 pub const METADATA_HEADER: &[u8] = &[b'r', b'u', b's', b't', 0, 0, 0, METADATA_VERSION];
62 /// Additional metadata for a `Lazy<T>` where `T` may not be `Sized`,
63 /// e.g. for `Lazy<[T]>`, this is the length (count of `T` values).
65 type Meta: Copy + 'static;
68 impl<T> LazyMeta for T {
72 impl<T> LazyMeta for [T] {
76 /// A value of type T referred to by its absolute position
77 /// in the metadata, and which can be decoded lazily.
79 /// Metadata is effective a tree, encoded in post-order,
80 /// and with the root's position written next to the header.
81 /// That means every single `Lazy` points to some previous
82 /// location in the metadata and is part of a larger node.
84 /// The first `Lazy` in a node is encoded as the backwards
85 /// distance from the position where the containing node
86 /// starts and where the `Lazy` points to, while the rest
87 /// use the forward distance from the previous `Lazy`.
88 /// Distances start at 1, as 0-byte nodes are invalid.
89 /// Also invalid are nodes being referred in a different
90 /// order than they were encoded in.
92 /// # Sequences (`Lazy<[T]>`)
94 /// Unlike `Lazy<Vec<T>>`, the length is encoded next to the
95 /// position, not at the position, which means that the length
96 /// doesn't need to be known before encoding all the elements.
98 /// If the length is 0, no position is encoded, but otherwise,
99 /// the encoding is that of `Lazy`, with the distinction that
100 /// the minimal distance the length of the sequence, i.e.
101 /// it's assumed there's no 0-byte element in the sequence.
103 // FIXME(#59875) the `Meta` parameter only exists to dodge
104 // invariance wrt `T` (coming from the `meta: T::Meta` field).
105 struct Lazy<T, Meta = <T as LazyMeta>::Meta>
107 T: ?Sized + LazyMeta<Meta = Meta>,
108 Meta: 'static + Copy,
110 position: NonZeroUsize,
112 _marker: PhantomData<T>,
115 impl<T: ?Sized + LazyMeta> Lazy<T> {
116 fn from_position_and_meta(position: NonZeroUsize, meta: T::Meta) -> Lazy<T> {
117 Lazy { position, meta, _marker: PhantomData }
122 fn from_position(position: NonZeroUsize) -> Lazy<T> {
123 Lazy::from_position_and_meta(position, ())
128 fn empty() -> Lazy<[T]> {
129 Lazy::from_position_and_meta(NonZeroUsize::new(1).unwrap(), 0)
133 impl<T: ?Sized + LazyMeta> Copy for Lazy<T> {}
134 impl<T: ?Sized + LazyMeta> Clone for Lazy<T> {
135 fn clone(&self) -> Self {
140 /// Encoding / decoding state for `Lazy`.
141 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
143 /// Outside of a metadata node.
146 /// Inside a metadata node, and before any `Lazy`.
147 /// The position is that of the node itself.
148 NodeStart(NonZeroUsize),
150 /// Inside a metadata node, with a previous `Lazy`.
151 /// The position is where that previous `Lazy` would start.
152 Previous(NonZeroUsize),
155 // FIXME(#59875) `Lazy!(T)` replaces `Lazy<T>`, passing the `Meta` parameter
156 // manually, instead of relying on the default, to get the correct variance.
157 // Only needed when `T` itself contains a parameter (e.g. `'tcx`).
159 (Table<$I:ty, $T:ty>) => {Lazy<Table<$I, $T>, usize>};
160 ([$T:ty]) => {Lazy<[$T], usize>};
161 ($T:ty) => {Lazy<$T, ()>};
164 type SyntaxContextTable = Lazy<Table<u32, Lazy<SyntaxContextData>>>;
165 type ExpnDataTable = Lazy<Table<ExpnIndex, Lazy<ExpnData>>>;
166 type ExpnHashTable = Lazy<Table<ExpnIndex, Lazy<ExpnHash>>>;
168 #[derive(MetadataEncodable, MetadataDecodable)]
169 crate struct ProcMacroData {
170 proc_macro_decls_static: DefIndex,
171 stability: Option<attr::Stability>,
172 macros: Lazy<[DefIndex]>,
175 /// Serialized metadata for a crate.
176 /// When compiling a proc-macro crate, we encode many of
177 /// the `Lazy<[T]>` fields as `Lazy::empty()`. This serves two purposes:
179 /// 1. We avoid performing unnecessary work. Proc-macro crates can only
180 /// export proc-macros functions, which are compiled into a shared library.
181 /// As a result, a large amount of the information we normally store
182 /// (e.g. optimized MIR) is unneeded by downstream crates.
183 /// 2. We avoid serializing invalid `CrateNum`s. When we deserialize
184 /// a proc-macro crate, we don't load any of its dependencies (since we
185 /// just need to invoke a native function from the shared library).
186 /// This means that any foreign `CrateNum`s that we serialize cannot be
187 /// deserialized, since we will not know how to map them into the current
188 /// compilation session. If we were to serialize a proc-macro crate like
189 /// a normal crate, much of what we serialized would be unusable in addition
191 #[derive(MetadataEncodable, MetadataDecodable)]
192 crate struct CrateRoot<'tcx> {
194 triple: TargetTriple,
195 extra_filename: String,
197 stable_crate_id: StableCrateId,
198 panic_strategy: PanicStrategy,
199 panic_in_drop_strategy: PanicStrategy,
201 has_global_allocator: bool,
202 has_panic_handler: bool,
203 has_default_lib_allocator: bool,
205 crate_deps: Lazy<[CrateDep]>,
206 dylib_dependency_formats: Lazy<[Option<LinkagePreference>]>,
207 lib_features: Lazy<[(Symbol, Option<Symbol>)]>,
208 lang_items: Lazy<[(DefIndex, usize)]>,
209 lang_items_missing: Lazy<[lang_items::LangItem]>,
210 diagnostic_items: Lazy<[(Symbol, DefIndex)]>,
211 native_libraries: Lazy<[NativeLib]>,
212 foreign_modules: Lazy<[ForeignModule]>,
213 traits: Lazy<[DefIndex]>,
214 impls: Lazy<[TraitImpls]>,
215 incoherent_impls: Lazy<[IncoherentImpls]>,
216 interpret_alloc_index: Lazy<[u32]>,
217 proc_macro_data: Option<ProcMacroData>,
219 tables: LazyTables<'tcx>,
221 exported_symbols: Lazy!([(ExportedSymbol<'tcx>, SymbolExportLevel)]),
223 syntax_contexts: SyntaxContextTable,
224 expn_data: ExpnDataTable,
225 expn_hashes: ExpnHashTable,
227 def_path_hash_map: Lazy<DefPathHashMapRef<'tcx>>,
229 source_map: Lazy<[rustc_span::SourceFile]>,
231 compiler_builtins: bool,
232 needs_allocator: bool,
233 needs_panic_runtime: bool,
236 profiler_runtime: bool,
237 symbol_mangling_version: SymbolManglingVersion,
240 #[derive(Encodable, Decodable)]
241 crate struct CrateDep {
244 pub host_hash: Option<Svh>,
245 pub kind: CrateDepKind,
246 pub extra_filename: String,
249 #[derive(MetadataEncodable, MetadataDecodable)]
250 crate struct TraitImpls {
251 trait_id: (u32, DefIndex),
252 impls: Lazy<[(DefIndex, Option<SimplifiedType>)]>,
255 #[derive(MetadataEncodable, MetadataDecodable)]
256 crate struct IncoherentImpls {
257 self_ty: SimplifiedType,
258 impls: Lazy<[DefIndex]>,
261 /// Define `LazyTables` and `TableBuilders` at the same time.
262 macro_rules! define_tables {
263 ($($name:ident: Table<$IDX:ty, $T:ty>),+ $(,)?) => {
264 #[derive(MetadataEncodable, MetadataDecodable)]
265 crate struct LazyTables<'tcx> {
266 $($name: Lazy!(Table<$IDX, $T>)),+
270 struct TableBuilders<'tcx> {
271 $($name: TableBuilder<$IDX, $T>),+
274 impl<'tcx> TableBuilders<'tcx> {
275 fn encode(&self, buf: &mut Encoder) -> LazyTables<'tcx> {
277 $($name: self.$name.encode(buf)),+
285 kind: Table<DefIndex, Lazy<EntryKind>>,
286 attributes: Table<DefIndex, Lazy<[ast::Attribute]>>,
287 children: Table<DefIndex, Lazy<[DefIndex]>>,
289 opt_def_kind: Table<DefIndex, Lazy<DefKind>>,
290 visibility: Table<DefIndex, Lazy<ty::Visibility>>,
291 def_span: Table<DefIndex, Lazy<Span>>,
292 def_ident_span: Table<DefIndex, Lazy<Span>>,
293 lookup_stability: Table<DefIndex, Lazy<attr::Stability>>,
294 lookup_const_stability: Table<DefIndex, Lazy<attr::ConstStability>>,
295 lookup_deprecation_entry: Table<DefIndex, Lazy<attr::Deprecation>>,
296 // As an optimization, a missing entry indicates an empty `&[]`.
297 explicit_item_bounds: Table<DefIndex, Lazy!([(ty::Predicate<'tcx>, Span)])>,
298 explicit_predicates_of: Table<DefIndex, Lazy!(ty::GenericPredicates<'tcx>)>,
299 generics_of: Table<DefIndex, Lazy<ty::Generics>>,
300 // As an optimization, a missing entry indicates an empty `&[]`.
301 inferred_outlives_of: Table<DefIndex, Lazy!([(ty::Predicate<'tcx>, Span)])>,
302 super_predicates_of: Table<DefIndex, Lazy!(ty::GenericPredicates<'tcx>)>,
303 type_of: Table<DefIndex, Lazy!(Ty<'tcx>)>,
304 variances_of: Table<DefIndex, Lazy<[ty::Variance]>>,
305 fn_sig: Table<DefIndex, Lazy!(ty::PolyFnSig<'tcx>)>,
306 impl_trait_ref: Table<DefIndex, Lazy!(ty::TraitRef<'tcx>)>,
307 const_param_default: Table<DefIndex, Lazy<rustc_middle::ty::Const<'tcx>>>,
308 optimized_mir: Table<DefIndex, Lazy!(mir::Body<'tcx>)>,
309 mir_for_ctfe: Table<DefIndex, Lazy!(mir::Body<'tcx>)>,
310 promoted_mir: Table<DefIndex, Lazy!(IndexVec<mir::Promoted, mir::Body<'tcx>>)>,
311 thir_abstract_const: Table<DefIndex, Lazy!(&'tcx [thir::abstract_const::Node<'tcx>])>,
312 impl_parent: Table<DefIndex, Lazy!(DefId)>,
313 impl_polarity: Table<DefIndex, Lazy!(ty::ImplPolarity)>,
314 impl_constness: Table<DefIndex, Lazy!(hir::Constness)>,
315 impl_defaultness: Table<DefIndex, Lazy!(hir::Defaultness)>,
316 // FIXME(eddyb) perhaps compute this on the fly if cheap enough?
317 coerce_unsized_info: Table<DefIndex, Lazy!(ty::adjustment::CoerceUnsizedInfo)>,
318 mir_const_qualif: Table<DefIndex, Lazy!(mir::ConstQualifs)>,
319 rendered_const: Table<DefIndex, Lazy!(String)>,
320 asyncness: Table<DefIndex, Lazy!(hir::IsAsync)>,
321 fn_arg_names: Table<DefIndex, Lazy!([Ident])>,
322 generator_kind: Table<DefIndex, Lazy!(hir::GeneratorKind)>,
324 trait_item_def_id: Table<DefIndex, Lazy<DefId>>,
325 inherent_impls: Table<DefIndex, Lazy<[DefIndex]>>,
326 expn_that_defined: Table<DefIndex, Lazy<ExpnId>>,
327 unused_generic_params: Table<DefIndex, Lazy<FiniteBitSet<u32>>>,
328 repr_options: Table<DefIndex, Lazy<ReprOptions>>,
329 // `def_keys` and `def_path_hashes` represent a lazy version of a
330 // `DefPathTable`. This allows us to avoid deserializing an entire
331 // `DefPathTable` up front, since we may only ever use a few
332 // definitions from any given crate.
333 def_keys: Table<DefIndex, Lazy<DefKey>>,
334 def_path_hashes: Table<DefIndex, Lazy<DefPathHash>>,
335 proc_macro_quoted_spans: Table<usize, Lazy<Span>>,
338 #[derive(Copy, Clone, MetadataEncodable, MetadataDecodable)]
353 Variant(Lazy<VariantData>),
354 Struct(Lazy<VariantData>),
355 Union(Lazy<VariantData>),
358 Mod(Lazy<[ModChild]>),
359 MacroDef(Lazy<ast::MacArgs>, /*macro_rules*/ bool),
360 ProcMacro(MacroKind),
363 Trait(Lazy<TraitData>),
365 AssocFn(Lazy<AssocFnData>),
366 AssocType(AssocContainer),
367 AssocConst(AssocContainer),
371 #[derive(TyEncodable, TyDecodable)]
374 discr: ty::VariantDiscr,
375 /// If this is unit or tuple-variant/struct, then this is the index of the ctor id.
376 ctor: Option<DefIndex>,
377 is_non_exhaustive: bool,
380 #[derive(TyEncodable, TyDecodable)]
382 unsafety: hir::Unsafety,
386 skip_array_during_method_dispatch: bool,
387 specialization_kind: ty::trait_def::TraitSpecializationKind,
388 must_implement_one_of: Option<Box<[Ident]>>,
391 /// Describes whether the container of an associated item
392 /// is a trait or an impl and whether, in a trait, it has
393 /// a default, or an in impl, whether it's marked "default".
394 #[derive(Copy, Clone, TyEncodable, TyDecodable)]
395 enum AssocContainer {
402 impl AssocContainer {
403 fn with_def_id(&self, def_id: DefId) -> ty::AssocItemContainer {
405 AssocContainer::TraitRequired | AssocContainer::TraitWithDefault => {
406 ty::TraitContainer(def_id)
409 AssocContainer::ImplDefault | AssocContainer::ImplFinal => ty::ImplContainer(def_id),
413 fn defaultness(&self) -> hir::Defaultness {
415 AssocContainer::TraitRequired => hir::Defaultness::Default { has_value: false },
417 AssocContainer::TraitWithDefault | AssocContainer::ImplDefault => {
418 hir::Defaultness::Default { has_value: true }
421 AssocContainer::ImplFinal => hir::Defaultness::Final,
426 #[derive(MetadataEncodable, MetadataDecodable)]
428 container: AssocContainer,
432 #[derive(TyEncodable, TyDecodable)]
433 struct GeneratorData<'tcx> {
434 layout: mir::GeneratorLayout<'tcx>,
437 // Tags used for encoding Spans:
438 const TAG_VALID_SPAN_LOCAL: u8 = 0;
439 const TAG_VALID_SPAN_FOREIGN: u8 = 1;
440 const TAG_PARTIAL_SPAN: u8 = 2;
442 pub fn provide(providers: &mut Providers) {
443 encoder::provide(providers);
444 decoder::provide(providers);