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