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