]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/rmeta/mod.rs
71872d53a56e7ec270b01569f332968ccc4a0df2
[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::vec::IndexVec;
13 use rustc_middle::hir::exports::Export;
14 use rustc_middle::middle::cstore::{DepKind, ForeignModule, LinkagePreference, NativeLibrary};
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::Symbol;
23 use rustc_span::{self, 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
32 mod decoder;
33 mod encoder;
34 mod table;
35
36 crate fn rustc_version() -> String {
37     format!("rustc {}", option_env!("CFG_VERSION").unwrap_or("unknown version"))
38 }
39
40 /// Metadata encoding version.
41 /// N.B., increment this if you change the format of metadata such that
42 /// the rustc version can't be found to compare with `rustc_version()`.
43 const METADATA_VERSION: u8 = 5;
44
45 /// Metadata header which includes `METADATA_VERSION`.
46 ///
47 /// This header is followed by the position of the `CrateRoot`,
48 /// which is encoded as a 32-bit big-endian unsigned integer,
49 /// and further followed by the rustc version string.
50 crate const METADATA_HEADER: &[u8; 8] = &[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
110     T: ?Sized + LazyMeta<Meta = Meta>,
111     Meta: 'static + Copy,
112 {
113     position: NonZeroUsize,
114     meta: Meta,
115     _marker: PhantomData<T>,
116 }
117
118 impl<T: ?Sized + LazyMeta> Lazy<T> {
119     fn from_position_and_meta(position: NonZeroUsize, meta: T::Meta) -> Lazy<T> {
120         Lazy { position, meta, _marker: PhantomData }
121     }
122 }
123
124 impl<T> Lazy<T> {
125     fn from_position(position: NonZeroUsize) -> Lazy<T> {
126         Lazy::from_position_and_meta(position, ())
127     }
128 }
129
130 impl<T> Lazy<[T]> {
131     fn empty() -> Lazy<[T]> {
132         Lazy::from_position_and_meta(NonZeroUsize::new(1).unwrap(), 0)
133     }
134 }
135
136 impl<T: ?Sized + LazyMeta> Copy for Lazy<T> {}
137 impl<T: ?Sized + LazyMeta> Clone for Lazy<T> {
138     fn clone(&self) -> Self {
139         *self
140     }
141 }
142
143 impl<T: ?Sized + LazyMeta> rustc_serialize::UseSpecializedEncodable for Lazy<T> {}
144 impl<T: ?Sized + LazyMeta> rustc_serialize::UseSpecializedDecodable for Lazy<T> {}
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 #[derive(RustcEncodable, RustcDecodable)]
172 crate struct CrateRoot<'tcx> {
173     name: Symbol,
174     triple: TargetTriple,
175     extra_filename: String,
176     hash: Svh,
177     disambiguator: CrateDisambiguator,
178     panic_strategy: PanicStrategy,
179     edition: Edition,
180     has_global_allocator: bool,
181     has_panic_handler: bool,
182     has_default_lib_allocator: bool,
183     plugin_registrar_fn: Option<DefIndex>,
184     proc_macro_decls_static: Option<DefIndex>,
185     proc_macro_stability: Option<attr::Stability>,
186
187     crate_deps: Lazy<[CrateDep]>,
188     dylib_dependency_formats: Lazy<[Option<LinkagePreference>]>,
189     lib_features: Lazy<[(Symbol, Option<Symbol>)]>,
190     lang_items: Lazy<[(DefIndex, usize)]>,
191     lang_items_missing: Lazy<[lang_items::LangItem]>,
192     diagnostic_items: Lazy<[(Symbol, DefIndex)]>,
193     native_libraries: Lazy<[NativeLibrary]>,
194     foreign_modules: Lazy<[ForeignModule]>,
195     source_map: Lazy<[rustc_span::SourceFile]>,
196     def_path_table: Lazy<rustc_hir::definitions::DefPathTable>,
197     impls: Lazy<[TraitImpls]>,
198     interpret_alloc_index: Lazy<[u32]>,
199
200     tables: LazyTables<'tcx>,
201
202     /// The DefIndex's of any proc macros declared by this crate.
203     proc_macro_data: Option<Lazy<[DefIndex]>>,
204
205     exported_symbols: Lazy!([(ExportedSymbol<'tcx>, SymbolExportLevel)]),
206
207     compiler_builtins: bool,
208     needs_allocator: bool,
209     needs_panic_runtime: bool,
210     no_builtins: bool,
211     panic_runtime: bool,
212     profiler_runtime: bool,
213     symbol_mangling_version: SymbolManglingVersion,
214 }
215
216 #[derive(RustcEncodable, RustcDecodable)]
217 crate struct CrateDep {
218     pub name: ast::Name,
219     pub hash: Svh,
220     pub host_hash: Option<Svh>,
221     pub kind: DepKind,
222     pub extra_filename: String,
223 }
224
225 #[derive(RustcEncodable, RustcDecodable)]
226 crate struct TraitImpls {
227     trait_id: (u32, DefIndex),
228     impls: Lazy<[DefIndex]>,
229 }
230
231 /// Define `LazyTables` and `TableBuilders` at the same time.
232 macro_rules! define_tables {
233     ($($name:ident: Table<DefIndex, $T:ty>),+ $(,)?) => {
234         #[derive(RustcEncodable, RustcDecodable)]
235         crate struct LazyTables<'tcx> {
236             $($name: Lazy!(Table<DefIndex, $T>)),+
237         }
238
239         #[derive(Default)]
240         struct TableBuilders<'tcx> {
241             $($name: TableBuilder<DefIndex, $T>),+
242         }
243
244         impl TableBuilders<'tcx> {
245             fn encode(&self, buf: &mut Encoder) -> LazyTables<'tcx> {
246                 LazyTables {
247                     $($name: self.$name.encode(buf)),+
248                 }
249             }
250         }
251     }
252 }
253
254 define_tables! {
255     kind: Table<DefIndex, Lazy<EntryKind>>,
256     visibility: Table<DefIndex, Lazy<ty::Visibility>>,
257     span: Table<DefIndex, Lazy<Span>>,
258     ident_span: Table<DefIndex, Lazy<Span>>,
259     attributes: Table<DefIndex, Lazy<[ast::Attribute]>>,
260     children: Table<DefIndex, Lazy<[DefIndex]>>,
261     stability: Table<DefIndex, Lazy<attr::Stability>>,
262     const_stability: Table<DefIndex, Lazy<attr::ConstStability>>,
263     deprecation: Table<DefIndex, Lazy<attr::Deprecation>>,
264     ty: Table<DefIndex, Lazy!(Ty<'tcx>)>,
265     fn_sig: Table<DefIndex, Lazy!(ty::PolyFnSig<'tcx>)>,
266     impl_trait_ref: Table<DefIndex, Lazy!(ty::TraitRef<'tcx>)>,
267     inherent_impls: Table<DefIndex, Lazy<[DefIndex]>>,
268     variances: Table<DefIndex, Lazy<[ty::Variance]>>,
269     generics: Table<DefIndex, Lazy<ty::Generics>>,
270     explicit_predicates: Table<DefIndex, Lazy!(ty::GenericPredicates<'tcx>)>,
271     // FIXME(eddyb) this would ideally be `Lazy<[...]>` but `ty::Predicate`
272     // doesn't handle shorthands in its own (de)serialization impls,
273     // as it's an `enum` for which we want to derive (de)serialization,
274     // so the `ty::codec` APIs handle the whole `&'tcx [...]` at once.
275     // Also, as an optimization, a missing entry indicates an empty `&[]`.
276     inferred_outlives: Table<DefIndex, Lazy!(&'tcx [(ty::Predicate<'tcx>, Span)])>,
277     super_predicates: Table<DefIndex, Lazy!(ty::GenericPredicates<'tcx>)>,
278     mir: Table<DefIndex, Lazy!(mir::BodyAndCache<'tcx>)>,
279     promoted_mir: Table<DefIndex, Lazy!(IndexVec<mir::Promoted, mir::BodyAndCache<'tcx>>)>,
280 }
281
282 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
283 enum EntryKind {
284     Const(mir::ConstQualifs, Lazy<RenderedConst>),
285     ImmStatic,
286     MutStatic,
287     ForeignImmStatic,
288     ForeignMutStatic,
289     ForeignMod,
290     ForeignType,
291     GlobalAsm,
292     Type,
293     TypeParam,
294     ConstParam,
295     OpaqueTy,
296     Enum(ReprOptions),
297     Field,
298     Variant(Lazy<VariantData>),
299     Struct(Lazy<VariantData>, ReprOptions),
300     Union(Lazy<VariantData>, ReprOptions),
301     Fn(Lazy<FnData>),
302     ForeignFn(Lazy<FnData>),
303     Mod(Lazy<ModData>),
304     MacroDef(Lazy<MacroDef>),
305     Closure,
306     Generator(hir::GeneratorKind),
307     Trait(Lazy<TraitData>),
308     Impl(Lazy<ImplData>),
309     AssocFn(Lazy<AssocFnData>),
310     AssocType(AssocContainer),
311     AssocOpaqueTy(AssocContainer),
312     AssocConst(AssocContainer, mir::ConstQualifs, Lazy<RenderedConst>),
313     TraitAlias,
314 }
315
316 /// Contains a constant which has been rendered to a String.
317 /// Used by rustdoc.
318 #[derive(RustcEncodable, RustcDecodable)]
319 struct RenderedConst(String);
320
321 #[derive(RustcEncodable, RustcDecodable)]
322 struct ModData {
323     reexports: Lazy<[Export<hir::HirId>]>,
324 }
325
326 #[derive(RustcEncodable, RustcDecodable)]
327 struct FnData {
328     asyncness: hir::IsAsync,
329     constness: hir::Constness,
330     param_names: Lazy<[ast::Name]>,
331 }
332
333 #[derive(RustcEncodable, RustcDecodable)]
334 struct VariantData {
335     ctor_kind: CtorKind,
336     discr: ty::VariantDiscr,
337     /// If this is unit or tuple-variant/struct, then this is the index of the ctor id.
338     ctor: Option<DefIndex>,
339 }
340
341 #[derive(RustcEncodable, RustcDecodable)]
342 struct TraitData {
343     unsafety: hir::Unsafety,
344     paren_sugar: bool,
345     has_auto_impl: bool,
346     is_marker: bool,
347     specialization_kind: ty::trait_def::TraitSpecializationKind,
348 }
349
350 #[derive(RustcEncodable, RustcDecodable)]
351 struct ImplData {
352     polarity: ty::ImplPolarity,
353     defaultness: hir::Defaultness,
354     parent_impl: Option<DefId>,
355
356     /// This is `Some` only for impls of `CoerceUnsized`.
357     // FIXME(eddyb) perhaps compute this on the fly if cheap enough?
358     coerce_unsized_info: Option<ty::adjustment::CoerceUnsizedInfo>,
359 }
360
361 /// Describes whether the container of an associated item
362 /// is a trait or an impl and whether, in a trait, it has
363 /// a default, or an in impl, whether it's marked "default".
364 #[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
365 enum AssocContainer {
366     TraitRequired,
367     TraitWithDefault,
368     ImplDefault,
369     ImplFinal,
370 }
371
372 impl AssocContainer {
373     fn with_def_id(&self, def_id: DefId) -> ty::AssocItemContainer {
374         match *self {
375             AssocContainer::TraitRequired | AssocContainer::TraitWithDefault => {
376                 ty::TraitContainer(def_id)
377             }
378
379             AssocContainer::ImplDefault | AssocContainer::ImplFinal => ty::ImplContainer(def_id),
380         }
381     }
382
383     fn defaultness(&self) -> hir::Defaultness {
384         match *self {
385             AssocContainer::TraitRequired => hir::Defaultness::Default { has_value: false },
386
387             AssocContainer::TraitWithDefault | AssocContainer::ImplDefault => {
388                 hir::Defaultness::Default { has_value: true }
389             }
390
391             AssocContainer::ImplFinal => hir::Defaultness::Final,
392         }
393     }
394 }
395
396 #[derive(RustcEncodable, RustcDecodable)]
397 struct AssocFnData {
398     fn_data: FnData,
399     container: AssocContainer,
400     has_self: bool,
401 }
402
403 #[derive(RustcEncodable, RustcDecodable)]
404 struct GeneratorData<'tcx> {
405     layout: mir::GeneratorLayout<'tcx>,
406 }
407
408 // Tags used for encoding Spans:
409 const TAG_VALID_SPAN_LOCAL: u8 = 0;
410 const TAG_VALID_SPAN_FOREIGN: u8 = 1;
411 const TAG_INVALID_SPAN: u8 = 2;