4 use rustc::hir::def::{self, CtorKind};
5 use rustc::hir::def_id::{DefIndex, DefId, CrateNum};
6 use rustc::ich::StableHashingContext;
7 use rustc::middle::cstore::{DepKind, LinkagePreference, NativeLibrary, ForeignModule};
8 use rustc::middle::lang_items;
10 use rustc::session::CrateDisambiguator;
11 use rustc::ty::{self, Ty, ReprOptions};
12 use rustc_target::spec::{PanicStrategy, TargetTriple};
13 use rustc_data_structures::svh::Svh;
15 use rustc_serialize as serialize;
16 use syntax::{ast, attr};
17 use syntax::edition::Edition;
18 use syntax::symbol::Symbol;
19 use syntax_pos::{self, Span};
21 use std::marker::PhantomData;
24 use rustc_data_structures::stable_hasher::{StableHasher, HashStable,
27 pub fn rustc_version() -> String {
29 option_env!("CFG_VERSION").unwrap_or("unknown version"))
32 /// Metadata encoding version.
33 /// N.B., increment this if you change the format of metadata such that
34 /// the rustc version can't be found to compare with `rustc_version()`.
35 pub const METADATA_VERSION: u8 = 4;
37 /// Metadata header which includes `METADATA_VERSION`.
38 /// To get older versions of rustc to ignore this metadata,
39 /// there are 4 zero bytes at the start, which are treated
40 /// as a length of 0 by old compilers.
42 /// This header is followed by the position of the `CrateRoot`,
43 /// which is encoded as a 32-bit big-endian unsigned integer,
44 /// and further followed by the rustc version string.
45 pub const METADATA_HEADER: &[u8; 12] =
46 &[0, 0, 0, 0, b'r', b'u', b's', b't', 0, 0, 0, METADATA_VERSION];
48 /// A value of type T referred to by its absolute position
49 /// in the metadata, and which can be decoded lazily.
51 /// Metadata is effective a tree, encoded in post-order,
52 /// and with the root's position written next to the header.
53 /// That means every single `Lazy` points to some previous
54 /// location in the metadata and is part of a larger node.
56 /// The first `Lazy` in a node is encoded as the backwards
57 /// distance from the position where the containing node
58 /// starts and where the `Lazy` points to, while the rest
59 /// use the forward distance from the previous `Lazy`.
60 /// Distances start at 1, as 0-byte nodes are invalid.
61 /// Also invalid are nodes being referred in a different
62 /// order than they were encoded in.
66 _marker: PhantomData<T>,
70 pub fn with_position(position: usize) -> Lazy<T> {
77 /// Returns the minimum encoded size of a value of type `T`.
78 // FIXME(eddyb) Give better estimates for certain types.
79 pub fn min_size() -> usize {
84 impl<T> Copy for Lazy<T> {}
85 impl<T> Clone for Lazy<T> {
86 fn clone(&self) -> Self {
91 impl<T> serialize::UseSpecializedEncodable for Lazy<T> {}
92 impl<T> serialize::UseSpecializedDecodable for Lazy<T> {}
94 impl<CTX, T> HashStable<CTX> for Lazy<T> {
95 fn hash_stable<W: StableHasherResult>(&self,
97 _: &mut StableHasher<W>) {
98 // There's nothing to do. Whatever got encoded within this Lazy<>
99 // wrapper has already been hashed.
103 /// A sequence of type T referred to by its absolute position
104 /// in the metadata and length, and which can be decoded lazily.
105 /// The sequence is a single node for the purposes of `Lazy`.
107 /// Unlike `Lazy<Vec<T>>`, the length is encoded next to the
108 /// position, not at the position, which means that the length
109 /// doesn't need to be known before encoding all the elements.
111 /// If the length is 0, no position is encoded, but otherwise,
112 /// the encoding is that of `Lazy`, with the distinction that
113 /// the minimal distance the length of the sequence, i.e.
114 /// it's assumed there's no 0-byte element in the sequence.
116 pub struct LazySeq<T> {
119 _marker: PhantomData<T>,
123 pub fn empty() -> LazySeq<T> {
124 LazySeq::with_position_and_length(0, 0)
127 pub fn with_position_and_length(position: usize, len: usize) -> LazySeq<T> {
131 _marker: PhantomData,
135 /// Returns the minimum encoded size of `length` values of type `T`.
136 pub fn min_size(length: usize) -> usize {
141 impl<T> Copy for LazySeq<T> {}
142 impl<T> Clone for LazySeq<T> {
143 fn clone(&self) -> Self {
148 impl<T> serialize::UseSpecializedEncodable for LazySeq<T> {}
149 impl<T> serialize::UseSpecializedDecodable for LazySeq<T> {}
151 impl<CTX, T> HashStable<CTX> for LazySeq<T> {
152 fn hash_stable<W: StableHasherResult>(&self,
154 _: &mut StableHasher<W>) {
155 // There's nothing to do. Whatever got encoded within this Lazy<>
156 // wrapper has already been hashed.
160 /// Encoding / decoding state for `Lazy` and `LazySeq`.
161 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
163 /// Outside of a metadata node.
166 /// Inside a metadata node, and before any `Lazy` or `LazySeq`.
167 /// The position is that of the node itself.
170 /// Inside a metadata node, with a previous `Lazy` or `LazySeq`.
171 /// The position is a conservative estimate of where that
172 /// previous `Lazy` / `LazySeq` would end (see their comments).
176 #[derive(RustcEncodable, RustcDecodable)]
177 pub struct CrateRoot {
179 pub triple: TargetTriple,
180 pub extra_filename: String,
182 pub disambiguator: CrateDisambiguator,
183 pub panic_strategy: PanicStrategy,
184 pub edition: Edition,
185 pub has_global_allocator: bool,
186 pub has_panic_handler: bool,
187 pub has_default_lib_allocator: bool,
188 pub plugin_registrar_fn: Option<DefIndex>,
189 pub proc_macro_decls_static: Option<DefIndex>,
190 pub proc_macro_stability: Option<attr::Stability>,
192 pub crate_deps: LazySeq<CrateDep>,
193 pub dylib_dependency_formats: LazySeq<Option<LinkagePreference>>,
194 pub lib_features: LazySeq<(Symbol, Option<Symbol>)>,
195 pub lang_items: LazySeq<(DefIndex, usize)>,
196 pub lang_items_missing: LazySeq<lang_items::LangItem>,
197 pub native_libraries: LazySeq<NativeLibrary>,
198 pub foreign_modules: LazySeq<ForeignModule>,
199 pub source_map: LazySeq<syntax_pos::SourceFile>,
200 pub def_path_table: Lazy<hir::map::definitions::DefPathTable>,
201 pub impls: LazySeq<TraitImpls>,
202 pub exported_symbols: EncodedExportedSymbols,
203 pub interpret_alloc_index: LazySeq<u32>,
205 pub index: LazySeq<index::Index>,
207 pub compiler_builtins: bool,
208 pub needs_allocator: bool,
209 pub needs_panic_runtime: bool,
210 pub no_builtins: bool,
211 pub panic_runtime: bool,
212 pub profiler_runtime: bool,
213 pub sanitizer_runtime: bool,
216 #[derive(RustcEncodable, RustcDecodable)]
217 pub struct CrateDep {
221 pub extra_filename: String,
224 impl_stable_hash_for!(struct CrateDep {
231 #[derive(RustcEncodable, RustcDecodable)]
232 pub struct TraitImpls {
233 pub trait_id: (u32, DefIndex),
234 pub impls: LazySeq<DefIndex>,
237 impl<'a, 'gcx> HashStable<StableHashingContext<'a>> for TraitImpls {
238 fn hash_stable<W: StableHasherResult>(&self,
239 hcx: &mut StableHashingContext<'a>,
240 hasher: &mut StableHasher<W>) {
242 trait_id: (krate, def_index),
247 krate: CrateNum::from_u32(krate),
249 }.hash_stable(hcx, hasher);
250 impls.hash_stable(hcx, hasher);
254 #[derive(RustcEncodable, RustcDecodable)]
255 pub struct Entry<'tcx> {
256 pub kind: EntryKind<'tcx>,
257 pub visibility: Lazy<ty::Visibility>,
258 pub span: Lazy<Span>,
259 pub attributes: LazySeq<ast::Attribute>,
260 pub children: LazySeq<DefIndex>,
261 pub stability: Option<Lazy<attr::Stability>>,
262 pub deprecation: Option<Lazy<attr::Deprecation>>,
264 pub ty: Option<Lazy<Ty<'tcx>>>,
265 pub inherent_impls: LazySeq<DefIndex>,
266 pub variances: LazySeq<ty::Variance>,
267 pub generics: Option<Lazy<ty::Generics>>,
268 pub predicates: Option<Lazy<ty::GenericPredicates<'tcx>>>,
269 pub predicates_defined_on: Option<Lazy<ty::GenericPredicates<'tcx>>>,
271 pub mir: Option<Lazy<mir::Mir<'tcx>>>,
274 impl_stable_hash_for!(struct Entry<'tcx> {
287 predicates_defined_on,
291 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
292 pub enum EntryKind<'tcx> {
293 Const(ConstQualif, Lazy<RenderedConst>),
307 Variant(Lazy<VariantData<'tcx>>),
308 Struct(Lazy<VariantData<'tcx>>, ReprOptions),
309 Union(Lazy<VariantData<'tcx>>, ReprOptions),
310 Fn(Lazy<FnData<'tcx>>),
311 ForeignFn(Lazy<FnData<'tcx>>),
313 MacroDef(Lazy<MacroDef>),
314 Closure(Lazy<ClosureData<'tcx>>),
315 Generator(Lazy<GeneratorData<'tcx>>),
316 Trait(Lazy<TraitData<'tcx>>),
317 Impl(Lazy<ImplData<'tcx>>),
318 Method(Lazy<MethodData<'tcx>>),
319 AssociatedType(AssociatedContainer),
320 AssociatedExistential(AssociatedContainer),
321 AssociatedConst(AssociatedContainer, ConstQualif, Lazy<RenderedConst>),
322 TraitAlias(Lazy<TraitAliasData<'tcx>>),
325 impl<'a, 'gcx> HashStable<StableHashingContext<'a>> for EntryKind<'gcx> {
326 fn hash_stable<W: StableHasherResult>(&self,
327 hcx: &mut StableHashingContext<'a>,
328 hasher: &mut StableHasher<W>) {
329 mem::discriminant(self).hash_stable(hcx, hasher);
331 EntryKind::ImmStatic |
332 EntryKind::MutStatic |
333 EntryKind::ForeignImmStatic |
334 EntryKind::ForeignMutStatic |
335 EntryKind::ForeignMod |
336 EntryKind::GlobalAsm |
337 EntryKind::ForeignType |
339 EntryKind::Existential |
341 EntryKind::TypeParam |
342 EntryKind::ConstParam => {
343 // Nothing else to hash here.
345 EntryKind::Const(qualif, ref const_data) => {
346 qualif.hash_stable(hcx, hasher);
347 const_data.hash_stable(hcx, hasher);
349 EntryKind::Enum(ref repr_options) => {
350 repr_options.hash_stable(hcx, hasher);
352 EntryKind::Variant(ref variant_data) => {
353 variant_data.hash_stable(hcx, hasher);
355 EntryKind::Struct(ref variant_data, ref repr_options) |
356 EntryKind::Union(ref variant_data, ref repr_options) => {
357 variant_data.hash_stable(hcx, hasher);
358 repr_options.hash_stable(hcx, hasher);
360 EntryKind::Fn(ref fn_data) |
361 EntryKind::ForeignFn(ref fn_data) => {
362 fn_data.hash_stable(hcx, hasher);
364 EntryKind::Mod(ref mod_data) => {
365 mod_data.hash_stable(hcx, hasher);
367 EntryKind::MacroDef(ref macro_def) => {
368 macro_def.hash_stable(hcx, hasher);
370 EntryKind::Generator(data) => {
371 data.hash_stable(hcx, hasher);
373 EntryKind::Closure(closure_data) => {
374 closure_data.hash_stable(hcx, hasher);
376 EntryKind::Trait(ref trait_data) => {
377 trait_data.hash_stable(hcx, hasher);
379 EntryKind::TraitAlias(ref trait_alias_data) => {
380 trait_alias_data.hash_stable(hcx, hasher);
382 EntryKind::Impl(ref impl_data) => {
383 impl_data.hash_stable(hcx, hasher);
385 EntryKind::Method(ref method_data) => {
386 method_data.hash_stable(hcx, hasher);
388 EntryKind::AssociatedExistential(associated_container) |
389 EntryKind::AssociatedType(associated_container) => {
390 associated_container.hash_stable(hcx, hasher);
392 EntryKind::AssociatedConst(associated_container, qualif, ref const_data) => {
393 associated_container.hash_stable(hcx, hasher);
394 qualif.hash_stable(hcx, hasher);
395 const_data.hash_stable(hcx, hasher);
401 /// Additional data for EntryKind::Const and EntryKind::AssociatedConst
402 #[derive(Clone, Copy, RustcEncodable, RustcDecodable)]
403 pub struct ConstQualif {
405 pub ast_promotable: bool,
408 impl_stable_hash_for!(struct ConstQualif { mir, ast_promotable });
410 /// Contains a constant which has been rendered to a String.
412 #[derive(RustcEncodable, RustcDecodable)]
413 pub struct RenderedConst(pub String);
415 impl<'a> HashStable<StableHashingContext<'a>> for RenderedConst {
417 fn hash_stable<W: StableHasherResult>(&self,
418 hcx: &mut StableHashingContext<'a>,
419 hasher: &mut StableHasher<W>) {
420 self.0.hash_stable(hcx, hasher);
424 #[derive(RustcEncodable, RustcDecodable)]
426 pub reexports: LazySeq<def::Export<hir::HirId>>,
429 impl_stable_hash_for!(struct ModData { reexports });
431 #[derive(RustcEncodable, RustcDecodable)]
432 pub struct MacroDef {
437 impl_stable_hash_for!(struct MacroDef { body, legacy });
439 #[derive(RustcEncodable, RustcDecodable)]
440 pub struct FnData<'tcx> {
441 pub constness: hir::Constness,
442 pub arg_names: LazySeq<ast::Name>,
443 pub sig: Lazy<ty::PolyFnSig<'tcx>>,
446 impl_stable_hash_for!(struct FnData<'tcx> { constness, arg_names, sig });
448 #[derive(RustcEncodable, RustcDecodable)]
449 pub struct VariantData<'tcx> {
450 pub ctor_kind: CtorKind,
451 pub discr: ty::VariantDiscr,
452 /// If this is unit or tuple-variant/struct, then this is the index of the ctor id.
453 pub ctor: Option<DefIndex>,
454 /// If this is a tuple struct or variant
455 /// ctor, this is its "function" signature.
456 pub ctor_sig: Option<Lazy<ty::PolyFnSig<'tcx>>>,
459 impl_stable_hash_for!(struct VariantData<'tcx> {
466 #[derive(RustcEncodable, RustcDecodable)]
467 pub struct TraitData<'tcx> {
468 pub unsafety: hir::Unsafety,
469 pub paren_sugar: bool,
470 pub has_auto_impl: bool,
472 pub super_predicates: Lazy<ty::GenericPredicates<'tcx>>,
475 impl_stable_hash_for!(struct TraitData<'tcx> {
483 #[derive(RustcEncodable, RustcDecodable)]
484 pub struct TraitAliasData<'tcx> {
485 pub super_predicates: Lazy<ty::GenericPredicates<'tcx>>,
488 impl_stable_hash_for!(struct TraitAliasData<'tcx> {
492 #[derive(RustcEncodable, RustcDecodable)]
493 pub struct ImplData<'tcx> {
494 pub polarity: hir::ImplPolarity,
495 pub defaultness: hir::Defaultness,
496 pub parent_impl: Option<DefId>,
498 /// This is `Some` only for impls of `CoerceUnsized`.
499 pub coerce_unsized_info: Option<ty::adjustment::CoerceUnsizedInfo>,
500 pub trait_ref: Option<Lazy<ty::TraitRef<'tcx>>>,
503 impl_stable_hash_for!(struct ImplData<'tcx> {
512 /// Describes whether the container of an associated item
513 /// is a trait or an impl and whether, in a trait, it has
514 /// a default, or an in impl, whether it's marked "default".
515 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
516 pub enum AssociatedContainer {
523 impl_stable_hash_for!(enum crate::schema::AssociatedContainer {
530 impl AssociatedContainer {
531 pub fn with_def_id(&self, def_id: DefId) -> ty::AssociatedItemContainer {
533 AssociatedContainer::TraitRequired |
534 AssociatedContainer::TraitWithDefault => ty::TraitContainer(def_id),
536 AssociatedContainer::ImplDefault |
537 AssociatedContainer::ImplFinal => ty::ImplContainer(def_id),
541 pub fn defaultness(&self) -> hir::Defaultness {
543 AssociatedContainer::TraitRequired => hir::Defaultness::Default {
547 AssociatedContainer::TraitWithDefault |
548 AssociatedContainer::ImplDefault => hir::Defaultness::Default {
552 AssociatedContainer::ImplFinal => hir::Defaultness::Final,
557 #[derive(RustcEncodable, RustcDecodable)]
558 pub struct MethodData<'tcx> {
559 pub fn_data: FnData<'tcx>,
560 pub container: AssociatedContainer,
563 impl_stable_hash_for!(struct MethodData<'tcx> { fn_data, container, has_self });
565 #[derive(RustcEncodable, RustcDecodable)]
566 pub struct ClosureData<'tcx> {
567 pub sig: Lazy<ty::PolyFnSig<'tcx>>,
569 impl_stable_hash_for!(struct ClosureData<'tcx> { sig });
571 #[derive(RustcEncodable, RustcDecodable)]
572 pub struct GeneratorData<'tcx> {
573 pub layout: mir::GeneratorLayout<'tcx>,
575 impl_stable_hash_for!(struct GeneratorData<'tcx> { layout });
577 // Tags used for encoding Spans:
578 pub const TAG_VALID_SPAN: u8 = 0;
579 pub const TAG_INVALID_SPAN: u8 = 1;
581 #[derive(RustcEncodable, RustcDecodable)]
582 pub struct EncodedExportedSymbols {