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