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