2 use table::{Table, TableBuilder};
5 use rustc::hir::def::{self, CtorKind};
6 use rustc::hir::def_id::{DefId, DefIndex};
7 use rustc::middle::cstore::{DepKind, ForeignModule, LinkagePreference, NativeLibrary};
8 use rustc::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel};
9 use rustc::middle::lang_items;
11 use rustc::session::config::SymbolManglingVersion;
12 use rustc::session::CrateDisambiguator;
13 use rustc::ty::{self, ReprOptions, Ty};
14 use rustc_data_structures::svh::Svh;
15 use rustc_data_structures::sync::MetadataRef;
16 use rustc_index::vec::IndexVec;
17 use rustc_serialize::opaque::Encoder;
18 use rustc_span::edition::Edition;
19 use rustc_span::symbol::Symbol;
20 use rustc_span::{self, Span};
21 use rustc_target::spec::{PanicStrategy, TargetTriple};
22 use syntax::{ast, attr};
24 use std::marker::PhantomData;
25 use std::num::NonZeroUsize;
27 pub use decoder::{provide, provide_extern};
28 crate use decoder::{CrateMetadata, CrateNumMap, MetadataBlob};
34 crate fn rustc_version() -> String {
35 format!("rustc {}", option_env!("CFG_VERSION").unwrap_or("unknown version"))
38 /// Metadata encoding version.
39 /// N.B., increment this if you change the format of metadata such that
40 /// the rustc version can't be found to compare with `rustc_version()`.
41 const METADATA_VERSION: u8 = 5;
43 /// Metadata header which includes `METADATA_VERSION`.
45 /// This header is followed by the position of the `CrateRoot`,
46 /// which is encoded as a 32-bit big-endian unsigned integer,
47 /// and further followed by the rustc version string.
48 crate const METADATA_HEADER: &[u8; 8] = &[b'r', b'u', b's', b't', 0, 0, 0, METADATA_VERSION];
50 /// Additional metadata for a `Lazy<T>` where `T` may not be `Sized`,
51 /// e.g. for `Lazy<[T]>`, this is the length (count of `T` values).
53 type Meta: Copy + 'static;
55 /// Returns the minimum encoded size.
56 // FIXME(eddyb) Give better estimates for certain types.
57 fn min_size(meta: Self::Meta) -> usize;
60 impl<T> LazyMeta for T {
63 fn min_size(_: ()) -> usize {
64 assert_ne!(std::mem::size_of::<T>(), 0);
69 impl<T> LazyMeta for [T] {
72 fn min_size(len: usize) -> usize {
77 /// A value of type T referred to by its absolute position
78 /// in the metadata, and which can be decoded lazily.
80 /// Metadata is effective a tree, encoded in post-order,
81 /// and with the root's position written next to the header.
82 /// That means every single `Lazy` points to some previous
83 /// location in the metadata and is part of a larger node.
85 /// The first `Lazy` in a node is encoded as the backwards
86 /// distance from the position where the containing node
87 /// starts and where the `Lazy` points to, while the rest
88 /// use the forward distance from the previous `Lazy`.
89 /// Distances start at 1, as 0-byte nodes are invalid.
90 /// Also invalid are nodes being referred in a different
91 /// order than they were encoded in.
93 /// # Sequences (`Lazy<[T]>`)
95 /// Unlike `Lazy<Vec<T>>`, the length is encoded next to the
96 /// position, not at the position, which means that the length
97 /// doesn't need to be known before encoding all the elements.
99 /// If the length is 0, no position is encoded, but otherwise,
100 /// the encoding is that of `Lazy`, with the distinction that
101 /// the minimal distance the length of the sequence, i.e.
102 /// it's assumed there's no 0-byte element in the sequence.
104 // FIXME(#59875) the `Meta` parameter only exists to dodge
105 // invariance wrt `T` (coming from the `meta: T::Meta` field).
106 struct Lazy<T, Meta = <T as LazyMeta>::Meta>
108 T: ?Sized + LazyMeta<Meta = Meta>,
109 Meta: 'static + Copy,
111 position: NonZeroUsize,
113 _marker: PhantomData<T>,
116 impl<T: ?Sized + LazyMeta> Lazy<T> {
117 fn from_position_and_meta(position: NonZeroUsize, meta: T::Meta) -> Lazy<T> {
118 Lazy { position, meta, _marker: PhantomData }
123 fn from_position(position: NonZeroUsize) -> Lazy<T> {
124 Lazy::from_position_and_meta(position, ())
129 fn empty() -> Lazy<[T]> {
130 Lazy::from_position_and_meta(NonZeroUsize::new(1).unwrap(), 0)
134 impl<T: ?Sized + LazyMeta> Copy for Lazy<T> {}
135 impl<T: ?Sized + LazyMeta> Clone for Lazy<T> {
136 fn clone(&self) -> Self {
141 impl<T: ?Sized + LazyMeta> rustc_serialize::UseSpecializedEncodable for Lazy<T> {}
142 impl<T: ?Sized + LazyMeta> rustc_serialize::UseSpecializedDecodable for Lazy<T> {}
144 /// Encoding / decoding state for `Lazy`.
145 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
147 /// Outside of a metadata node.
150 /// Inside a metadata node, and before any `Lazy`.
151 /// The position is that of the node itself.
152 NodeStart(NonZeroUsize),
154 /// Inside a metadata node, with a previous `Lazy`.
155 /// The position is a conservative estimate of where that
156 /// previous `Lazy` would end (see their comments).
157 Previous(NonZeroUsize),
160 // FIXME(#59875) `Lazy!(T)` replaces `Lazy<T>`, passing the `Meta` parameter
161 // manually, instead of relying on the default, to get the correct variance.
162 // Only needed when `T` itself contains a parameter (e.g. `'tcx`).
164 (Table<$I:ty, $T:ty>) => {Lazy<Table<$I, $T>, usize>};
165 ([$T:ty]) => {Lazy<[$T], usize>};
166 ($T:ty) => {Lazy<$T, ()>};
169 #[derive(RustcEncodable, RustcDecodable)]
170 crate struct CrateRoot<'tcx> {
172 triple: TargetTriple,
173 extra_filename: String,
175 disambiguator: CrateDisambiguator,
176 panic_strategy: PanicStrategy,
178 has_global_allocator: bool,
179 has_panic_handler: bool,
180 has_default_lib_allocator: bool,
181 plugin_registrar_fn: Option<DefIndex>,
182 proc_macro_decls_static: Option<DefIndex>,
183 proc_macro_stability: Option<attr::Stability>,
185 crate_deps: Lazy<[CrateDep]>,
186 dylib_dependency_formats: Lazy<[Option<LinkagePreference>]>,
187 lib_features: Lazy<[(Symbol, Option<Symbol>)]>,
188 lang_items: Lazy<[(DefIndex, usize)]>,
189 lang_items_missing: Lazy<[lang_items::LangItem]>,
190 diagnostic_items: Lazy<[(Symbol, DefIndex)]>,
191 native_libraries: Lazy<[NativeLibrary]>,
192 foreign_modules: Lazy<[ForeignModule]>,
193 source_map: Lazy<[rustc_span::SourceFile]>,
194 def_path_table: Lazy<hir::map::definitions::DefPathTable>,
195 impls: Lazy<[TraitImpls]>,
196 exported_symbols: Lazy!([(ExportedSymbol<'tcx>, SymbolExportLevel)]),
197 interpret_alloc_index: Lazy<[u32]>,
199 per_def: LazyPerDefTables<'tcx>,
201 /// The DefIndex's of any proc macros delcared by this crate.
202 proc_macro_data: Option<Lazy<[DefIndex]>>,
204 compiler_builtins: bool,
205 needs_allocator: bool,
206 needs_panic_runtime: bool,
209 profiler_runtime: bool,
210 sanitizer_runtime: bool,
211 symbol_mangling_version: SymbolManglingVersion,
214 #[derive(RustcEncodable, RustcDecodable)]
215 crate struct CrateDep {
218 pub host_hash: Option<Svh>,
220 pub extra_filename: String,
223 #[derive(RustcEncodable, RustcDecodable)]
224 crate struct TraitImpls {
225 trait_id: (u32, DefIndex),
226 impls: Lazy<[DefIndex]>,
229 /// Define `LazyPerDefTables` and `PerDefTableBuilders` at the same time.
230 macro_rules! define_per_def_tables {
231 ($($name:ident: Table<DefIndex, $T:ty>),+ $(,)?) => {
232 #[derive(RustcEncodable, RustcDecodable)]
233 crate struct LazyPerDefTables<'tcx> {
234 $($name: Lazy!(Table<DefIndex, $T>)),+
238 struct PerDefTableBuilders<'tcx> {
239 $($name: TableBuilder<DefIndex, $T>),+
242 impl PerDefTableBuilders<'tcx> {
243 fn encode(&self, buf: &mut Encoder) -> LazyPerDefTables<'tcx> {
245 $($name: self.$name.encode(buf)),+
252 define_per_def_tables! {
253 kind: Table<DefIndex, Lazy!(EntryKind<'tcx>)>,
254 visibility: Table<DefIndex, Lazy<ty::Visibility>>,
255 span: Table<DefIndex, Lazy<Span>>,
256 attributes: Table<DefIndex, Lazy<[ast::Attribute]>>,
257 children: Table<DefIndex, Lazy<[DefIndex]>>,
258 stability: Table<DefIndex, Lazy<attr::Stability>>,
259 const_stability: Table<DefIndex, Lazy<attr::ConstStability>>,
260 deprecation: Table<DefIndex, Lazy<attr::Deprecation>>,
261 ty: Table<DefIndex, Lazy!(Ty<'tcx>)>,
262 fn_sig: Table<DefIndex, Lazy!(ty::PolyFnSig<'tcx>)>,
263 impl_trait_ref: Table<DefIndex, Lazy!(ty::TraitRef<'tcx>)>,
264 inherent_impls: Table<DefIndex, Lazy<[DefIndex]>>,
265 variances: Table<DefIndex, Lazy<[ty::Variance]>>,
266 generics: Table<DefIndex, Lazy<ty::Generics>>,
267 explicit_predicates: Table<DefIndex, Lazy!(ty::GenericPredicates<'tcx>)>,
268 // FIXME(eddyb) this would ideally be `Lazy<[...]>` but `ty::Predicate`
269 // doesn't handle shorthands in its own (de)serialization impls,
270 // as it's an `enum` for which we want to derive (de)serialization,
271 // so the `ty::codec` APIs handle the whole `&'tcx [...]` at once.
272 // Also, as an optimization, a missing entry indicates an empty `&[]`.
273 inferred_outlives: Table<DefIndex, Lazy!(&'tcx [(ty::Predicate<'tcx>, Span)])>,
274 super_predicates: Table<DefIndex, Lazy!(ty::GenericPredicates<'tcx>)>,
275 mir: Table<DefIndex, Lazy!(mir::BodyAndCache<'tcx>)>,
276 promoted_mir: Table<DefIndex, Lazy!(IndexVec<mir::Promoted, mir::BodyAndCache<'tcx>>)>,
279 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
280 enum EntryKind<'tcx> {
281 Const(mir::ConstQualifs, Lazy<RenderedConst>),
295 Variant(Lazy<VariantData>),
296 Struct(Lazy<VariantData>, ReprOptions),
297 Union(Lazy<VariantData>, ReprOptions),
299 ForeignFn(Lazy<FnData>),
301 MacroDef(Lazy<MacroDef>),
303 Generator(Lazy!(GeneratorData<'tcx>)),
304 Trait(Lazy<TraitData>),
305 Impl(Lazy<ImplData>),
306 Method(Lazy<MethodData>),
307 AssocType(AssocContainer),
308 AssocOpaqueTy(AssocContainer),
309 AssocConst(AssocContainer, mir::ConstQualifs, Lazy<RenderedConst>),
313 /// Contains a constant which has been rendered to a String.
315 #[derive(RustcEncodable, RustcDecodable)]
316 struct RenderedConst(String);
318 #[derive(RustcEncodable, RustcDecodable)]
320 reexports: Lazy<[def::Export<hir::HirId>]>,
323 #[derive(RustcEncodable, RustcDecodable)]
329 #[derive(RustcEncodable, RustcDecodable)]
331 asyncness: hir::IsAsync,
332 constness: hir::Constness,
333 param_names: Lazy<[ast::Name]>,
336 #[derive(RustcEncodable, RustcDecodable)]
339 discr: ty::VariantDiscr,
340 /// If this is unit or tuple-variant/struct, then this is the index of the ctor id.
341 ctor: Option<DefIndex>,
344 #[derive(RustcEncodable, RustcDecodable)]
346 unsafety: hir::Unsafety,
352 #[derive(RustcEncodable, RustcDecodable)]
354 polarity: ty::ImplPolarity,
355 defaultness: hir::Defaultness,
356 parent_impl: Option<DefId>,
358 /// This is `Some` only for impls of `CoerceUnsized`.
359 // FIXME(eddyb) perhaps compute this on the fly if cheap enough?
360 coerce_unsized_info: Option<ty::adjustment::CoerceUnsizedInfo>,
363 /// Describes whether the container of an associated item
364 /// is a trait or an impl and whether, in a trait, it has
365 /// a default, or an in impl, whether it's marked "default".
366 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
367 enum AssocContainer {
374 impl AssocContainer {
375 fn with_def_id(&self, def_id: DefId) -> ty::AssocItemContainer {
377 AssocContainer::TraitRequired | AssocContainer::TraitWithDefault => {
378 ty::TraitContainer(def_id)
381 AssocContainer::ImplDefault | AssocContainer::ImplFinal => ty::ImplContainer(def_id),
385 fn defaultness(&self) -> hir::Defaultness {
387 AssocContainer::TraitRequired => hir::Defaultness::Default { has_value: false },
389 AssocContainer::TraitWithDefault | AssocContainer::ImplDefault => {
390 hir::Defaultness::Default { has_value: true }
393 AssocContainer::ImplFinal => hir::Defaultness::Final,
398 #[derive(RustcEncodable, RustcDecodable)]
401 container: AssocContainer,
405 #[derive(RustcEncodable, RustcDecodable)]
406 struct GeneratorData<'tcx> {
407 layout: mir::GeneratorLayout<'tcx>,
410 // Tags used for encoding Spans:
411 const TAG_VALID_SPAN: u8 = 0;
412 const TAG_INVALID_SPAN: u8 = 1;