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