]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/rmeta/mod.rs
5abae4293731d9c4f58dc9944e37c8a00da89856
[rust.git] / src / librustc_metadata / rmeta / mod.rs
1 use decoder::Metadata;
2 use table::{Table, TableBuilder};
3
4 use rustc::hir;
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;
10 use rustc::mir;
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_data_structures::sync::MetadataRef;
18 use rustc_serialize::opaque::Encoder;
19 use syntax::{ast, attr};
20 use syntax::edition::Edition;
21 use syntax::symbol::Symbol;
22 use syntax_pos::{self, Span};
23
24 use std::marker::PhantomData;
25 use std::num::NonZeroUsize;
26
27 pub use decoder::{provide, provide_extern};
28 crate use decoder::{CrateMetadata, CrateNumMap, MetadataBlob};
29
30 mod decoder;
31 mod encoder;
32 mod table;
33
34 crate fn rustc_version() -> String {
35     format!("rustc {}",
36             option_env!("CFG_VERSION").unwrap_or("unknown version"))
37 }
38
39 /// Metadata encoding version.
40 /// N.B., increment this if you change the format of metadata such that
41 /// the rustc version can't be found to compare with `rustc_version()`.
42 const METADATA_VERSION: u8 = 5;
43
44 /// Metadata header which includes `METADATA_VERSION`.
45 ///
46 /// This header is followed by the position of the `CrateRoot`,
47 /// which is encoded as a 32-bit big-endian unsigned integer,
48 /// and further followed by the rustc version string.
49 crate const METADATA_HEADER: &[u8; 8] =
50     &[b'r', b'u', b's', b't', 0, 0, 0, METADATA_VERSION];
51
52 /// Additional metadata for a `Lazy<T>` where `T` may not be `Sized`,
53 /// e.g. for `Lazy<[T]>`, this is the length (count of `T` values).
54 trait LazyMeta {
55     type Meta: Copy + 'static;
56
57     /// Returns the minimum encoded size.
58     // FIXME(eddyb) Give better estimates for certain types.
59     fn min_size(meta: Self::Meta) -> usize;
60 }
61
62 impl<T> LazyMeta for T {
63     type Meta = ();
64
65     fn min_size(_: ()) -> usize {
66         assert_ne!(std::mem::size_of::<T>(), 0);
67         1
68     }
69 }
70
71 impl<T> LazyMeta for [T] {
72     type Meta = usize;
73
74     fn min_size(len: usize) -> usize {
75         len * T::min_size(())
76     }
77 }
78
79 /// A value of type T referred to by its absolute position
80 /// in the metadata, and which can be decoded lazily.
81 ///
82 /// Metadata is effective a tree, encoded in post-order,
83 /// and with the root's position written next to the header.
84 /// That means every single `Lazy` points to some previous
85 /// location in the metadata and is part of a larger node.
86 ///
87 /// The first `Lazy` in a node is encoded as the backwards
88 /// distance from the position where the containing node
89 /// starts and where the `Lazy` points to, while the rest
90 /// use the forward distance from the previous `Lazy`.
91 /// Distances start at 1, as 0-byte nodes are invalid.
92 /// Also invalid are nodes being referred in a different
93 /// order than they were encoded in.
94 ///
95 /// # Sequences (`Lazy<[T]>`)
96 ///
97 /// Unlike `Lazy<Vec<T>>`, the length is encoded next to the
98 /// position, not at the position, which means that the length
99 /// doesn't need to be known before encoding all the elements.
100 ///
101 /// If the length is 0, no position is encoded, but otherwise,
102 /// the encoding is that of `Lazy`, with the distinction that
103 /// the minimal distance the length of the sequence, i.e.
104 /// it's assumed there's no 0-byte element in the sequence.
105 #[must_use]
106 // FIXME(#59875) the `Meta` parameter only exists to dodge
107 // invariance wrt `T` (coming from the `meta: T::Meta` field).
108 struct Lazy<T, Meta = <T as LazyMeta>::Meta>
109     where T: ?Sized + LazyMeta<Meta = Meta>,
110           Meta: 'static + Copy,
111 {
112     position: NonZeroUsize,
113     meta: Meta,
114     _marker: PhantomData<T>,
115 }
116
117 impl<T: ?Sized + LazyMeta> Lazy<T> {
118      fn from_position_and_meta(position: NonZeroUsize, meta: T::Meta) -> Lazy<T> {
119         Lazy {
120             position,
121             meta,
122             _marker: PhantomData,
123         }
124     }
125 }
126
127 impl<T> Lazy<T> {
128     fn from_position(position: NonZeroUsize) -> Lazy<T> {
129         Lazy::from_position_and_meta(position, ())
130     }
131 }
132
133 impl<T> Lazy<[T]> {
134     fn empty() -> Lazy<[T]> {
135         Lazy::from_position_and_meta(NonZeroUsize::new(1).unwrap(), 0)
136     }
137 }
138
139 impl<T: ?Sized + LazyMeta> Copy for Lazy<T> {}
140 impl<T: ?Sized + LazyMeta> Clone for Lazy<T> {
141     fn clone(&self) -> Self {
142         *self
143     }
144 }
145
146 impl<T: ?Sized + LazyMeta> rustc_serialize::UseSpecializedEncodable for Lazy<T> {}
147 impl<T: ?Sized + LazyMeta> rustc_serialize::UseSpecializedDecodable for Lazy<T> {}
148
149 /// Encoding / decoding state for `Lazy`.
150 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
151 enum LazyState {
152     /// Outside of a metadata node.
153     NoNode,
154
155     /// Inside a metadata node, and before any `Lazy`.
156     /// The position is that of the node itself.
157     NodeStart(NonZeroUsize),
158
159     /// Inside a metadata node, with a previous `Lazy`.
160     /// The position is a conservative estimate of where that
161     /// previous `Lazy` would end (see their comments).
162     Previous(NonZeroUsize),
163 }
164
165 // FIXME(#59875) `Lazy!(T)` replaces `Lazy<T>`, passing the `Meta` parameter
166 // manually, instead of relying on the default, to get the correct variance.
167 // Only needed when `T` itself contains a parameter (e.g. `'tcx`).
168 macro_rules! Lazy {
169     (Table<$I:ty, $T:ty>) => {Lazy<Table<$I, $T>, usize>};
170     ([$T:ty]) => {Lazy<[$T], usize>};
171     ($T:ty) => {Lazy<$T, ()>};
172 }
173
174 #[derive(RustcEncodable, RustcDecodable)]
175 crate struct CrateRoot<'tcx> {
176     name: Symbol,
177     triple: TargetTriple,
178     extra_filename: String,
179     hash: Svh,
180     disambiguator: CrateDisambiguator,
181     panic_strategy: PanicStrategy,
182     edition: Edition,
183     has_global_allocator: bool,
184     has_panic_handler: bool,
185     has_default_lib_allocator: bool,
186     plugin_registrar_fn: Option<DefIndex>,
187     proc_macro_decls_static: Option<DefIndex>,
188     proc_macro_stability: Option<attr::Stability>,
189
190     crate_deps: Lazy<[CrateDep]>,
191     dylib_dependency_formats: Lazy<[Option<LinkagePreference>]>,
192     lib_features: Lazy<[(Symbol, Option<Symbol>)]>,
193     lang_items: Lazy<[(DefIndex, usize)]>,
194     lang_items_missing: Lazy<[lang_items::LangItem]>,
195     diagnostic_items: Lazy<[(Symbol, DefIndex)]>,
196     native_libraries: Lazy<[NativeLibrary]>,
197     foreign_modules: Lazy<[ForeignModule]>,
198     source_map: Lazy<[syntax_pos::SourceFile]>,
199     def_path_table: Lazy<hir::map::definitions::DefPathTable>,
200     impls: Lazy<[TraitImpls]>,
201     exported_symbols: Lazy!([(ExportedSymbol<'tcx>, SymbolExportLevel)]),
202     interpret_alloc_index: Lazy<[u32]>,
203
204     per_def: LazyPerDefTables<'tcx>,
205
206     /// The DefIndex's of any proc macros delcared by this crate.
207     proc_macro_data: Option<Lazy<[DefIndex]>>,
208
209     compiler_builtins: bool,
210     needs_allocator: bool,
211     needs_panic_runtime: bool,
212     no_builtins: bool,
213     panic_runtime: bool,
214     profiler_runtime: bool,
215     sanitizer_runtime: bool,
216     symbol_mangling_version: SymbolManglingVersion,
217 }
218
219 #[derive(RustcEncodable, RustcDecodable)]
220 crate struct CrateDep {
221     pub name: ast::Name,
222     pub hash: Svh,
223     pub host_hash: Option<Svh>,
224     pub kind: DepKind,
225     pub extra_filename: String,
226 }
227
228 #[derive(RustcEncodable, RustcDecodable)]
229 crate struct TraitImpls {
230     trait_id: (u32, DefIndex),
231     impls: Lazy<[DefIndex]>,
232 }
233
234 /// Define `LazyPerDefTables` and `PerDefTableBuilders` at the same time.
235 macro_rules! define_per_def_tables {
236     ($($name:ident: Table<DefIndex, $T:ty>),+ $(,)?) => {
237         #[derive(RustcEncodable, RustcDecodable)]
238         crate struct LazyPerDefTables<'tcx> {
239             $($name: Lazy!(Table<DefIndex, $T>)),+
240         }
241
242         #[derive(Default)]
243         struct PerDefTableBuilders<'tcx> {
244             $($name: TableBuilder<DefIndex, $T>),+
245         }
246
247         impl PerDefTableBuilders<'tcx> {
248             fn encode(&self, buf: &mut Encoder) -> LazyPerDefTables<'tcx> {
249                 LazyPerDefTables {
250                     $($name: self.$name.encode(buf)),+
251                 }
252             }
253         }
254     }
255 }
256
257 define_per_def_tables! {
258     kind: Table<DefIndex, Lazy!(EntryKind<'tcx>)>,
259     visibility: Table<DefIndex, Lazy<ty::Visibility>>,
260     span: Table<DefIndex, Lazy<Span>>,
261     attributes: Table<DefIndex, Lazy<[ast::Attribute]>>,
262     children: Table<DefIndex, Lazy<[DefIndex]>>,
263     stability: Table<DefIndex, Lazy<attr::Stability>>,
264     deprecation: Table<DefIndex, Lazy<attr::Deprecation>>,
265     ty: Table<DefIndex, Lazy!(Ty<'tcx>)>,
266     fn_sig: Table<DefIndex, Lazy!(ty::PolyFnSig<'tcx>)>,
267     impl_trait_ref: Table<DefIndex, Lazy!(ty::TraitRef<'tcx>)>,
268     inherent_impls: Table<DefIndex, Lazy<[DefIndex]>>,
269     variances: Table<DefIndex, Lazy<[ty::Variance]>>,
270     generics: Table<DefIndex, Lazy<ty::Generics>>,
271     explicit_predicates: Table<DefIndex, Lazy!(ty::GenericPredicates<'tcx>)>,
272     // FIXME(eddyb) this would ideally be `Lazy<[...]>` but `ty::Predicate`
273     // doesn't handle shorthands in its own (de)serialization impls,
274     // as it's an `enum` for which we want to derive (de)serialization,
275     // so the `ty::codec` APIs handle the whole `&'tcx [...]` at once.
276     // Also, as an optimization, a missing entry indicates an empty `&[]`.
277     inferred_outlives: Table<DefIndex, Lazy!(&'tcx [(ty::Predicate<'tcx>, Span)])>,
278     super_predicates: Table<DefIndex, Lazy!(ty::GenericPredicates<'tcx>)>,
279     mir: Table<DefIndex, Lazy!(mir::BodyAndCache<'tcx>)>,
280     promoted_mir: Table<DefIndex, Lazy!(IndexVec<mir::Promoted, mir::BodyAndCache<'tcx>>)>,
281 }
282
283 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
284 enum EntryKind<'tcx> {
285     Const(mir::ConstQualifs, Lazy<RenderedConst>),
286     ImmStatic,
287     MutStatic,
288     ForeignImmStatic,
289     ForeignMutStatic,
290     ForeignMod,
291     ForeignType,
292     GlobalAsm,
293     Type,
294     TypeParam,
295     ConstParam,
296     OpaqueTy,
297     Enum(ReprOptions),
298     Field,
299     Variant(Lazy<VariantData>),
300     Struct(Lazy<VariantData>, ReprOptions),
301     Union(Lazy<VariantData>, ReprOptions),
302     Fn(Lazy<FnData>),
303     ForeignFn(Lazy<FnData>),
304     Mod(Lazy<ModData>),
305     MacroDef(Lazy<MacroDef>),
306     Closure,
307     Generator(Lazy!(GeneratorData<'tcx>)),
308     Trait(Lazy<TraitData>),
309     Impl(Lazy<ImplData>),
310     Method(Lazy<MethodData>),
311     AssocType(AssocContainer),
312     AssocOpaqueTy(AssocContainer),
313     AssocConst(AssocContainer, mir::ConstQualifs, Lazy<RenderedConst>),
314     TraitAlias,
315 }
316
317 /// Contains a constant which has been rendered to a String.
318 /// Used by rustdoc.
319 #[derive(RustcEncodable, RustcDecodable)]
320 struct RenderedConst(String);
321
322 #[derive(RustcEncodable, RustcDecodable)]
323 struct ModData {
324     reexports: Lazy<[def::Export<hir::HirId>]>,
325 }
326
327 #[derive(RustcEncodable, RustcDecodable)]
328 struct MacroDef {
329     body: String,
330     legacy: bool,
331 }
332
333 #[derive(RustcEncodable, RustcDecodable)]
334 struct FnData {
335     asyncness: hir::IsAsync,
336     constness: hir::Constness,
337     param_names: Lazy<[ast::Name]>,
338 }
339
340 #[derive(RustcEncodable, RustcDecodable)]
341 struct VariantData {
342     ctor_kind: CtorKind,
343     discr: ty::VariantDiscr,
344     /// If this is unit or tuple-variant/struct, then this is the index of the ctor id.
345     ctor: Option<DefIndex>,
346 }
347
348 #[derive(RustcEncodable, RustcDecodable)]
349 struct TraitData {
350     unsafety: hir::Unsafety,
351     paren_sugar: bool,
352     has_auto_impl: bool,
353     is_marker: bool,
354 }
355
356 #[derive(RustcEncodable, RustcDecodable)]
357 struct ImplData {
358     polarity: ty::ImplPolarity,
359     defaultness: hir::Defaultness,
360     parent_impl: Option<DefId>,
361
362     /// This is `Some` only for impls of `CoerceUnsized`.
363     // FIXME(eddyb) perhaps compute this on the fly if cheap enough?
364     coerce_unsized_info: Option<ty::adjustment::CoerceUnsizedInfo>,
365 }
366
367
368 /// Describes whether the container of an associated item
369 /// is a trait or an impl and whether, in a trait, it has
370 /// a default, or an in impl, whether it's marked "default".
371 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
372 enum AssocContainer {
373     TraitRequired,
374     TraitWithDefault,
375     ImplDefault,
376     ImplFinal,
377 }
378
379 impl AssocContainer {
380     fn with_def_id(&self, def_id: DefId) -> ty::AssocItemContainer {
381         match *self {
382             AssocContainer::TraitRequired |
383             AssocContainer::TraitWithDefault => ty::TraitContainer(def_id),
384
385             AssocContainer::ImplDefault |
386             AssocContainer::ImplFinal => ty::ImplContainer(def_id),
387         }
388     }
389
390     fn defaultness(&self) -> hir::Defaultness {
391         match *self {
392             AssocContainer::TraitRequired => hir::Defaultness::Default {
393                 has_value: false,
394             },
395
396             AssocContainer::TraitWithDefault |
397             AssocContainer::ImplDefault => hir::Defaultness::Default {
398                 has_value: true,
399             },
400
401             AssocContainer::ImplFinal => hir::Defaultness::Final,
402         }
403     }
404 }
405
406 #[derive(RustcEncodable, RustcDecodable)]
407 struct MethodData {
408     fn_data: FnData,
409     container: AssocContainer,
410     has_self: bool,
411 }
412
413 #[derive(RustcEncodable, RustcDecodable)]
414 struct GeneratorData<'tcx> {
415     layout: mir::GeneratorLayout<'tcx>,
416 }
417
418 // Tags used for encoding Spans:
419 const TAG_VALID_SPAN: u8 = 0;
420 const TAG_INVALID_SPAN: u8 = 1;