2 use table::{Table, TableBuilder};
4 use rustc_ast::{self as ast, MacroDef};
5 use rustc_attr as attr;
6 use rustc_data_structures::svh::Svh;
7 use rustc_data_structures::sync::MetadataRef;
9 use rustc_hir::def::{CtorKind, DefKind};
10 use rustc_hir::def_id::{DefId, DefIndex, DefPathHash, StableCrateId};
11 use rustc_hir::definitions::DefKey;
12 use rustc_hir::lang_items;
13 use rustc_index::{bit_set::FiniteBitSet, vec::IndexVec};
14 use rustc_middle::hir::exports::Export;
15 use rustc_middle::middle::cstore::{CrateDepKind, ForeignModule, LinkagePreference, NativeLib};
16 use rustc_middle::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel};
17 use rustc_middle::mir;
18 use rustc_middle::thir;
19 use rustc_middle::ty::{self, ReprOptions, Ty};
20 use rustc_serialize::opaque::Encoder;
21 use rustc_session::config::SymbolManglingVersion;
22 use rustc_span::edition::Edition;
23 use rustc_span::hygiene::{ExpnIndex, MacroKind};
24 use rustc_span::symbol::{Ident, Symbol};
25 use rustc_span::{self, ExpnData, ExpnHash, ExpnId, Span};
26 use rustc_target::spec::{PanicStrategy, TargetTriple};
28 use std::marker::PhantomData;
29 use std::num::NonZeroUsize;
31 use decoder::DecodeContext;
32 pub use decoder::{provide, provide_extern};
33 crate use decoder::{CrateMetadata, CrateNumMap, MetadataBlob};
34 use encoder::EncodeContext;
35 use rustc_span::hygiene::SyntaxContextData;
41 crate fn rustc_version() -> String {
42 format!("rustc {}", option_env!("CFG_VERSION").unwrap_or("unknown version"))
45 /// Metadata encoding version.
46 /// N.B., increment this if you change the format of metadata such that
47 /// the rustc version can't be found to compare with `rustc_version()`.
48 const METADATA_VERSION: u8 = 5;
50 /// Metadata header which includes `METADATA_VERSION`.
52 /// This header is followed by the position of the `CrateRoot`,
53 /// which is encoded as a 32-bit big-endian unsigned integer,
54 /// and further followed by the rustc version string.
55 pub const METADATA_HEADER: &[u8] = &[b'r', b'u', b's', b't', 0, 0, 0, METADATA_VERSION];
57 /// Additional metadata for a `Lazy<T>` where `T` may not be `Sized`,
58 /// e.g. for `Lazy<[T]>`, this is the length (count of `T` values).
60 type Meta: Copy + 'static;
62 /// Returns the minimum encoded size.
63 // FIXME(eddyb) Give better estimates for certain types.
64 fn min_size(meta: Self::Meta) -> usize;
67 impl<T> LazyMeta for T {
70 fn min_size(_: ()) -> usize {
71 assert_ne!(std::mem::size_of::<T>(), 0);
76 impl<T> LazyMeta for [T] {
79 fn min_size(len: usize) -> usize {
84 /// A value of type T referred to by its absolute position
85 /// in the metadata, and which can be decoded lazily.
87 /// Metadata is effective a tree, encoded in post-order,
88 /// and with the root's position written next to the header.
89 /// That means every single `Lazy` points to some previous
90 /// location in the metadata and is part of a larger node.
92 /// The first `Lazy` in a node is encoded as the backwards
93 /// distance from the position where the containing node
94 /// starts and where the `Lazy` points to, while the rest
95 /// use the forward distance from the previous `Lazy`.
96 /// Distances start at 1, as 0-byte nodes are invalid.
97 /// Also invalid are nodes being referred in a different
98 /// order than they were encoded in.
100 /// # Sequences (`Lazy<[T]>`)
102 /// Unlike `Lazy<Vec<T>>`, the length is encoded next to the
103 /// position, not at the position, which means that the length
104 /// doesn't need to be known before encoding all the elements.
106 /// If the length is 0, no position is encoded, but otherwise,
107 /// the encoding is that of `Lazy`, with the distinction that
108 /// the minimal distance the length of the sequence, i.e.
109 /// it's assumed there's no 0-byte element in the sequence.
111 // FIXME(#59875) the `Meta` parameter only exists to dodge
112 // invariance wrt `T` (coming from the `meta: T::Meta` field).
113 struct Lazy<T, Meta = <T as LazyMeta>::Meta>
115 T: ?Sized + LazyMeta<Meta = Meta>,
116 Meta: 'static + Copy,
118 position: NonZeroUsize,
120 _marker: PhantomData<T>,
123 impl<T: ?Sized + LazyMeta> Lazy<T> {
124 fn from_position_and_meta(position: NonZeroUsize, meta: T::Meta) -> Lazy<T> {
125 Lazy { position, meta, _marker: PhantomData }
130 fn from_position(position: NonZeroUsize) -> Lazy<T> {
131 Lazy::from_position_and_meta(position, ())
136 fn empty() -> Lazy<[T]> {
137 Lazy::from_position_and_meta(NonZeroUsize::new(1).unwrap(), 0)
141 impl<T: ?Sized + LazyMeta> Copy for Lazy<T> {}
142 impl<T: ?Sized + LazyMeta> Clone for Lazy<T> {
143 fn clone(&self) -> Self {
148 /// Encoding / decoding state for `Lazy`.
149 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
151 /// Outside of a metadata node.
154 /// Inside a metadata node, and before any `Lazy`.
155 /// The position is that of the node itself.
156 NodeStart(NonZeroUsize),
158 /// Inside a metadata node, with a previous `Lazy`.
159 /// The position is a conservative estimate of where that
160 /// previous `Lazy` would end (see their comments).
161 Previous(NonZeroUsize),
164 // FIXME(#59875) `Lazy!(T)` replaces `Lazy<T>`, passing the `Meta` parameter
165 // manually, instead of relying on the default, to get the correct variance.
166 // Only needed when `T` itself contains a parameter (e.g. `'tcx`).
168 (Table<$I:ty, $T:ty>) => {Lazy<Table<$I, $T>, usize>};
169 ([$T:ty]) => {Lazy<[$T], usize>};
170 ($T:ty) => {Lazy<$T, ()>};
173 type SyntaxContextTable = Lazy<Table<u32, Lazy<SyntaxContextData>>>;
174 type ExpnDataTable = Lazy<Table<ExpnIndex, Lazy<ExpnData>>>;
175 type ExpnHashTable = Lazy<Table<ExpnIndex, Lazy<ExpnHash>>>;
177 #[derive(MetadataEncodable, MetadataDecodable)]
178 crate struct ProcMacroData {
179 proc_macro_decls_static: DefIndex,
180 stability: Option<attr::Stability>,
181 macros: Lazy<[DefIndex]>,
184 /// Serialized metadata for a crate.
185 /// When compiling a proc-macro crate, we encode many of
186 /// the `Lazy<[T]>` fields as `Lazy::empty()`. This serves two purposes:
188 /// 1. We avoid performing unnecessary work. Proc-macro crates can only
189 /// export proc-macros functions, which are compiled into a shared library.
190 /// As a result, a large amount of the information we normally store
191 /// (e.g. optimized MIR) is unneeded by downstream crates.
192 /// 2. We avoid serializing invalid `CrateNum`s. When we deserialize
193 /// a proc-macro crate, we don't load any of its dependencies (since we
194 /// just need to invoke a native function from the shared library).
195 /// This means that any foreign `CrateNum`s that we serialize cannot be
196 /// deserialized, since we will not know how to map them into the current
197 /// compilation session. If we were to serialize a proc-macro crate like
198 /// a normal crate, much of what we serialized would be unusable in addition
200 #[derive(MetadataEncodable, MetadataDecodable)]
201 crate struct CrateRoot<'tcx> {
203 triple: TargetTriple,
204 extra_filename: String,
206 stable_crate_id: StableCrateId,
207 panic_strategy: PanicStrategy,
209 has_global_allocator: bool,
210 has_panic_handler: bool,
211 has_default_lib_allocator: bool,
213 crate_deps: Lazy<[CrateDep]>,
214 dylib_dependency_formats: Lazy<[Option<LinkagePreference>]>,
215 lib_features: Lazy<[(Symbol, Option<Symbol>)]>,
216 lang_items: Lazy<[(DefIndex, usize)]>,
217 lang_items_missing: Lazy<[lang_items::LangItem]>,
218 diagnostic_items: Lazy<[(Symbol, DefIndex)]>,
219 native_libraries: Lazy<[NativeLib]>,
220 foreign_modules: Lazy<[ForeignModule]>,
221 impls: Lazy<[TraitImpls]>,
222 interpret_alloc_index: Lazy<[u32]>,
223 proc_macro_data: Option<ProcMacroData>,
225 tables: LazyTables<'tcx>,
227 exported_symbols: Lazy!([(ExportedSymbol<'tcx>, SymbolExportLevel)]),
229 syntax_contexts: SyntaxContextTable,
230 expn_data: ExpnDataTable,
231 expn_hashes: ExpnHashTable,
233 source_map: Lazy<[rustc_span::SourceFile]>,
235 compiler_builtins: bool,
236 needs_allocator: bool,
237 needs_panic_runtime: bool,
240 profiler_runtime: bool,
241 symbol_mangling_version: SymbolManglingVersion,
244 #[derive(Encodable, Decodable)]
245 crate struct CrateDep {
248 pub host_hash: Option<Svh>,
249 pub kind: CrateDepKind,
250 pub extra_filename: String,
253 #[derive(MetadataEncodable, MetadataDecodable)]
254 crate struct TraitImpls {
255 trait_id: (u32, DefIndex),
256 impls: Lazy<[(DefIndex, Option<ty::fast_reject::SimplifiedType>)]>,
259 /// Define `LazyTables` and `TableBuilders` at the same time.
260 macro_rules! define_tables {
261 ($($name:ident: Table<$IDX:ty, $T:ty>),+ $(,)?) => {
262 #[derive(MetadataEncodable, MetadataDecodable)]
263 crate struct LazyTables<'tcx> {
264 $($name: Lazy!(Table<$IDX, $T>)),+
268 struct TableBuilders<'tcx> {
269 $($name: TableBuilder<$IDX, $T>),+
272 impl TableBuilders<'tcx> {
273 fn encode(&self, buf: &mut Encoder) -> LazyTables<'tcx> {
275 $($name: self.$name.encode(buf)),+
283 def_kind: Table<DefIndex, Lazy<DefKind>>,
284 kind: Table<DefIndex, Lazy<EntryKind>>,
285 visibility: Table<DefIndex, Lazy<ty::Visibility>>,
286 span: Table<DefIndex, Lazy<Span>>,
287 ident_span: Table<DefIndex, Lazy<Span>>,
288 attributes: Table<DefIndex, Lazy<[ast::Attribute]>>,
289 children: Table<DefIndex, Lazy<[DefIndex]>>,
290 stability: Table<DefIndex, Lazy<attr::Stability>>,
291 const_stability: Table<DefIndex, Lazy<attr::ConstStability>>,
292 deprecation: Table<DefIndex, Lazy<attr::Deprecation>>,
293 ty: Table<DefIndex, Lazy!(Ty<'tcx>)>,
294 fn_sig: Table<DefIndex, Lazy!(ty::PolyFnSig<'tcx>)>,
295 impl_trait_ref: Table<DefIndex, Lazy!(ty::TraitRef<'tcx>)>,
296 inherent_impls: Table<DefIndex, Lazy<[DefIndex]>>,
297 variances: Table<DefIndex, Lazy<[ty::Variance]>>,
298 generics: Table<DefIndex, Lazy<ty::Generics>>,
299 explicit_predicates: Table<DefIndex, Lazy!(ty::GenericPredicates<'tcx>)>,
300 expn_that_defined: Table<DefIndex, Lazy<ExpnId>>,
301 // As an optimization, a missing entry indicates an empty `&[]`.
302 inferred_outlives: Table<DefIndex, Lazy!([(ty::Predicate<'tcx>, Span)])>,
303 super_predicates: Table<DefIndex, Lazy!(ty::GenericPredicates<'tcx>)>,
304 // As an optimization, a missing entry indicates an empty `&[]`.
305 explicit_item_bounds: Table<DefIndex, Lazy!([(ty::Predicate<'tcx>, Span)])>,
306 mir: Table<DefIndex, Lazy!(mir::Body<'tcx>)>,
307 mir_for_ctfe: Table<DefIndex, Lazy!(mir::Body<'tcx>)>,
308 promoted_mir: Table<DefIndex, Lazy!(IndexVec<mir::Promoted, mir::Body<'tcx>>)>,
309 thir_abstract_consts: Table<DefIndex, Lazy!(&'tcx [thir::abstract_const::Node<'tcx>])>,
310 const_defaults: Table<DefIndex, Lazy<rustc_middle::ty::Const<'tcx>>>,
311 unused_generic_params: Table<DefIndex, Lazy<FiniteBitSet<u32>>>,
312 // `def_keys` and `def_path_hashes` represent a lazy version of a
313 // `DefPathTable`. This allows us to avoid deserializing an entire
314 // `DefPathTable` up front, since we may only ever use a few
315 // definitions from any given crate.
316 def_keys: Table<DefIndex, Lazy<DefKey>>,
317 def_path_hashes: Table<DefIndex, Lazy<DefPathHash>>,
318 proc_macro_quoted_spans: Table<usize, Lazy<Span>>,
321 #[derive(Copy, Clone, MetadataEncodable, MetadataDecodable)]
323 AnonConst(mir::ConstQualifs, Lazy<RenderedConst>),
324 Const(mir::ConstQualifs, Lazy<RenderedConst>),
338 Variant(Lazy<VariantData>),
339 Struct(Lazy<VariantData>, ReprOptions),
340 Union(Lazy<VariantData>, ReprOptions),
342 ForeignFn(Lazy<FnData>),
344 MacroDef(Lazy<MacroDef>),
345 ProcMacro(MacroKind),
347 Generator(hir::GeneratorKind),
348 Trait(Lazy<TraitData>),
349 Impl(Lazy<ImplData>),
350 AssocFn(Lazy<AssocFnData>),
351 AssocType(AssocContainer),
352 AssocConst(AssocContainer, mir::ConstQualifs, Lazy<RenderedConst>),
356 /// Contains a constant which has been rendered to a String.
358 #[derive(Encodable, Decodable)]
359 struct RenderedConst(String);
361 #[derive(MetadataEncodable, MetadataDecodable)]
363 reexports: Lazy<[Export]>,
367 #[derive(MetadataEncodable, MetadataDecodable)]
369 asyncness: hir::IsAsync,
370 constness: hir::Constness,
371 param_names: Lazy<[Ident]>,
374 #[derive(TyEncodable, TyDecodable)]
377 discr: ty::VariantDiscr,
378 /// If this is unit or tuple-variant/struct, then this is the index of the ctor id.
379 ctor: Option<DefIndex>,
380 is_non_exhaustive: bool,
383 #[derive(TyEncodable, TyDecodable)]
385 unsafety: hir::Unsafety,
389 skip_array_during_method_dispatch: bool,
390 specialization_kind: ty::trait_def::TraitSpecializationKind,
393 #[derive(TyEncodable, TyDecodable)]
395 polarity: ty::ImplPolarity,
396 constness: hir::Constness,
397 defaultness: hir::Defaultness,
398 parent_impl: Option<DefId>,
400 /// This is `Some` only for impls of `CoerceUnsized`.
401 // FIXME(eddyb) perhaps compute this on the fly if cheap enough?
402 coerce_unsized_info: Option<ty::adjustment::CoerceUnsizedInfo>,
405 /// Describes whether the container of an associated item
406 /// is a trait or an impl and whether, in a trait, it has
407 /// a default, or an in impl, whether it's marked "default".
408 #[derive(Copy, Clone, TyEncodable, TyDecodable)]
409 enum AssocContainer {
416 impl AssocContainer {
417 fn with_def_id(&self, def_id: DefId) -> ty::AssocItemContainer {
419 AssocContainer::TraitRequired | AssocContainer::TraitWithDefault => {
420 ty::TraitContainer(def_id)
423 AssocContainer::ImplDefault | AssocContainer::ImplFinal => ty::ImplContainer(def_id),
427 fn defaultness(&self) -> hir::Defaultness {
429 AssocContainer::TraitRequired => hir::Defaultness::Default { has_value: false },
431 AssocContainer::TraitWithDefault | AssocContainer::ImplDefault => {
432 hir::Defaultness::Default { has_value: true }
435 AssocContainer::ImplFinal => hir::Defaultness::Final,
440 #[derive(MetadataEncodable, MetadataDecodable)]
443 container: AssocContainer,
447 #[derive(TyEncodable, TyDecodable)]
448 struct GeneratorData<'tcx> {
449 layout: mir::GeneratorLayout<'tcx>,
452 // Tags used for encoding Spans:
453 const TAG_VALID_SPAN_LOCAL: u8 = 0;
454 const TAG_VALID_SPAN_FOREIGN: u8 = 1;
455 const TAG_PARTIAL_SPAN: u8 = 2;