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, CrateNum};
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 use rustc::dep_graph::{DepGraph, DepNode};
37 pub fn rustc_version() -> String {
39 option_env!("CFG_VERSION").unwrap_or("unknown version"))
42 /// Metadata encoding version.
43 /// NB: increment this if you change the format of metadata such that
44 /// the rustc version can't be found to compare with `rustc_version()`.
45 pub const METADATA_VERSION: u8 = 4;
47 /// Metadata header which includes `METADATA_VERSION`.
48 /// To get older versions of rustc to ignore this metadata,
49 /// there are 4 zero bytes at the start, which are treated
50 /// as a length of 0 by old compilers.
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: &'static [u8; 12] =
56 &[0, 0, 0, 0, b'r', b'u', b's', b't', 0, 0, 0, METADATA_VERSION];
58 /// The shorthand encoding uses an enum's variant index `usize`
59 /// and is offset by this value so it never matches a real variant.
60 /// This offset is also chosen so that the first byte is never < 0x80.
61 pub const SHORTHAND_OFFSET: usize = 0x80;
63 /// A value of type T referred to by its absolute position
64 /// in the metadata, and which can be decoded lazily.
66 /// Metadata is effective a tree, encoded in post-order,
67 /// and with the root's position written next to the header.
68 /// That means every single `Lazy` points to some previous
69 /// location in the metadata and is part of a larger node.
71 /// The first `Lazy` in a node is encoded as the backwards
72 /// distance from the position where the containing node
73 /// starts and where the `Lazy` points to, while the rest
74 /// use the forward distance from the previous `Lazy`.
75 /// Distances start at 1, as 0-byte nodes are invalid.
76 /// Also invalid are nodes being referred in a different
77 /// order than they were encoded in.
81 _marker: PhantomData<T>,
85 pub fn with_position(position: usize) -> Lazy<T> {
92 /// Returns the minimum encoded size of a value of type `T`.
93 // FIXME(eddyb) Give better estimates for certain types.
94 pub fn min_size() -> usize {
99 impl<T> Copy for Lazy<T> {}
100 impl<T> Clone for Lazy<T> {
101 fn clone(&self) -> Self {
106 impl<T> serialize::UseSpecializedEncodable for Lazy<T> {}
107 impl<T> serialize::UseSpecializedDecodable for Lazy<T> {}
109 impl<CTX, T> HashStable<CTX> for Lazy<T> {
110 fn hash_stable<W: StableHasherResult>(&self,
112 _: &mut StableHasher<W>) {
113 // There's nothing to do. Whatever got encoded within this Lazy<>
114 // wrapper has already been hashed.
118 /// A sequence of type T referred to by its absolute position
119 /// in the metadata and length, and which can be decoded lazily.
120 /// The sequence is a single node for the purposes of `Lazy`.
122 /// Unlike `Lazy<Vec<T>>`, the length is encoded next to the
123 /// position, not at the position, which means that the length
124 /// doesn't need to be known before encoding all the elements.
126 /// If the length is 0, no position is encoded, but otherwise,
127 /// the encoding is that of `Lazy`, with the distinction that
128 /// the minimal distance the length of the sequence, i.e.
129 /// it's assumed there's no 0-byte element in the sequence.
131 pub struct LazySeq<T> {
134 _marker: PhantomData<T>,
138 pub fn empty() -> LazySeq<T> {
139 LazySeq::with_position_and_length(0, 0)
142 pub fn with_position_and_length(position: usize, len: usize) -> LazySeq<T> {
146 _marker: PhantomData,
150 /// Returns the minimum encoded size of `length` values of type `T`.
151 pub fn min_size(length: usize) -> usize {
156 impl<T> Copy for LazySeq<T> {}
157 impl<T> Clone for LazySeq<T> {
158 fn clone(&self) -> Self {
163 impl<T> serialize::UseSpecializedEncodable for LazySeq<T> {}
164 impl<T> serialize::UseSpecializedDecodable for LazySeq<T> {}
166 impl<CTX, T> HashStable<CTX> for LazySeq<T> {
167 fn hash_stable<W: StableHasherResult>(&self,
169 _: &mut StableHasher<W>) {
170 // There's nothing to do. Whatever got encoded within this Lazy<>
171 // wrapper has already been hashed.
175 /// Encoding / decoding state for `Lazy` and `LazySeq`.
176 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
178 /// Outside of a metadata node.
181 /// Inside a metadata node, and before any `Lazy` or `LazySeq`.
182 /// The position is that of the node itself.
185 /// Inside a metadata node, with a previous `Lazy` or `LazySeq`.
186 /// The position is a conservative estimate of where that
187 /// previous `Lazy` / `LazySeq` would end (see their comments).
191 /// A `Tracked<T>` wraps a value so that one can only access it when specifying
192 /// the `DepNode` for that value. This makes it harder to forget registering
194 #[derive(RustcEncodable, RustcDecodable)]
195 pub struct Tracked<T> {
200 pub fn new(state: T) -> Tracked<T> {
206 pub fn get(&self, dep_graph: &DepGraph, dep_node: DepNode<DefId>) -> &T {
207 dep_graph.read(dep_node);
211 pub fn get_untracked(&self) -> &T {
215 pub fn map<F, R>(&self, f: F) -> Tracked<R>
216 where F: FnOnce(&T) -> R
219 state: f(&self.state),
224 impl<'a, 'tcx, T> HashStable<StableHashingContext<'a, 'tcx>> for Tracked<T>
225 where T: HashStable<StableHashingContext<'a, 'tcx>>
227 fn hash_stable<W: StableHasherResult>(&self,
228 hcx: &mut StableHashingContext<'a, 'tcx>,
229 hasher: &mut StableHasher<W>) {
234 state.hash_stable(hcx, hasher);
239 #[derive(RustcEncodable, RustcDecodable)]
240 pub struct CrateRoot {
243 pub hash: hir::svh::Svh,
244 pub disambiguator: Symbol,
245 pub panic_strategy: Tracked<PanicStrategy>,
246 pub plugin_registrar_fn: Option<DefIndex>,
247 pub macro_derive_registrar: Option<DefIndex>,
249 pub crate_deps: Tracked<LazySeq<CrateDep>>,
250 pub dylib_dependency_formats: Tracked<LazySeq<Option<LinkagePreference>>>,
251 pub lang_items: Tracked<LazySeq<(DefIndex, usize)>>,
252 pub lang_items_missing: Tracked<LazySeq<lang_items::LangItem>>,
253 pub native_libraries: Tracked<LazySeq<NativeLibrary>>,
254 pub codemap: LazySeq<syntax_pos::FileMap>,
255 pub def_path_table: Lazy<hir::map::definitions::DefPathTable>,
256 pub impls: Tracked<LazySeq<TraitImpls>>,
257 pub exported_symbols: Tracked<LazySeq<DefIndex>>,
258 pub index: LazySeq<index::Index>,
261 #[derive(RustcEncodable, RustcDecodable)]
262 pub struct CrateDep {
264 pub hash: hir::svh::Svh,
268 impl_stable_hash_for!(struct CrateDep {
274 #[derive(RustcEncodable, RustcDecodable)]
275 pub struct TraitImpls {
276 pub trait_id: (u32, DefIndex),
277 pub impls: LazySeq<DefIndex>,
280 impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for TraitImpls {
281 fn hash_stable<W: StableHasherResult>(&self,
282 hcx: &mut StableHashingContext<'a, 'tcx>,
283 hasher: &mut StableHasher<W>) {
285 trait_id: (krate, def_index),
290 krate: CrateNum::from_u32(krate),
292 }.hash_stable(hcx, hasher);
293 impls.hash_stable(hcx, hasher);
297 #[derive(RustcEncodable, RustcDecodable)]
298 pub struct Entry<'tcx> {
299 pub kind: EntryKind<'tcx>,
300 pub visibility: Lazy<ty::Visibility>,
301 pub span: Lazy<Span>,
302 pub attributes: LazySeq<ast::Attribute>,
303 pub children: LazySeq<DefIndex>,
304 pub stability: Option<Lazy<attr::Stability>>,
305 pub deprecation: Option<Lazy<attr::Deprecation>>,
307 pub ty: Option<Lazy<Ty<'tcx>>>,
308 pub inherent_impls: LazySeq<DefIndex>,
309 pub variances: LazySeq<ty::Variance>,
310 pub generics: Option<Lazy<ty::Generics>>,
311 pub predicates: Option<Lazy<ty::GenericPredicates<'tcx>>>,
313 pub ast: Option<Lazy<astencode::Ast<'tcx>>>,
314 pub mir: Option<Lazy<mir::Mir<'tcx>>>,
317 impl_stable_hash_for!(struct Entry<'tcx> {
334 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
335 pub enum EntryKind<'tcx> {
346 Variant(Lazy<VariantData>),
347 Struct(Lazy<VariantData>, ReprOptions),
348 Union(Lazy<VariantData>, ReprOptions),
350 ForeignFn(Lazy<FnData>),
352 MacroDef(Lazy<MacroDef>),
353 Closure(Lazy<ClosureData<'tcx>>),
354 Trait(Lazy<TraitData<'tcx>>),
355 Impl(Lazy<ImplData<'tcx>>),
356 DefaultImpl(Lazy<ImplData<'tcx>>),
357 Method(Lazy<MethodData>),
358 AssociatedType(AssociatedContainer),
359 AssociatedConst(AssociatedContainer, u8),
362 impl<'a, 'tcx> HashStable<StableHashingContext<'a, 'tcx>> for EntryKind<'tcx> {
363 fn hash_stable<W: StableHasherResult>(&self,
364 hcx: &mut StableHashingContext<'a, 'tcx>,
365 hasher: &mut StableHasher<W>) {
366 mem::discriminant(self).hash_stable(hcx, hasher);
368 EntryKind::ImmStatic |
369 EntryKind::MutStatic |
370 EntryKind::ForeignImmStatic |
371 EntryKind::ForeignMutStatic |
372 EntryKind::ForeignMod |
373 EntryKind::GlobalAsm |
376 // Nothing else to hash here.
378 EntryKind::Const(qualif) => {
379 qualif.hash_stable(hcx, hasher);
381 EntryKind::Enum(ref repr_options) => {
382 repr_options.hash_stable(hcx, hasher);
384 EntryKind::Variant(ref variant_data) => {
385 variant_data.hash_stable(hcx, hasher);
387 EntryKind::Struct(ref variant_data, ref repr_options) |
388 EntryKind::Union(ref variant_data, ref repr_options) => {
389 variant_data.hash_stable(hcx, hasher);
390 repr_options.hash_stable(hcx, hasher);
392 EntryKind::Fn(ref fn_data) |
393 EntryKind::ForeignFn(ref fn_data) => {
394 fn_data.hash_stable(hcx, hasher);
396 EntryKind::Mod(ref mod_data) => {
397 mod_data.hash_stable(hcx, hasher);
399 EntryKind::MacroDef(ref macro_def) => {
400 macro_def.hash_stable(hcx, hasher);
402 EntryKind::Closure(closure_data) => {
403 closure_data.hash_stable(hcx, hasher);
405 EntryKind::Trait(ref trait_data) => {
406 trait_data.hash_stable(hcx, hasher);
408 EntryKind::DefaultImpl(ref impl_data) |
409 EntryKind::Impl(ref impl_data) => {
410 impl_data.hash_stable(hcx, hasher);
412 EntryKind::Method(ref method_data) => {
413 method_data.hash_stable(hcx, hasher);
415 EntryKind::AssociatedType(associated_container) => {
416 associated_container.hash_stable(hcx, hasher);
418 EntryKind::AssociatedConst(associated_container, qualif) => {
419 associated_container.hash_stable(hcx, hasher);
420 qualif.hash_stable(hcx, hasher);
426 #[derive(RustcEncodable, RustcDecodable)]
428 pub reexports: LazySeq<def::Export>,
431 impl_stable_hash_for!(struct ModData { reexports });
433 #[derive(RustcEncodable, RustcDecodable)]
434 pub struct MacroDef {
439 impl_stable_hash_for!(struct MacroDef { body, legacy });
441 #[derive(RustcEncodable, RustcDecodable)]
443 pub constness: hir::Constness,
444 pub arg_names: LazySeq<ast::Name>,
447 impl_stable_hash_for!(struct FnData { constness, arg_names });
449 #[derive(RustcEncodable, RustcDecodable)]
450 pub struct VariantData {
451 pub ctor_kind: CtorKind,
452 pub discr: ty::VariantDiscr,
454 /// If this is a struct's only variant, this
455 /// is the index of the "struct ctor" item.
456 pub struct_ctor: Option<DefIndex>,
459 impl_stable_hash_for!(struct VariantData {
465 #[derive(RustcEncodable, RustcDecodable)]
466 pub struct TraitData<'tcx> {
467 pub unsafety: hir::Unsafety,
468 pub paren_sugar: bool,
469 pub has_default_impl: bool,
470 pub super_predicates: Lazy<ty::GenericPredicates<'tcx>>,
473 impl_stable_hash_for!(struct TraitData<'tcx> {
480 #[derive(RustcEncodable, RustcDecodable)]
481 pub struct ImplData<'tcx> {
482 pub polarity: hir::ImplPolarity,
483 pub defaultness: hir::Defaultness,
484 pub parent_impl: Option<DefId>,
486 /// This is `Some` only for impls of `CoerceUnsized`.
487 pub coerce_unsized_info: Option<ty::adjustment::CoerceUnsizedInfo>,
488 pub trait_ref: Option<Lazy<ty::TraitRef<'tcx>>>,
491 impl_stable_hash_for!(struct ImplData<'tcx> {
500 /// Describes whether the container of an associated item
501 /// is a trait or an impl and whether, in a trait, it has
502 /// a default, or an in impl, whether it's marked "default".
503 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
504 pub enum AssociatedContainer {
511 impl_stable_hash_for!(enum ::schema::AssociatedContainer {
518 impl AssociatedContainer {
519 pub fn with_def_id(&self, def_id: DefId) -> ty::AssociatedItemContainer {
521 AssociatedContainer::TraitRequired |
522 AssociatedContainer::TraitWithDefault => ty::TraitContainer(def_id),
524 AssociatedContainer::ImplDefault |
525 AssociatedContainer::ImplFinal => ty::ImplContainer(def_id),
529 pub fn defaultness(&self) -> hir::Defaultness {
531 AssociatedContainer::TraitRequired => hir::Defaultness::Default {
535 AssociatedContainer::TraitWithDefault |
536 AssociatedContainer::ImplDefault => hir::Defaultness::Default {
540 AssociatedContainer::ImplFinal => hir::Defaultness::Final,
545 #[derive(RustcEncodable, RustcDecodable)]
546 pub struct MethodData {
548 pub container: AssociatedContainer,
551 impl_stable_hash_for!(struct MethodData { fn_data, container, has_self });
553 #[derive(RustcEncodable, RustcDecodable)]
554 pub struct ClosureData<'tcx> {
555 pub kind: ty::ClosureKind,
556 pub ty: Lazy<ty::PolyFnSig<'tcx>>,
558 impl_stable_hash_for!(struct ClosureData<'tcx> { kind, ty });