1 use crate::table::PerDefTable;
4 use rustc::hir::def::{self, CtorKind};
5 use rustc::hir::def_id::{DefIndex, DefId};
6 use rustc::middle::exported_symbols::{ExportedSymbol, SymbolExportLevel};
7 use rustc::middle::cstore::{DepKind, LinkagePreference, NativeLibrary, ForeignModule};
8 use rustc::middle::lang_items;
10 use rustc::session::CrateDisambiguator;
11 use rustc::session::config::SymbolManglingVersion;
12 use rustc::ty::{self, Ty, ReprOptions};
13 use rustc_target::spec::{PanicStrategy, TargetTriple};
14 use rustc_index::vec::IndexVec;
15 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 crate fn rustc_version() -> String {
28 option_env!("CFG_VERSION").unwrap_or("unknown version"))
31 /// Metadata encoding version.
32 /// N.B., increment this if you change the format of metadata such that
33 /// the rustc version can't be found to compare with `rustc_version()`.
34 const METADATA_VERSION: u8 = 4;
36 /// Metadata header which includes `METADATA_VERSION`.
37 /// To get older versions of rustc to ignore this metadata,
38 /// there are 4 zero bytes at the start, which are treated
39 /// as a length of 0 by old compilers.
41 /// This header is followed by the position of the `CrateRoot`,
42 /// which is encoded as a 32-bit big-endian unsigned integer,
43 /// and further followed by the rustc version string.
44 crate const METADATA_HEADER: &[u8; 12] =
45 &[0, 0, 0, 0, b'r', b'u', b's', b't', 0, 0, 0, METADATA_VERSION];
47 /// Additional metadata for a `Lazy<T>` where `T` may not be `Sized`,
48 /// e.g. for `Lazy<[T]>`, this is the length (count of `T` values).
49 crate trait LazyMeta {
50 type Meta: Copy + 'static;
52 /// Returns the minimum encoded size.
53 // FIXME(eddyb) Give better estimates for certain types.
54 fn min_size(meta: Self::Meta) -> usize;
57 impl<T: Encodable> LazyMeta for T {
60 fn min_size(_: ()) -> usize {
61 assert_ne!(std::mem::size_of::<T>(), 0);
66 impl<T: Encodable> LazyMeta for [T] {
69 fn min_size(len: usize) -> usize {
74 /// A value of type T referred to by its absolute position
75 /// in the metadata, and which can be decoded lazily.
77 /// Metadata is effective a tree, encoded in post-order,
78 /// and with the root's position written next to the header.
79 /// That means every single `Lazy` points to some previous
80 /// location in the metadata and is part of a larger node.
82 /// The first `Lazy` in a node is encoded as the backwards
83 /// distance from the position where the containing node
84 /// starts and where the `Lazy` points to, while the rest
85 /// use the forward distance from the previous `Lazy`.
86 /// Distances start at 1, as 0-byte nodes are invalid.
87 /// Also invalid are nodes being referred in a different
88 /// order than they were encoded in.
90 /// # Sequences (`Lazy<[T]>`)
92 /// Unlike `Lazy<Vec<T>>`, the length is encoded next to the
93 /// position, not at the position, which means that the length
94 /// doesn't need to be known before encoding all the elements.
96 /// If the length is 0, no position is encoded, but otherwise,
97 /// the encoding is that of `Lazy`, with the distinction that
98 /// the minimal distance the length of the sequence, i.e.
99 /// it's assumed there's no 0-byte element in the sequence.
101 // FIXME(#59875) the `Meta` parameter only exists to dodge
102 // invariance wrt `T` (coming from the `meta: T::Meta` field).
103 crate struct Lazy<T, Meta = <T as LazyMeta>::Meta>
104 where T: ?Sized + LazyMeta<Meta = Meta>,
105 Meta: 'static + Copy,
107 pub position: NonZeroUsize,
109 _marker: PhantomData<T>,
112 impl<T: ?Sized + LazyMeta> Lazy<T> {
113 crate fn from_position_and_meta(position: NonZeroUsize, meta: T::Meta) -> Lazy<T> {
117 _marker: PhantomData,
122 impl<T: Encodable> Lazy<T> {
123 crate fn from_position(position: NonZeroUsize) -> Lazy<T> {
124 Lazy::from_position_and_meta(position, ())
128 impl<T: Encodable> Lazy<[T]> {
129 crate 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)]
146 crate enum LazyState {
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<$T:ty>) => {Lazy<Table<$T>, usize>};
165 (PerDefTable<$T:ty>) => {Lazy<PerDefTable<$T>, usize>};
166 ([$T:ty]) => {Lazy<[$T], usize>};
167 ($T:ty) => {Lazy<$T, ()>};
170 #[derive(RustcEncodable, RustcDecodable)]
171 crate struct CrateRoot<'tcx> {
173 pub triple: TargetTriple,
174 pub extra_filename: String,
176 pub disambiguator: CrateDisambiguator,
177 pub panic_strategy: PanicStrategy,
178 pub edition: Edition,
179 pub has_global_allocator: bool,
180 pub has_panic_handler: bool,
181 pub has_default_lib_allocator: bool,
182 pub plugin_registrar_fn: Option<DefIndex>,
183 pub proc_macro_decls_static: Option<DefIndex>,
184 pub proc_macro_stability: Option<attr::Stability>,
186 pub crate_deps: Lazy<[CrateDep]>,
187 pub dylib_dependency_formats: Lazy<[Option<LinkagePreference>]>,
188 pub lib_features: Lazy<[(Symbol, Option<Symbol>)]>,
189 pub lang_items: Lazy<[(DefIndex, usize)]>,
190 pub lang_items_missing: Lazy<[lang_items::LangItem]>,
191 pub diagnostic_items: Lazy<[(Symbol, DefIndex)]>,
192 pub native_libraries: Lazy<[NativeLibrary]>,
193 pub foreign_modules: Lazy<[ForeignModule]>,
194 pub source_map: Lazy<[syntax_pos::SourceFile]>,
195 pub def_path_table: Lazy<hir::map::definitions::DefPathTable>,
196 pub impls: Lazy<[TraitImpls]>,
197 pub exported_symbols: Lazy!([(ExportedSymbol<'tcx>, SymbolExportLevel)]),
198 pub interpret_alloc_index: Lazy<[u32]>,
200 pub per_def: LazyPerDefTables<'tcx>,
202 /// The DefIndex's of any proc macros delcared by
204 pub proc_macro_data: Option<Lazy<[DefIndex]>>,
206 pub compiler_builtins: bool,
207 pub needs_allocator: bool,
208 pub needs_panic_runtime: bool,
209 pub no_builtins: bool,
210 pub panic_runtime: bool,
211 pub profiler_runtime: bool,
212 pub sanitizer_runtime: bool,
213 pub symbol_mangling_version: SymbolManglingVersion,
216 #[derive(RustcEncodable, RustcDecodable)]
217 crate struct CrateDep {
221 pub extra_filename: String,
224 #[derive(RustcEncodable, RustcDecodable)]
225 crate struct TraitImpls {
226 pub trait_id: (u32, DefIndex),
227 pub impls: Lazy<[DefIndex]>,
230 #[derive(RustcEncodable, RustcDecodable)]
231 crate struct LazyPerDefTables<'tcx> {
232 pub kind: Lazy!(PerDefTable<Lazy!(EntryKind<'tcx>)>),
233 pub visibility: Lazy!(PerDefTable<Lazy<ty::Visibility>>),
234 pub span: Lazy!(PerDefTable<Lazy<Span>>),
235 pub attributes: Lazy!(PerDefTable<Lazy<[ast::Attribute]>>),
236 pub children: Lazy!(PerDefTable<Lazy<[DefIndex]>>),
237 pub stability: Lazy!(PerDefTable<Lazy<attr::Stability>>),
238 pub deprecation: Lazy!(PerDefTable<Lazy<attr::Deprecation>>),
240 pub ty: Lazy!(PerDefTable<Lazy!(Ty<'tcx>)>),
241 pub inherent_impls: Lazy!(PerDefTable<Lazy<[DefIndex]>>),
242 pub variances: Lazy!(PerDefTable<Lazy<[ty::Variance]>>),
243 pub generics: Lazy!(PerDefTable<Lazy<ty::Generics>>),
244 pub predicates: Lazy!(PerDefTable<Lazy!(ty::GenericPredicates<'tcx>)>),
245 pub predicates_defined_on: Lazy!(PerDefTable<Lazy!(ty::GenericPredicates<'tcx>)>),
247 pub mir: Lazy!(PerDefTable<Lazy!(mir::Body<'tcx>)>),
248 pub promoted_mir: Lazy!(PerDefTable<Lazy!(IndexVec<mir::Promoted, mir::Body<'tcx>>)>),
251 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
252 crate enum EntryKind<'tcx> {
253 Const(ConstQualif, Lazy<RenderedConst>),
267 Variant(Lazy!(VariantData<'tcx>)),
268 Struct(Lazy!(VariantData<'tcx>), ReprOptions),
269 Union(Lazy!(VariantData<'tcx>), ReprOptions),
270 Fn(Lazy!(FnData<'tcx>)),
271 ForeignFn(Lazy!(FnData<'tcx>)),
273 MacroDef(Lazy<MacroDef>),
274 Closure(Lazy!(ClosureData<'tcx>)),
275 Generator(Lazy!(GeneratorData<'tcx>)),
276 Trait(Lazy!(TraitData<'tcx>)),
277 Impl(Lazy!(ImplData<'tcx>)),
278 Method(Lazy!(MethodData<'tcx>)),
279 AssocType(AssocContainer),
280 AssocOpaqueTy(AssocContainer),
281 AssocConst(AssocContainer, ConstQualif, Lazy<RenderedConst>),
282 TraitAlias(Lazy!(TraitAliasData<'tcx>)),
285 /// Additional data for EntryKind::Const and EntryKind::AssocConst
286 #[derive(Clone, Copy, RustcEncodable, RustcDecodable)]
287 crate struct ConstQualif {
291 /// Contains a constant which has been rendered to a String.
293 #[derive(RustcEncodable, RustcDecodable)]
294 crate struct RenderedConst(pub String);
296 #[derive(RustcEncodable, RustcDecodable)]
297 crate struct ModData {
298 pub reexports: Lazy<[def::Export<hir::HirId>]>,
301 #[derive(RustcEncodable, RustcDecodable)]
302 crate struct MacroDef {
307 #[derive(RustcEncodable, RustcDecodable)]
308 crate struct FnData<'tcx> {
309 pub asyncness: hir::IsAsync,
310 pub constness: hir::Constness,
311 pub param_names: Lazy<[ast::Name]>,
312 pub sig: Lazy!(ty::PolyFnSig<'tcx>),
315 #[derive(RustcEncodable, RustcDecodable)]
316 crate struct VariantData<'tcx> {
317 pub ctor_kind: CtorKind,
318 pub discr: ty::VariantDiscr,
319 /// If this is unit or tuple-variant/struct, then this is the index of the ctor id.
320 pub ctor: Option<DefIndex>,
321 /// If this is a tuple struct or variant
322 /// ctor, this is its "function" signature.
323 pub ctor_sig: Option<Lazy!(ty::PolyFnSig<'tcx>)>,
326 #[derive(RustcEncodable, RustcDecodable)]
327 crate struct TraitData<'tcx> {
328 pub unsafety: hir::Unsafety,
329 pub paren_sugar: bool,
330 pub has_auto_impl: bool,
332 pub super_predicates: Lazy!(ty::GenericPredicates<'tcx>),
335 #[derive(RustcEncodable, RustcDecodable)]
336 crate struct TraitAliasData<'tcx> {
337 pub super_predicates: Lazy!(ty::GenericPredicates<'tcx>),
340 #[derive(RustcEncodable, RustcDecodable)]
341 crate struct ImplData<'tcx> {
342 pub polarity: ty::ImplPolarity,
343 pub defaultness: hir::Defaultness,
344 pub parent_impl: Option<DefId>,
346 /// This is `Some` only for impls of `CoerceUnsized`.
347 pub coerce_unsized_info: Option<ty::adjustment::CoerceUnsizedInfo>,
348 pub trait_ref: Option<Lazy!(ty::TraitRef<'tcx>)>,
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 crate enum AssocContainer {
363 impl AssocContainer {
364 crate 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 crate 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)]
391 crate struct MethodData<'tcx> {
392 pub fn_data: FnData<'tcx>,
393 pub container: AssocContainer,
397 #[derive(RustcEncodable, RustcDecodable)]
398 crate struct ClosureData<'tcx> {
399 pub sig: Lazy!(ty::PolyFnSig<'tcx>),
402 #[derive(RustcEncodable, RustcDecodable)]
403 crate struct GeneratorData<'tcx> {
404 pub layout: mir::GeneratorLayout<'tcx>,
407 // Tags used for encoding Spans:
408 crate const TAG_VALID_SPAN: u8 = 0;
409 crate const TAG_INVALID_SPAN: u8 = 1;