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