1 // Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
15 use rustc::hir::def::{self, CtorKind};
16 use rustc::hir::def_id::{DefIndex, DefId};
17 use rustc::ich::StableHashingContext;
18 use rustc::middle::cstore::{DepKind, LinkagePreference, NativeLibrary};
19 use rustc::middle::lang_items;
21 use rustc::ty::{self, Ty, ReprOptions};
22 use rustc_back::PanicStrategy;
24 use rustc_serialize as serialize;
25 use syntax::{ast, attr};
26 use syntax::symbol::Symbol;
27 use syntax_pos::{self, Span};
29 use std::marker::PhantomData;
32 use rustc_data_structures::stable_hasher::{StableHasher, HashStable,
35 pub fn rustc_version() -> String {
37 option_env!("CFG_VERSION").unwrap_or("unknown version"))
40 /// Metadata encoding version.
41 /// NB: increment this if you change the format of metadata such that
42 /// the rustc version can't be found to compare with `rustc_version()`.
43 pub const METADATA_VERSION: u8 = 4;
45 /// Metadata header which includes `METADATA_VERSION`.
46 /// To get older versions of rustc to ignore this metadata,
47 /// there are 4 zero bytes at the start, which are treated
48 /// as a length of 0 by old compilers.
50 /// This header is followed by the position of the `CrateRoot`,
51 /// which is encoded as a 32-bit big-endian unsigned integer,
52 /// and further followed by the rustc version string.
53 pub const METADATA_HEADER: &'static [u8; 12] =
54 &[0, 0, 0, 0, b'r', b'u', b's', b't', 0, 0, 0, METADATA_VERSION];
56 /// The shorthand encoding uses an enum's variant index `usize`
57 /// and is offset by this value so it never matches a real variant.
58 /// This offset is also chosen so that the first byte is never < 0x80.
59 pub const SHORTHAND_OFFSET: usize = 0x80;
61 /// A value of type T referred to by its absolute position
62 /// in the metadata, and which can be decoded lazily.
64 /// Metadata is effective a tree, encoded in post-order,
65 /// and with the root's position written next to the header.
66 /// That means every single `Lazy` points to some previous
67 /// location in the metadata and is part of a larger node.
69 /// The first `Lazy` in a node is encoded as the backwards
70 /// distance from the position where the containing node
71 /// starts and where the `Lazy` points to, while the rest
72 /// use the forward distance from the previous `Lazy`.
73 /// Distances start at 1, as 0-byte nodes are invalid.
74 /// Also invalid are nodes being referred in a different
75 /// order than they were encoded in.
79 _marker: PhantomData<T>,
83 pub fn with_position(position: usize) -> Lazy<T> {
90 /// Returns the minimum encoded size of a value of type `T`.
91 // FIXME(eddyb) Give better estimates for certain types.
92 pub fn min_size() -> usize {
97 impl<T> Copy for Lazy<T> {}
98 impl<T> Clone for Lazy<T> {
99 fn clone(&self) -> Self {
104 impl<T> serialize::UseSpecializedEncodable for Lazy<T> {}
105 impl<T> serialize::UseSpecializedDecodable for Lazy<T> {}
107 impl<CTX, T> HashStable<CTX> for Lazy<T> {
108 fn hash_stable<W: StableHasherResult>(&self,
110 _: &mut StableHasher<W>) {
111 // There's nothing to do. Whatever got encoded within this Lazy<>
112 // wrapper has already been hashed.
116 /// A sequence of type T referred to by its absolute position
117 /// in the metadata and length, and which can be decoded lazily.
118 /// The sequence is a single node for the purposes of `Lazy`.
120 /// Unlike `Lazy<Vec<T>>`, the length is encoded next to the
121 /// position, not at the position, which means that the length
122 /// doesn't need to be known before encoding all the elements.
124 /// If the length is 0, no position is encoded, but otherwise,
125 /// the encoding is that of `Lazy`, with the distinction that
126 /// the minimal distance the length of the sequence, i.e.
127 /// it's assumed there's no 0-byte element in the sequence.
129 pub struct LazySeq<T> {
132 _marker: PhantomData<T>,
136 pub fn empty() -> LazySeq<T> {
137 LazySeq::with_position_and_length(0, 0)
140 pub fn with_position_and_length(position: usize, len: usize) -> LazySeq<T> {
144 _marker: PhantomData,
148 /// Returns the minimum encoded size of `length` values of type `T`.
149 pub fn min_size(length: usize) -> usize {
154 impl<T> Copy for LazySeq<T> {}
155 impl<T> Clone for LazySeq<T> {
156 fn clone(&self) -> Self {
161 impl<T> serialize::UseSpecializedEncodable for LazySeq<T> {}
162 impl<T> serialize::UseSpecializedDecodable for LazySeq<T> {}
164 impl<CTX, T> HashStable<CTX> for LazySeq<T> {
165 fn hash_stable<W: StableHasherResult>(&self,
167 _: &mut StableHasher<W>) {
168 // There's nothing to do. Whatever got encoded within this Lazy<>
169 // wrapper has already been hashed.
173 /// Encoding / decoding state for `Lazy` and `LazySeq`.
174 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
176 /// Outside of a metadata node.
179 /// Inside a metadata node, and before any `Lazy` or `LazySeq`.
180 /// The position is that of the node itself.
183 /// Inside a metadata node, with a previous `Lazy` or `LazySeq`.
184 /// The position is a conservative estimate of where that
185 /// previous `Lazy` / `LazySeq` would end (see their comments).
189 #[derive(RustcEncodable, RustcDecodable)]
190 pub struct CrateRoot {
193 pub hash: hir::svh::Svh,
194 pub disambiguator: Symbol,
195 pub panic_strategy: PanicStrategy,
196 pub plugin_registrar_fn: Option<DefIndex>,
197 pub macro_derive_registrar: Option<DefIndex>,
199 pub crate_deps: LazySeq<CrateDep>,
200 pub dylib_dependency_formats: LazySeq<Option<LinkagePreference>>,
201 pub lang_items: LazySeq<(DefIndex, usize)>,
202 pub lang_items_missing: LazySeq<lang_items::LangItem>,
203 pub native_libraries: LazySeq<NativeLibrary>,
204 pub codemap: LazySeq<syntax_pos::FileMap>,
205 pub def_path_table: Lazy<hir::map::definitions::DefPathTable>,
206 pub impls: LazySeq<TraitImpls>,
207 pub exported_symbols: LazySeq<DefIndex>,
208 pub index: LazySeq<index::Index>,
211 #[derive(RustcEncodable, RustcDecodable)]
212 pub struct CrateDep {
214 pub hash: hir::svh::Svh,
218 #[derive(RustcEncodable, RustcDecodable)]
219 pub struct TraitImpls {
220 pub trait_id: (u32, DefIndex),
221 pub impls: LazySeq<DefIndex>,
224 #[derive(RustcEncodable, RustcDecodable)]
225 pub struct Entry<'tcx> {
226 pub kind: EntryKind<'tcx>,
227 pub visibility: Lazy<ty::Visibility>,
228 pub span: Lazy<Span>,
229 pub attributes: LazySeq<ast::Attribute>,
230 pub children: LazySeq<DefIndex>,
231 pub stability: Option<Lazy<attr::Stability>>,
232 pub deprecation: Option<Lazy<attr::Deprecation>>,
234 pub ty: Option<Lazy<Ty<'tcx>>>,
235 pub inherent_impls: LazySeq<DefIndex>,
236 pub variances: LazySeq<ty::Variance>,
237 pub generics: Option<Lazy<ty::Generics>>,
238 pub predicates: Option<Lazy<ty::GenericPredicates<'tcx>>>,
240 pub ast: Option<Lazy<astencode::Ast<'tcx>>>,
241 pub mir: Option<Lazy<mir::Mir<'tcx>>>,
244 impl_stable_hash_for!(struct Entry<'tcx> {
261 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
262 pub enum EntryKind<'tcx> {
273 Variant(Lazy<VariantData>),
274 Struct(Lazy<VariantData>, ReprOptions),
275 Union(Lazy<VariantData>, ReprOptions),
277 ForeignFn(Lazy<FnData>),
279 MacroDef(Lazy<MacroDef>),
280 Closure(Lazy<ClosureData<'tcx>>),
281 Trait(Lazy<TraitData<'tcx>>),
282 Impl(Lazy<ImplData<'tcx>>),
283 DefaultImpl(Lazy<ImplData<'tcx>>),
284 Method(Lazy<MethodData>),
285 AssociatedType(AssociatedContainer),
286 AssociatedConst(AssociatedContainer, u8),
289 impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for EntryKind<'tcx> {
290 fn hash_stable<W: StableHasherResult>(&self,
291 hcx: &mut StableHashingContext<'a, 'tcx>,
292 hasher: &mut StableHasher<W>) {
293 mem::discriminant(self).hash_stable(hcx, hasher);
295 EntryKind::ImmStatic |
296 EntryKind::MutStatic |
297 EntryKind::ForeignImmStatic |
298 EntryKind::ForeignMutStatic |
299 EntryKind::ForeignMod |
300 EntryKind::GlobalAsm |
303 // Nothing else to hash here.
305 EntryKind::Const(qualif) => {
306 qualif.hash_stable(hcx, hasher);
308 EntryKind::Enum(ref repr_options) => {
309 repr_options.hash_stable(hcx, hasher);
311 EntryKind::Variant(ref variant_data) => {
312 variant_data.hash_stable(hcx, hasher);
314 EntryKind::Struct(ref variant_data, ref repr_options) |
315 EntryKind::Union(ref variant_data, ref repr_options) => {
316 variant_data.hash_stable(hcx, hasher);
317 repr_options.hash_stable(hcx, hasher);
319 EntryKind::Fn(ref fn_data) |
320 EntryKind::ForeignFn(ref fn_data) => {
321 fn_data.hash_stable(hcx, hasher);
323 EntryKind::Mod(ref mod_data) => {
324 mod_data.hash_stable(hcx, hasher);
326 EntryKind::MacroDef(ref macro_def) => {
327 macro_def.hash_stable(hcx, hasher);
329 EntryKind::Closure(closure_data) => {
330 closure_data.hash_stable(hcx, hasher);
332 EntryKind::Trait(ref trait_data) => {
333 trait_data.hash_stable(hcx, hasher);
335 EntryKind::DefaultImpl(ref impl_data) |
336 EntryKind::Impl(ref impl_data) => {
337 impl_data.hash_stable(hcx, hasher);
339 EntryKind::Method(ref method_data) => {
340 method_data.hash_stable(hcx, hasher);
342 EntryKind::AssociatedType(associated_container) => {
343 associated_container.hash_stable(hcx, hasher);
345 EntryKind::AssociatedConst(associated_container, qualif) => {
346 associated_container.hash_stable(hcx, hasher);
347 qualif.hash_stable(hcx, hasher);
353 #[derive(RustcEncodable, RustcDecodable)]
355 pub reexports: LazySeq<def::Export>,
358 impl_stable_hash_for!(struct ModData { reexports });
360 #[derive(RustcEncodable, RustcDecodable)]
361 pub struct MacroDef {
365 impl_stable_hash_for!(struct MacroDef { body });
367 #[derive(RustcEncodable, RustcDecodable)]
369 pub constness: hir::Constness,
370 pub arg_names: LazySeq<ast::Name>,
373 impl_stable_hash_for!(struct FnData { constness, arg_names });
375 #[derive(RustcEncodable, RustcDecodable)]
376 pub struct VariantData {
377 pub ctor_kind: CtorKind,
378 pub discr: ty::VariantDiscr,
380 /// If this is a struct's only variant, this
381 /// is the index of the "struct ctor" item.
382 pub struct_ctor: Option<DefIndex>,
385 impl_stable_hash_for!(struct VariantData {
391 #[derive(RustcEncodable, RustcDecodable)]
392 pub struct TraitData<'tcx> {
393 pub unsafety: hir::Unsafety,
394 pub paren_sugar: bool,
395 pub has_default_impl: bool,
396 pub super_predicates: Lazy<ty::GenericPredicates<'tcx>>,
399 impl_stable_hash_for!(struct TraitData<'tcx> {
406 #[derive(RustcEncodable, RustcDecodable)]
407 pub struct ImplData<'tcx> {
408 pub polarity: hir::ImplPolarity,
409 pub parent_impl: Option<DefId>,
411 /// This is `Some` only for impls of `CoerceUnsized`.
412 pub coerce_unsized_info: Option<ty::adjustment::CoerceUnsizedInfo>,
413 pub trait_ref: Option<Lazy<ty::TraitRef<'tcx>>>,
416 impl_stable_hash_for!(struct ImplData<'tcx> {
424 /// Describes whether the container of an associated item
425 /// is a trait or an impl and whether, in a trait, it has
426 /// a default, or an in impl, whether it's marked "default".
427 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
428 pub enum AssociatedContainer {
435 impl_stable_hash_for!(enum ::schema::AssociatedContainer {
442 impl AssociatedContainer {
443 pub fn with_def_id(&self, def_id: DefId) -> ty::AssociatedItemContainer {
445 AssociatedContainer::TraitRequired |
446 AssociatedContainer::TraitWithDefault => ty::TraitContainer(def_id),
448 AssociatedContainer::ImplDefault |
449 AssociatedContainer::ImplFinal => ty::ImplContainer(def_id),
453 pub fn defaultness(&self) -> hir::Defaultness {
455 AssociatedContainer::TraitRequired => hir::Defaultness::Default {
459 AssociatedContainer::TraitWithDefault |
460 AssociatedContainer::ImplDefault => hir::Defaultness::Default {
464 AssociatedContainer::ImplFinal => hir::Defaultness::Final,
469 #[derive(RustcEncodable, RustcDecodable)]
470 pub struct MethodData {
472 pub container: AssociatedContainer,
475 impl_stable_hash_for!(struct MethodData { fn_data, container, has_self });
477 #[derive(RustcEncodable, RustcDecodable)]
478 pub struct ClosureData<'tcx> {
479 pub kind: ty::ClosureKind,
480 pub ty: Lazy<ty::PolyFnSig<'tcx>>,
482 impl_stable_hash_for!(struct ClosureData<'tcx> { kind, ty });