]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_metadata/src/rmeta/mod.rs
Rollup merge of #88709 - BoxyUwU:thir-abstract-const, r=lcnr
[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, StableCrateId};
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::thir;
19 use rustc_middle::ty::{self, ReprOptions, Ty};
20 use rustc_serialize::opaque::Encoder;
21 use rustc_session::config::SymbolManglingVersion;
22 use rustc_span::edition::Edition;
23 use rustc_span::hygiene::{ExpnIndex, MacroKind};
24 use rustc_span::symbol::{Ident, Symbol};
25 use rustc_span::{self, ExpnData, ExpnHash, 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 pub const METADATA_HEADER: &[u8] = &[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<ExpnIndex, Lazy<ExpnData>>>;
175 type ExpnHashTable = Lazy<Table<ExpnIndex, Lazy<ExpnHash>>>;
176
177 #[derive(MetadataEncodable, MetadataDecodable)]
178 crate struct ProcMacroData {
179     proc_macro_decls_static: DefIndex,
180     stability: Option<attr::Stability>,
181     macros: Lazy<[DefIndex]>,
182 }
183
184 /// Serialized metadata for a crate.
185 /// When compiling a proc-macro crate, we encode many of
186 /// the `Lazy<[T]>` fields as `Lazy::empty()`. This serves two purposes:
187 ///
188 /// 1. We avoid performing unnecessary work. Proc-macro crates can only
189 /// export proc-macros functions, which are compiled into a shared library.
190 /// As a result, a large amount of the information we normally store
191 /// (e.g. optimized MIR) is unneeded by downstream crates.
192 /// 2. We avoid serializing invalid `CrateNum`s. When we deserialize
193 /// a proc-macro crate, we don't load any of its dependencies (since we
194 /// just need to invoke a native function from the shared library).
195 /// This means that any foreign `CrateNum`s that we serialize cannot be
196 /// deserialized, since we will not know how to map them into the current
197 /// compilation session. If we were to serialize a proc-macro crate like
198 /// a normal crate, much of what we serialized would be unusable in addition
199 /// to being unused.
200 #[derive(MetadataEncodable, MetadataDecodable)]
201 crate struct CrateRoot<'tcx> {
202     name: Symbol,
203     triple: TargetTriple,
204     extra_filename: String,
205     hash: Svh,
206     stable_crate_id: StableCrateId,
207     panic_strategy: PanicStrategy,
208     edition: Edition,
209     has_global_allocator: bool,
210     has_panic_handler: bool,
211     has_default_lib_allocator: bool,
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     expn_hashes: ExpnHashTable,
232
233     source_map: Lazy<[rustc_span::SourceFile]>,
234
235     compiler_builtins: bool,
236     needs_allocator: bool,
237     needs_panic_runtime: bool,
238     no_builtins: bool,
239     panic_runtime: bool,
240     profiler_runtime: bool,
241     symbol_mangling_version: SymbolManglingVersion,
242 }
243
244 #[derive(Encodable, Decodable)]
245 crate struct CrateDep {
246     pub name: Symbol,
247     pub hash: Svh,
248     pub host_hash: Option<Svh>,
249     pub kind: CrateDepKind,
250     pub extra_filename: String,
251 }
252
253 #[derive(MetadataEncodable, MetadataDecodable)]
254 crate struct TraitImpls {
255     trait_id: (u32, DefIndex),
256     impls: Lazy<[(DefIndex, Option<ty::fast_reject::SimplifiedType>)]>,
257 }
258
259 /// Define `LazyTables` and `TableBuilders` at the same time.
260 macro_rules! define_tables {
261     ($($name:ident: Table<$IDX:ty, $T:ty>),+ $(,)?) => {
262         #[derive(MetadataEncodable, MetadataDecodable)]
263         crate struct LazyTables<'tcx> {
264             $($name: Lazy!(Table<$IDX, $T>)),+
265         }
266
267         #[derive(Default)]
268         struct TableBuilders<'tcx> {
269             $($name: TableBuilder<$IDX, $T>),+
270         }
271
272         impl TableBuilders<'tcx> {
273             fn encode(&self, buf: &mut Encoder) -> LazyTables<'tcx> {
274                 LazyTables {
275                     $($name: self.$name.encode(buf)),+
276                 }
277             }
278         }
279     }
280 }
281
282 define_tables! {
283     def_kind: Table<DefIndex, Lazy<DefKind>>,
284     kind: Table<DefIndex, Lazy<EntryKind>>,
285     visibility: Table<DefIndex, Lazy<ty::Visibility>>,
286     span: Table<DefIndex, Lazy<Span>>,
287     ident_span: Table<DefIndex, Lazy<Span>>,
288     attributes: Table<DefIndex, Lazy<[ast::Attribute]>>,
289     children: Table<DefIndex, Lazy<[DefIndex]>>,
290     stability: Table<DefIndex, Lazy<attr::Stability>>,
291     const_stability: Table<DefIndex, Lazy<attr::ConstStability>>,
292     deprecation: Table<DefIndex, Lazy<attr::Deprecation>>,
293     ty: Table<DefIndex, Lazy!(Ty<'tcx>)>,
294     fn_sig: Table<DefIndex, Lazy!(ty::PolyFnSig<'tcx>)>,
295     impl_trait_ref: Table<DefIndex, Lazy!(ty::TraitRef<'tcx>)>,
296     inherent_impls: Table<DefIndex, Lazy<[DefIndex]>>,
297     variances: Table<DefIndex, Lazy<[ty::Variance]>>,
298     generics: Table<DefIndex, Lazy<ty::Generics>>,
299     explicit_predicates: Table<DefIndex, Lazy!(ty::GenericPredicates<'tcx>)>,
300     expn_that_defined: Table<DefIndex, Lazy<ExpnId>>,
301     // As an optimization, a missing entry indicates an empty `&[]`.
302     inferred_outlives: Table<DefIndex, Lazy!([(ty::Predicate<'tcx>, Span)])>,
303     super_predicates: Table<DefIndex, Lazy!(ty::GenericPredicates<'tcx>)>,
304     // As an optimization, a missing entry indicates an empty `&[]`.
305     explicit_item_bounds: Table<DefIndex, Lazy!([(ty::Predicate<'tcx>, Span)])>,
306     mir: Table<DefIndex, Lazy!(mir::Body<'tcx>)>,
307     mir_for_ctfe: Table<DefIndex, Lazy!(mir::Body<'tcx>)>,
308     promoted_mir: Table<DefIndex, Lazy!(IndexVec<mir::Promoted, mir::Body<'tcx>>)>,
309     thir_abstract_consts: Table<DefIndex, Lazy!(&'tcx [thir::abstract_const::Node<'tcx>])>,
310     const_defaults: Table<DefIndex, Lazy<rustc_middle::ty::Const<'tcx>>>,
311     unused_generic_params: Table<DefIndex, Lazy<FiniteBitSet<u32>>>,
312     // `def_keys` and `def_path_hashes` represent a lazy version of a
313     // `DefPathTable`. This allows us to avoid deserializing an entire
314     // `DefPathTable` up front, since we may only ever use a few
315     // definitions from any given crate.
316     def_keys: Table<DefIndex, Lazy<DefKey>>,
317     def_path_hashes: Table<DefIndex, Lazy<DefPathHash>>,
318     proc_macro_quoted_spans: Table<usize, Lazy<Span>>,
319 }
320
321 #[derive(Copy, Clone, MetadataEncodable, MetadataDecodable)]
322 enum EntryKind {
323     AnonConst(mir::ConstQualifs, Lazy<RenderedConst>),
324     Const(mir::ConstQualifs, Lazy<RenderedConst>),
325     ImmStatic,
326     MutStatic,
327     ForeignImmStatic,
328     ForeignMutStatic,
329     ForeignMod,
330     ForeignType,
331     GlobalAsm,
332     Type,
333     TypeParam,
334     ConstParam,
335     OpaqueTy,
336     Enum(ReprOptions),
337     Field,
338     Variant(Lazy<VariantData>),
339     Struct(Lazy<VariantData>, ReprOptions),
340     Union(Lazy<VariantData>, ReprOptions),
341     Fn(Lazy<FnData>),
342     ForeignFn(Lazy<FnData>),
343     Mod(Lazy<ModData>),
344     MacroDef(Lazy<MacroDef>),
345     ProcMacro(MacroKind),
346     Closure,
347     Generator(hir::GeneratorKind),
348     Trait(Lazy<TraitData>),
349     Impl(Lazy<ImplData>),
350     AssocFn(Lazy<AssocFnData>),
351     AssocType(AssocContainer),
352     AssocConst(AssocContainer, mir::ConstQualifs, Lazy<RenderedConst>),
353     TraitAlias,
354 }
355
356 /// Contains a constant which has been rendered to a String.
357 /// Used by rustdoc.
358 #[derive(Encodable, Decodable)]
359 struct RenderedConst(String);
360
361 #[derive(MetadataEncodable, MetadataDecodable)]
362 struct ModData {
363     reexports: Lazy<[Export]>,
364     expansion: ExpnId,
365 }
366
367 #[derive(MetadataEncodable, MetadataDecodable)]
368 struct FnData {
369     asyncness: hir::IsAsync,
370     constness: hir::Constness,
371     param_names: Lazy<[Ident]>,
372 }
373
374 #[derive(TyEncodable, TyDecodable)]
375 struct VariantData {
376     ctor_kind: CtorKind,
377     discr: ty::VariantDiscr,
378     /// If this is unit or tuple-variant/struct, then this is the index of the ctor id.
379     ctor: Option<DefIndex>,
380     is_non_exhaustive: bool,
381 }
382
383 #[derive(TyEncodable, TyDecodable)]
384 struct TraitData {
385     unsafety: hir::Unsafety,
386     paren_sugar: bool,
387     has_auto_impl: bool,
388     is_marker: bool,
389     skip_array_during_method_dispatch: bool,
390     specialization_kind: ty::trait_def::TraitSpecializationKind,
391 }
392
393 #[derive(TyEncodable, TyDecodable)]
394 struct ImplData {
395     polarity: ty::ImplPolarity,
396     constness: hir::Constness,
397     defaultness: hir::Defaultness,
398     parent_impl: Option<DefId>,
399
400     /// This is `Some` only for impls of `CoerceUnsized`.
401     // FIXME(eddyb) perhaps compute this on the fly if cheap enough?
402     coerce_unsized_info: Option<ty::adjustment::CoerceUnsizedInfo>,
403 }
404
405 /// Describes whether the container of an associated item
406 /// is a trait or an impl and whether, in a trait, it has
407 /// a default, or an in impl, whether it's marked "default".
408 #[derive(Copy, Clone, TyEncodable, TyDecodable)]
409 enum AssocContainer {
410     TraitRequired,
411     TraitWithDefault,
412     ImplDefault,
413     ImplFinal,
414 }
415
416 impl AssocContainer {
417     fn with_def_id(&self, def_id: DefId) -> ty::AssocItemContainer {
418         match *self {
419             AssocContainer::TraitRequired | AssocContainer::TraitWithDefault => {
420                 ty::TraitContainer(def_id)
421             }
422
423             AssocContainer::ImplDefault | AssocContainer::ImplFinal => ty::ImplContainer(def_id),
424         }
425     }
426
427     fn defaultness(&self) -> hir::Defaultness {
428         match *self {
429             AssocContainer::TraitRequired => hir::Defaultness::Default { has_value: false },
430
431             AssocContainer::TraitWithDefault | AssocContainer::ImplDefault => {
432                 hir::Defaultness::Default { has_value: true }
433             }
434
435             AssocContainer::ImplFinal => hir::Defaultness::Final,
436         }
437     }
438 }
439
440 #[derive(MetadataEncodable, MetadataDecodable)]
441 struct AssocFnData {
442     fn_data: FnData,
443     container: AssocContainer,
444     has_self: bool,
445 }
446
447 #[derive(TyEncodable, TyDecodable)]
448 struct GeneratorData<'tcx> {
449     layout: mir::GeneratorLayout<'tcx>,
450 }
451
452 // Tags used for encoding Spans:
453 const TAG_VALID_SPAN_LOCAL: u8 = 0;
454 const TAG_VALID_SPAN_FOREIGN: u8 = 1;
455 const TAG_PARTIAL_SPAN: u8 = 2;