2 use table::PerDefTable;
5 use rustc::hir::def::{self, CtorKind};
6 use rustc::hir::def_id::{DefIndex, DefId};
7 use rustc::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel};
8 use rustc::middle::cstore::{DepKind, LinkagePreference, NativeLibrary, ForeignModule};
9 use rustc::middle::lang_items;
11 use rustc::session::CrateDisambiguator;
12 use rustc::session::config::SymbolManglingVersion;
13 use rustc::ty::{self, Ty, ReprOptions};
14 use rustc_target::spec::{PanicStrategy, TargetTriple};
15 use rustc_index::vec::IndexVec;
16 use rustc_data_structures::svh::Svh;
17 use rustc_serialize::Encodable;
18 use syntax::{ast, attr};
19 use syntax::edition::Edition;
20 use syntax::symbol::Symbol;
21 use syntax_pos::{self, Span};
23 use std::marker::PhantomData;
24 use std::num::NonZeroUsize;
26 pub use decoder::{provide, provide_extern};
32 crate fn rustc_version() -> String {
34 option_env!("CFG_VERSION").unwrap_or("unknown version"))
37 /// Metadata encoding version.
38 /// N.B., increment this if you change the format of metadata such that
39 /// the rustc version can't be found to compare with `rustc_version()`.
40 const METADATA_VERSION: u8 = 5;
42 /// Metadata header which includes `METADATA_VERSION`.
44 /// This header is followed by the position of the `CrateRoot`,
45 /// which is encoded as a 32-bit big-endian unsigned integer,
46 /// and further followed by the rustc version string.
47 crate const METADATA_HEADER: &[u8; 8] =
48 &[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).
52 crate trait LazyMeta {
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: Encodable> LazyMeta for T {
63 fn min_size(_: ()) -> usize {
64 assert_ne!(std::mem::size_of::<T>(), 0);
69 impl<T: Encodable> 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 crate struct Lazy<T, Meta = <T as LazyMeta>::Meta>
107 where 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> {
120 _marker: PhantomData,
125 impl<T: Encodable> Lazy<T> {
126 fn from_position(position: NonZeroUsize) -> Lazy<T> {
127 Lazy::from_position_and_meta(position, ())
131 impl<T: Encodable> Lazy<[T]> {
132 fn empty() -> Lazy<[T]> {
133 Lazy::from_position_and_meta(NonZeroUsize::new(1).unwrap(), 0)
137 impl<T: ?Sized + LazyMeta> Copy for Lazy<T> {}
138 impl<T: ?Sized + LazyMeta> Clone for Lazy<T> {
139 fn clone(&self) -> Self {
144 impl<T: ?Sized + LazyMeta> rustc_serialize::UseSpecializedEncodable for Lazy<T> {}
145 impl<T: ?Sized + LazyMeta> rustc_serialize::UseSpecializedDecodable for Lazy<T> {}
147 /// Encoding / decoding state for `Lazy`.
148 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
150 /// Outside of a metadata node.
153 /// Inside a metadata node, and before any `Lazy`.
154 /// The position is that of the node itself.
155 NodeStart(NonZeroUsize),
157 /// Inside a metadata node, with a previous `Lazy`.
158 /// The position is a conservative estimate of where that
159 /// previous `Lazy` would end (see their comments).
160 Previous(NonZeroUsize),
163 // FIXME(#59875) `Lazy!(T)` replaces `Lazy<T>`, passing the `Meta` parameter
164 // manually, instead of relying on the default, to get the correct variance.
165 // Only needed when `T` itself contains a parameter (e.g. `'tcx`).
167 (Table<$T:ty>) => {Lazy<Table<$T>, usize>};
168 (PerDefTable<$T:ty>) => {Lazy<PerDefTable<$T>, usize>};
169 ([$T:ty]) => {Lazy<[$T], usize>};
170 ($T:ty) => {Lazy<$T, ()>};
173 #[derive(RustcEncodable, RustcDecodable)]
174 crate struct CrateRoot<'tcx> {
176 pub triple: TargetTriple,
177 extra_filename: String,
179 pub disambiguator: CrateDisambiguator,
180 pub panic_strategy: PanicStrategy,
182 pub has_global_allocator: bool,
183 has_panic_handler: bool,
184 pub has_default_lib_allocator: bool,
185 plugin_registrar_fn: Option<DefIndex>,
186 proc_macro_decls_static: Option<DefIndex>,
187 proc_macro_stability: Option<attr::Stability>,
189 pub crate_deps: Lazy<[CrateDep]>,
190 dylib_dependency_formats: Lazy<[Option<LinkagePreference>]>,
191 lib_features: Lazy<[(Symbol, Option<Symbol>)]>,
192 lang_items: Lazy<[(DefIndex, usize)]>,
193 lang_items_missing: Lazy<[lang_items::LangItem]>,
194 diagnostic_items: Lazy<[(Symbol, DefIndex)]>,
195 native_libraries: Lazy<[NativeLibrary]>,
196 foreign_modules: Lazy<[ForeignModule]>,
197 source_map: Lazy<[syntax_pos::SourceFile]>,
198 pub def_path_table: Lazy<hir::map::definitions::DefPathTable>,
199 pub impls: Lazy<[TraitImpls]>,
200 exported_symbols: Lazy!([(ExportedSymbol<'tcx>, SymbolExportLevel)]),
201 pub interpret_alloc_index: Lazy<[u32]>,
203 per_def: LazyPerDefTables<'tcx>,
205 /// The DefIndex's of any proc macros delcared by
207 pub proc_macro_data: Option<Lazy<[DefIndex]>>,
209 compiler_builtins: bool,
210 pub needs_allocator: bool,
211 pub needs_panic_runtime: bool,
213 pub panic_runtime: bool,
214 pub profiler_runtime: bool,
215 pub sanitizer_runtime: bool,
216 symbol_mangling_version: SymbolManglingVersion,
219 #[derive(RustcEncodable, RustcDecodable)]
220 crate struct CrateDep {
223 pub host_hash: Option<Svh>,
225 pub extra_filename: String,
228 #[derive(RustcEncodable, RustcDecodable)]
229 crate struct TraitImpls {
230 pub trait_id: (u32, DefIndex),
231 pub impls: Lazy<[DefIndex]>,
234 #[derive(RustcEncodable, RustcDecodable)]
235 crate struct LazyPerDefTables<'tcx> {
236 kind: Lazy!(PerDefTable<Lazy!(EntryKind<'tcx>)>),
237 visibility: Lazy!(PerDefTable<Lazy<ty::Visibility>>),
238 span: Lazy!(PerDefTable<Lazy<Span>>),
239 attributes: Lazy!(PerDefTable<Lazy<[ast::Attribute]>>),
240 children: Lazy!(PerDefTable<Lazy<[DefIndex]>>),
241 stability: Lazy!(PerDefTable<Lazy<attr::Stability>>),
242 deprecation: Lazy!(PerDefTable<Lazy<attr::Deprecation>>),
243 ty: Lazy!(PerDefTable<Lazy!(Ty<'tcx>)>),
244 fn_sig: Lazy!(PerDefTable<Lazy!(ty::PolyFnSig<'tcx>)>),
245 impl_trait_ref: Lazy!(PerDefTable<Lazy!(ty::TraitRef<'tcx>)>),
246 inherent_impls: Lazy!(PerDefTable<Lazy<[DefIndex]>>),
247 variances: Lazy!(PerDefTable<Lazy<[ty::Variance]>>),
248 generics: Lazy!(PerDefTable<Lazy<ty::Generics>>),
249 explicit_predicates: Lazy!(PerDefTable<Lazy!(ty::GenericPredicates<'tcx>)>),
250 // FIXME(eddyb) this would ideally be `Lazy<[...]>` but `ty::Predicate`
251 // doesn't handle shorthands in its own (de)serialization impls,
252 // as it's an `enum` for which we want to derive (de)serialization,
253 // so the `ty::codec` APIs handle the whole `&'tcx [...]` at once.
254 // Also, as an optimization, a missing entry indicates an empty `&[]`.
255 inferred_outlives: Lazy!(PerDefTable<Lazy!(&'tcx [(ty::Predicate<'tcx>, Span)])>),
256 super_predicates: Lazy!(PerDefTable<Lazy!(ty::GenericPredicates<'tcx>)>),
257 mir: Lazy!(PerDefTable<Lazy!(mir::Body<'tcx>)>),
258 promoted_mir: Lazy!(PerDefTable<Lazy!(IndexVec<mir::Promoted, mir::Body<'tcx>>)>),
261 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
262 enum EntryKind<'tcx> {
263 Const(ConstQualif, Lazy<RenderedConst>),
277 Variant(Lazy<VariantData>),
278 Struct(Lazy<VariantData>, ReprOptions),
279 Union(Lazy<VariantData>, ReprOptions),
281 ForeignFn(Lazy<FnData>),
283 MacroDef(Lazy<MacroDef>),
285 Generator(Lazy!(GeneratorData<'tcx>)),
286 Trait(Lazy<TraitData>),
287 Impl(Lazy<ImplData>),
288 Method(Lazy<MethodData>),
289 AssocType(AssocContainer),
290 AssocOpaqueTy(AssocContainer),
291 AssocConst(AssocContainer, ConstQualif, Lazy<RenderedConst>),
295 /// Additional data for EntryKind::Const and EntryKind::AssocConst
296 #[derive(Clone, Copy, RustcEncodable, RustcDecodable)]
301 /// Contains a constant which has been rendered to a String.
303 #[derive(RustcEncodable, RustcDecodable)]
304 struct RenderedConst(String);
306 #[derive(RustcEncodable, RustcDecodable)]
308 reexports: Lazy<[def::Export<hir::HirId>]>,
311 #[derive(RustcEncodable, RustcDecodable)]
317 #[derive(RustcEncodable, RustcDecodable)]
319 asyncness: hir::IsAsync,
320 constness: hir::Constness,
321 param_names: Lazy<[ast::Name]>,
324 #[derive(RustcEncodable, RustcDecodable)]
327 discr: ty::VariantDiscr,
328 /// If this is unit or tuple-variant/struct, then this is the index of the ctor id.
329 ctor: Option<DefIndex>,
332 #[derive(RustcEncodable, RustcDecodable)]
334 unsafety: hir::Unsafety,
340 #[derive(RustcEncodable, RustcDecodable)]
342 polarity: ty::ImplPolarity,
343 defaultness: hir::Defaultness,
344 parent_impl: Option<DefId>,
346 /// This is `Some` only for impls of `CoerceUnsized`.
347 // FIXME(eddyb) perhaps compute this on the fly if cheap enough?
348 coerce_unsized_info: Option<ty::adjustment::CoerceUnsizedInfo>,
352 /// Describes whether the container of an associated item
353 /// is a trait or an impl and whether, in a trait, it has
354 /// a default, or an in impl, whether it's marked "default".
355 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
356 enum AssocContainer {
363 impl AssocContainer {
364 fn with_def_id(&self, def_id: DefId) -> ty::AssocItemContainer {
366 AssocContainer::TraitRequired |
367 AssocContainer::TraitWithDefault => ty::TraitContainer(def_id),
369 AssocContainer::ImplDefault |
370 AssocContainer::ImplFinal => ty::ImplContainer(def_id),
374 fn defaultness(&self) -> hir::Defaultness {
376 AssocContainer::TraitRequired => hir::Defaultness::Default {
380 AssocContainer::TraitWithDefault |
381 AssocContainer::ImplDefault => hir::Defaultness::Default {
385 AssocContainer::ImplFinal => hir::Defaultness::Final,
390 #[derive(RustcEncodable, RustcDecodable)]
393 container: AssocContainer,
397 #[derive(RustcEncodable, RustcDecodable)]
398 struct GeneratorData<'tcx> {
399 layout: mir::GeneratorLayout<'tcx>,
402 // Tags used for encoding Spans:
403 const TAG_VALID_SPAN: u8 = 0;
404 const TAG_INVALID_SPAN: u8 = 1;