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};
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::ty::{self, ReprOptions, Ty};
19 use rustc_serialize::opaque::Encoder;
20 use rustc_session::config::SymbolManglingVersion;
21 use rustc_session::CrateDisambiguator;
22 use rustc_span::edition::Edition;
23 use rustc_span::hygiene::MacroKind;
24 use rustc_span::symbol::{Ident, Symbol};
25 use rustc_span::{self, ExpnData, 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 crate const METADATA_HEADER: &[u8; 8] = &[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<u32, Lazy<ExpnData>>>;
176 #[derive(MetadataEncodable, MetadataDecodable)]
177 crate struct ProcMacroData {
178 proc_macro_decls_static: DefIndex,
179 stability: Option<attr::Stability>,
180 macros: Lazy<[DefIndex]>,
183 /// Serialized metadata for a crate.
184 /// When compiling a proc-macro crate, we encode many of
185 /// the `Lazy<[T]>` fields as `Lazy::empty()`. This serves two purposes:
187 /// 1. We avoid performing unnecessary work. Proc-macro crates can only
188 /// export proc-macros functions, which are compiled into a shared library.
189 /// As a result, a large amount of the information we normally store
190 /// (e.g. optimized MIR) is unneeded by downstream crates.
191 /// 2. We avoid serializing invalid `CrateNum`s. When we deserialize
192 /// a proc-macro crate, we don't load any of its dependencies (since we
193 /// just need to invoke a native function from the shared library).
194 /// This means that any foreign `CrateNum`s that we serialize cannot be
195 /// deserialized, since we will not know how to map them into the current
196 /// compilation session. If we were to serialize a proc-macro crate like
197 /// a normal crate, much of what we serialized would be unusable in addition
199 #[derive(MetadataEncodable, MetadataDecodable)]
200 crate struct CrateRoot<'tcx> {
202 triple: TargetTriple,
203 extra_filename: String,
205 disambiguator: CrateDisambiguator,
206 panic_strategy: PanicStrategy,
208 has_global_allocator: bool,
209 has_panic_handler: bool,
210 has_default_lib_allocator: bool,
211 plugin_registrar_fn: Option<DefIndex>,
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,
232 source_map: Lazy<[rustc_span::SourceFile]>,
234 compiler_builtins: bool,
235 needs_allocator: bool,
236 needs_panic_runtime: bool,
239 profiler_runtime: bool,
240 symbol_mangling_version: SymbolManglingVersion,
243 #[derive(Encodable, Decodable)]
244 crate struct CrateDep {
247 pub host_hash: Option<Svh>,
248 pub kind: CrateDepKind,
249 pub extra_filename: String,
252 #[derive(MetadataEncodable, MetadataDecodable)]
253 crate struct TraitImpls {
254 trait_id: (u32, DefIndex),
255 impls: Lazy<[(DefIndex, Option<ty::fast_reject::SimplifiedType>)]>,
258 /// Define `LazyTables` and `TableBuilders` at the same time.
259 macro_rules! define_tables {
260 ($($name:ident: Table<DefIndex, $T:ty>),+ $(,)?) => {
261 #[derive(MetadataEncodable, MetadataDecodable)]
262 crate struct LazyTables<'tcx> {
263 $($name: Lazy!(Table<DefIndex, $T>)),+
267 struct TableBuilders<'tcx> {
268 $($name: TableBuilder<DefIndex, $T>),+
271 impl TableBuilders<'tcx> {
272 fn encode(&self, buf: &mut Encoder) -> LazyTables<'tcx> {
274 $($name: self.$name.encode(buf)),+
282 def_kind: Table<DefIndex, Lazy<DefKind>>,
283 kind: Table<DefIndex, Lazy<EntryKind>>,
284 visibility: Table<DefIndex, Lazy<ty::Visibility>>,
285 span: Table<DefIndex, Lazy<Span>>,
286 ident_span: Table<DefIndex, Lazy<Span>>,
287 attributes: Table<DefIndex, Lazy<[ast::Attribute]>>,
288 children: Table<DefIndex, Lazy<[DefIndex]>>,
289 stability: Table<DefIndex, Lazy<attr::Stability>>,
290 const_stability: Table<DefIndex, Lazy<attr::ConstStability>>,
291 deprecation: Table<DefIndex, Lazy<attr::Deprecation>>,
292 ty: Table<DefIndex, Lazy!(Ty<'tcx>)>,
293 fn_sig: Table<DefIndex, Lazy!(ty::PolyFnSig<'tcx>)>,
294 impl_trait_ref: Table<DefIndex, Lazy!(ty::TraitRef<'tcx>)>,
295 inherent_impls: Table<DefIndex, Lazy<[DefIndex]>>,
296 variances: Table<DefIndex, Lazy<[ty::Variance]>>,
297 generics: Table<DefIndex, Lazy<ty::Generics>>,
298 explicit_predicates: Table<DefIndex, Lazy!(ty::GenericPredicates<'tcx>)>,
299 expn_that_defined: Table<DefIndex, Lazy<ExpnId>>,
300 // As an optimization, a missing entry indicates an empty `&[]`.
301 inferred_outlives: Table<DefIndex, Lazy!([(ty::Predicate<'tcx>, Span)])>,
302 super_predicates: Table<DefIndex, Lazy!(ty::GenericPredicates<'tcx>)>,
303 // As an optimization, a missing entry indicates an empty `&[]`.
304 explicit_item_bounds: Table<DefIndex, Lazy!([(ty::Predicate<'tcx>, Span)])>,
305 mir: Table<DefIndex, Lazy!(mir::Body<'tcx>)>,
306 mir_for_ctfe: Table<DefIndex, Lazy!(mir::Body<'tcx>)>,
307 promoted_mir: Table<DefIndex, Lazy!(IndexVec<mir::Promoted, mir::Body<'tcx>>)>,
308 mir_abstract_consts: Table<DefIndex, Lazy!(&'tcx [mir::abstract_const::Node<'tcx>])>,
309 unused_generic_params: Table<DefIndex, Lazy<FiniteBitSet<u32>>>,
310 // `def_keys` and `def_path_hashes` represent a lazy version of a
311 // `DefPathTable`. This allows us to avoid deserializing an entire
312 // `DefPathTable` up front, since we may only ever use a few
313 // definitions from any given crate.
314 def_keys: Table<DefIndex, Lazy<DefKey>>,
315 def_path_hashes: Table<DefIndex, Lazy<DefPathHash>>
318 #[derive(Copy, Clone, MetadataEncodable, MetadataDecodable)]
320 AnonConst(mir::ConstQualifs, Lazy<RenderedConst>),
321 Const(mir::ConstQualifs, Lazy<RenderedConst>),
335 Variant(Lazy<VariantData>),
336 Struct(Lazy<VariantData>, ReprOptions),
337 Union(Lazy<VariantData>, ReprOptions),
339 ForeignFn(Lazy<FnData>),
341 MacroDef(Lazy<MacroDef>),
342 ProcMacro(MacroKind),
344 Generator(hir::GeneratorKind),
345 Trait(Lazy<TraitData>),
346 Impl(Lazy<ImplData>),
347 AssocFn(Lazy<AssocFnData>),
348 AssocType(AssocContainer),
349 AssocConst(AssocContainer, mir::ConstQualifs, Lazy<RenderedConst>),
353 /// Contains a constant which has been rendered to a String.
355 #[derive(Encodable, Decodable)]
356 struct RenderedConst(String);
358 #[derive(MetadataEncodable, MetadataDecodable)]
360 reexports: Lazy<[Export<hir::HirId>]>,
364 #[derive(MetadataEncodable, MetadataDecodable)]
366 asyncness: hir::IsAsync,
367 constness: hir::Constness,
368 param_names: Lazy<[Ident]>,
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 specialization_kind: ty::trait_def::TraitSpecializationKind,
389 #[derive(TyEncodable, TyDecodable)]
391 polarity: ty::ImplPolarity,
392 defaultness: hir::Defaultness,
393 parent_impl: Option<DefId>,
395 /// This is `Some` only for impls of `CoerceUnsized`.
396 // FIXME(eddyb) perhaps compute this on the fly if cheap enough?
397 coerce_unsized_info: Option<ty::adjustment::CoerceUnsizedInfo>,
400 /// Describes whether the container of an associated item
401 /// is a trait or an impl and whether, in a trait, it has
402 /// a default, or an in impl, whether it's marked "default".
403 #[derive(Copy, Clone, TyEncodable, TyDecodable)]
404 enum AssocContainer {
411 impl AssocContainer {
412 fn with_def_id(&self, def_id: DefId) -> ty::AssocItemContainer {
414 AssocContainer::TraitRequired | AssocContainer::TraitWithDefault => {
415 ty::TraitContainer(def_id)
418 AssocContainer::ImplDefault | AssocContainer::ImplFinal => ty::ImplContainer(def_id),
422 fn defaultness(&self) -> hir::Defaultness {
424 AssocContainer::TraitRequired => hir::Defaultness::Default { has_value: false },
426 AssocContainer::TraitWithDefault | AssocContainer::ImplDefault => {
427 hir::Defaultness::Default { has_value: true }
430 AssocContainer::ImplFinal => hir::Defaultness::Final,
435 #[derive(MetadataEncodable, MetadataDecodable)]
438 container: AssocContainer,
442 #[derive(TyEncodable, TyDecodable)]
443 struct GeneratorData<'tcx> {
444 layout: mir::GeneratorLayout<'tcx>,
447 // Tags used for encoding Spans:
448 const TAG_VALID_SPAN_LOCAL: u8 = 0;
449 const TAG_VALID_SPAN_FOREIGN: u8 = 1;
450 const TAG_INVALID_SPAN: u8 = 2;