]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_metadata/src/rmeta/mod.rs
Rollup merge of #107706 - tgross35:atomic-as-mut-ptr, r=m-ou-se
[rust.git] / compiler / rustc_metadata / src / rmeta / mod.rs
1 use crate::creader::CrateMetadataRef;
2 use decoder::Metadata;
3 use def_path_hash_map::DefPathHashMapRef;
4 use rustc_data_structures::fx::FxHashMap;
5 use table::TableBuilder;
6
7 use rustc_ast as ast;
8 use rustc_attr as attr;
9 use rustc_data_structures::svh::Svh;
10 use rustc_data_structures::sync::MetadataRef;
11 use rustc_hir as hir;
12 use rustc_hir::def::{CtorKind, DefKind};
13 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, DefPathHash, StableCrateId};
14 use rustc_hir::definitions::DefKey;
15 use rustc_hir::lang_items::LangItem;
16 use rustc_index::bit_set::BitSet;
17 use rustc_index::vec::IndexVec;
18 use rustc_middle::metadata::ModChild;
19 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
20 use rustc_middle::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo};
21 use rustc_middle::middle::resolve_lifetime::ObjectLifetimeDefault;
22 use rustc_middle::mir;
23 use rustc_middle::ty::fast_reject::SimplifiedType;
24 use rustc_middle::ty::query::Providers;
25 use rustc_middle::ty::{self, ReprOptions, Ty, UnusedGenericParams};
26 use rustc_middle::ty::{DeducedParamAttrs, GeneratorDiagnosticData, ParameterizedOverTcx, TyCtxt};
27 use rustc_serialize::opaque::FileEncoder;
28 use rustc_session::config::SymbolManglingVersion;
29 use rustc_session::cstore::{CrateDepKind, ForeignModule, LinkagePreference, NativeLib};
30 use rustc_span::edition::Edition;
31 use rustc_span::hygiene::{ExpnIndex, MacroKind};
32 use rustc_span::symbol::{Ident, Symbol};
33 use rustc_span::{self, ExpnData, ExpnHash, ExpnId, Span};
34 use rustc_target::spec::{PanicStrategy, TargetTriple};
35
36 use std::marker::PhantomData;
37 use std::num::NonZeroUsize;
38
39 pub use decoder::provide_extern;
40 use decoder::DecodeContext;
41 pub(crate) use decoder::{CrateMetadata, CrateNumMap, MetadataBlob};
42 use encoder::EncodeContext;
43 pub use encoder::{encode_metadata, EncodedMetadata};
44 use rustc_span::hygiene::SyntaxContextData;
45
46 mod decoder;
47 mod def_path_hash_map;
48 mod encoder;
49 mod table;
50
51 pub(crate) fn rustc_version() -> String {
52     format!("rustc {}", option_env!("CFG_VERSION").unwrap_or("unknown version"))
53 }
54
55 /// Metadata encoding version.
56 /// N.B., increment this if you change the format of metadata such that
57 /// the rustc version can't be found to compare with `rustc_version()`.
58 const METADATA_VERSION: u8 = 6;
59
60 /// Metadata header which includes `METADATA_VERSION`.
61 ///
62 /// This header is followed by the position of the `CrateRoot`,
63 /// which is encoded as a 32-bit big-endian unsigned integer,
64 /// and further followed by the rustc version string.
65 pub const METADATA_HEADER: &[u8] = &[b'r', b'u', b's', b't', 0, 0, 0, METADATA_VERSION];
66
67 /// A value of type T referred to by its absolute position
68 /// in the metadata, and which can be decoded lazily.
69 ///
70 /// Metadata is effective a tree, encoded in post-order,
71 /// and with the root's position written next to the header.
72 /// That means every single `LazyValue` points to some previous
73 /// location in the metadata and is part of a larger node.
74 ///
75 /// The first `LazyValue` in a node is encoded as the backwards
76 /// distance from the position where the containing node
77 /// starts and where the `LazyValue` points to, while the rest
78 /// use the forward distance from the previous `LazyValue`.
79 /// Distances start at 1, as 0-byte nodes are invalid.
80 /// Also invalid are nodes being referred in a different
81 /// order than they were encoded in.
82 #[must_use]
83 struct LazyValue<T> {
84     position: NonZeroUsize,
85     _marker: PhantomData<fn() -> T>,
86 }
87
88 impl<T: ParameterizedOverTcx> ParameterizedOverTcx for LazyValue<T> {
89     type Value<'tcx> = LazyValue<T::Value<'tcx>>;
90 }
91
92 impl<T> LazyValue<T> {
93     fn from_position(position: NonZeroUsize) -> LazyValue<T> {
94         LazyValue { position, _marker: PhantomData }
95     }
96 }
97
98 /// A list of lazily-decoded values.
99 ///
100 /// Unlike `LazyValue<Vec<T>>`, the length is encoded next to the
101 /// position, not at the position, which means that the length
102 /// doesn't need to be known before encoding all the elements.
103 ///
104 /// If the length is 0, no position is encoded, but otherwise,
105 /// the encoding is that of `LazyArray`, with the distinction that
106 /// the minimal distance the length of the sequence, i.e.
107 /// it's assumed there's no 0-byte element in the sequence.
108 struct LazyArray<T> {
109     position: NonZeroUsize,
110     num_elems: usize,
111     _marker: PhantomData<fn() -> T>,
112 }
113
114 impl<T: ParameterizedOverTcx> ParameterizedOverTcx for LazyArray<T> {
115     type Value<'tcx> = LazyArray<T::Value<'tcx>>;
116 }
117
118 impl<T> Default for LazyArray<T> {
119     fn default() -> LazyArray<T> {
120         LazyArray::from_position_and_num_elems(NonZeroUsize::new(1).unwrap(), 0)
121     }
122 }
123
124 impl<T> LazyArray<T> {
125     fn from_position_and_num_elems(position: NonZeroUsize, num_elems: usize) -> LazyArray<T> {
126         LazyArray { position, num_elems, _marker: PhantomData }
127     }
128 }
129
130 /// A list of lazily-decoded values, with the added capability of random access.
131 ///
132 /// Random-access table (i.e. offering constant-time `get`/`set`), similar to
133 /// `LazyArray<T>`, but without requiring encoding or decoding all the values
134 /// eagerly and in-order.
135 struct LazyTable<I, T> {
136     position: NonZeroUsize,
137     encoded_size: usize,
138     _marker: PhantomData<fn(I) -> T>,
139 }
140
141 impl<I: 'static, T: ParameterizedOverTcx> ParameterizedOverTcx for LazyTable<I, T> {
142     type Value<'tcx> = LazyTable<I, T::Value<'tcx>>;
143 }
144
145 impl<I, T> LazyTable<I, T> {
146     fn from_position_and_encoded_size(
147         position: NonZeroUsize,
148         encoded_size: usize,
149     ) -> LazyTable<I, T> {
150         LazyTable { position, encoded_size, _marker: PhantomData }
151     }
152 }
153
154 impl<T> Copy for LazyValue<T> {}
155 impl<T> Clone for LazyValue<T> {
156     fn clone(&self) -> Self {
157         *self
158     }
159 }
160
161 impl<T> Copy for LazyArray<T> {}
162 impl<T> Clone for LazyArray<T> {
163     fn clone(&self) -> Self {
164         *self
165     }
166 }
167
168 impl<I, T> Copy for LazyTable<I, T> {}
169 impl<I, T> Clone for LazyTable<I, T> {
170     fn clone(&self) -> Self {
171         *self
172     }
173 }
174
175 /// Encoding / decoding state for `Lazy`s (`LazyValue`, `LazyArray`, and `LazyTable`).
176 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
177 enum LazyState {
178     /// Outside of a metadata node.
179     NoNode,
180
181     /// Inside a metadata node, and before any `Lazy`s.
182     /// The position is that of the node itself.
183     NodeStart(NonZeroUsize),
184
185     /// Inside a metadata node, with a previous `Lazy`s.
186     /// The position is where that previous `Lazy` would start.
187     Previous(NonZeroUsize),
188 }
189
190 type SyntaxContextTable = LazyTable<u32, Option<LazyValue<SyntaxContextData>>>;
191 type ExpnDataTable = LazyTable<ExpnIndex, Option<LazyValue<ExpnData>>>;
192 type ExpnHashTable = LazyTable<ExpnIndex, Option<LazyValue<ExpnHash>>>;
193
194 #[derive(MetadataEncodable, MetadataDecodable)]
195 pub(crate) struct ProcMacroData {
196     proc_macro_decls_static: DefIndex,
197     stability: Option<attr::Stability>,
198     macros: LazyArray<DefIndex>,
199 }
200
201 /// Serialized metadata for a crate.
202 /// When compiling a proc-macro crate, we encode many of
203 /// the `LazyArray<T>` fields as `Lazy::empty()`. This serves two purposes:
204 ///
205 /// 1. We avoid performing unnecessary work. Proc-macro crates can only
206 /// export proc-macros functions, which are compiled into a shared library.
207 /// As a result, a large amount of the information we normally store
208 /// (e.g. optimized MIR) is unneeded by downstream crates.
209 /// 2. We avoid serializing invalid `CrateNum`s. When we deserialize
210 /// a proc-macro crate, we don't load any of its dependencies (since we
211 /// just need to invoke a native function from the shared library).
212 /// This means that any foreign `CrateNum`s that we serialize cannot be
213 /// deserialized, since we will not know how to map them into the current
214 /// compilation session. If we were to serialize a proc-macro crate like
215 /// a normal crate, much of what we serialized would be unusable in addition
216 /// to being unused.
217 #[derive(MetadataEncodable, MetadataDecodable)]
218 pub(crate) struct CrateRoot {
219     name: Symbol,
220     triple: TargetTriple,
221     extra_filename: String,
222     hash: Svh,
223     stable_crate_id: StableCrateId,
224     required_panic_strategy: Option<PanicStrategy>,
225     panic_in_drop_strategy: PanicStrategy,
226     edition: Edition,
227     has_global_allocator: bool,
228     has_alloc_error_handler: bool,
229     has_panic_handler: bool,
230     has_default_lib_allocator: bool,
231
232     crate_deps: LazyArray<CrateDep>,
233     dylib_dependency_formats: LazyArray<Option<LinkagePreference>>,
234     lib_features: LazyArray<(Symbol, Option<Symbol>)>,
235     stability_implications: LazyArray<(Symbol, Symbol)>,
236     lang_items: LazyArray<(DefIndex, LangItem)>,
237     lang_items_missing: LazyArray<LangItem>,
238     diagnostic_items: LazyArray<(Symbol, DefIndex)>,
239     native_libraries: LazyArray<NativeLib>,
240     foreign_modules: LazyArray<ForeignModule>,
241     traits: LazyArray<DefIndex>,
242     impls: LazyArray<TraitImpls>,
243     incoherent_impls: LazyArray<IncoherentImpls>,
244     interpret_alloc_index: LazyArray<u32>,
245     proc_macro_data: Option<ProcMacroData>,
246
247     tables: LazyTables,
248     debugger_visualizers: LazyArray<rustc_span::DebuggerVisualizerFile>,
249
250     exported_symbols: LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)>,
251
252     syntax_contexts: SyntaxContextTable,
253     expn_data: ExpnDataTable,
254     expn_hashes: ExpnHashTable,
255
256     def_path_hash_map: LazyValue<DefPathHashMapRef<'static>>,
257
258     source_map: LazyTable<u32, Option<LazyValue<rustc_span::SourceFile>>>,
259
260     compiler_builtins: bool,
261     needs_allocator: bool,
262     needs_panic_runtime: bool,
263     no_builtins: bool,
264     panic_runtime: bool,
265     profiler_runtime: bool,
266     symbol_mangling_version: SymbolManglingVersion,
267 }
268
269 /// On-disk representation of `DefId`.
270 /// This creates a type-safe way to enforce that we remap the CrateNum between the on-disk
271 /// representation and the compilation session.
272 #[derive(Copy, Clone)]
273 pub(crate) struct RawDefId {
274     krate: u32,
275     index: u32,
276 }
277
278 impl Into<RawDefId> for DefId {
279     fn into(self) -> RawDefId {
280         RawDefId { krate: self.krate.as_u32(), index: self.index.as_u32() }
281     }
282 }
283
284 impl RawDefId {
285     /// This exists so that `provide_one!` is happy
286     fn decode(self, meta: (CrateMetadataRef<'_>, TyCtxt<'_>)) -> DefId {
287         self.decode_from_cdata(meta.0)
288     }
289
290     fn decode_from_cdata(self, cdata: CrateMetadataRef<'_>) -> DefId {
291         let krate = CrateNum::from_u32(self.krate);
292         let krate = cdata.map_encoded_cnum_to_current(krate);
293         DefId { krate, index: DefIndex::from_u32(self.index) }
294     }
295 }
296
297 #[derive(Encodable, Decodable)]
298 pub(crate) struct CrateDep {
299     pub name: Symbol,
300     pub hash: Svh,
301     pub host_hash: Option<Svh>,
302     pub kind: CrateDepKind,
303     pub extra_filename: String,
304 }
305
306 #[derive(MetadataEncodable, MetadataDecodable)]
307 pub(crate) struct TraitImpls {
308     trait_id: (u32, DefIndex),
309     impls: LazyArray<(DefIndex, Option<SimplifiedType>)>,
310 }
311
312 #[derive(MetadataEncodable, MetadataDecodable)]
313 pub(crate) struct IncoherentImpls {
314     self_ty: SimplifiedType,
315     impls: LazyArray<DefIndex>,
316 }
317
318 /// Define `LazyTables` and `TableBuilders` at the same time.
319 macro_rules! define_tables {
320     (
321         - defaulted: $($name1:ident: Table<$IDX1:ty, $T1:ty>,)+
322         - optional: $($name2:ident: Table<$IDX2:ty, $T2:ty>,)+
323     ) => {
324         #[derive(MetadataEncodable, MetadataDecodable)]
325         pub(crate) struct LazyTables {
326             $($name1: LazyTable<$IDX1, $T1>,)+
327             $($name2: LazyTable<$IDX2, Option<$T2>>,)+
328         }
329
330         #[derive(Default)]
331         struct TableBuilders {
332             $($name1: TableBuilder<$IDX1, $T1>,)+
333             $($name2: TableBuilder<$IDX2, Option<$T2>>,)+
334         }
335
336         impl TableBuilders {
337             fn encode(&self, buf: &mut FileEncoder) -> LazyTables {
338                 LazyTables {
339                     $($name1: self.$name1.encode(buf),)+
340                     $($name2: self.$name2.encode(buf),)+
341                 }
342             }
343         }
344     }
345 }
346
347 define_tables! {
348 - defaulted:
349     is_intrinsic: Table<DefIndex, bool>,
350     is_macro_rules: Table<DefIndex, bool>,
351     is_type_alias_impl_trait: Table<DefIndex, bool>,
352     attr_flags: Table<DefIndex, AttrFlags>,
353     def_path_hashes: Table<DefIndex, DefPathHash>,
354     explicit_item_bounds: Table<DefIndex, LazyArray<(ty::Predicate<'static>, Span)>>,
355     inferred_outlives_of: Table<DefIndex, LazyArray<(ty::Clause<'static>, Span)>>,
356     inherent_impls: Table<DefIndex, LazyArray<DefIndex>>,
357
358 - optional:
359     attributes: Table<DefIndex, LazyArray<ast::Attribute>>,
360     children: Table<DefIndex, LazyArray<DefIndex>>,
361     opt_def_kind: Table<DefIndex, DefKind>,
362     visibility: Table<DefIndex, LazyValue<ty::Visibility<DefIndex>>>,
363     def_span: Table<DefIndex, LazyValue<Span>>,
364     def_ident_span: Table<DefIndex, LazyValue<Span>>,
365     lookup_stability: Table<DefIndex, LazyValue<attr::Stability>>,
366     lookup_const_stability: Table<DefIndex, LazyValue<attr::ConstStability>>,
367     lookup_default_body_stability: Table<DefIndex, LazyValue<attr::DefaultBodyStability>>,
368     lookup_deprecation_entry: Table<DefIndex, LazyValue<attr::Deprecation>>,
369     explicit_predicates_of: Table<DefIndex, LazyValue<ty::GenericPredicates<'static>>>,
370     generics_of: Table<DefIndex, LazyValue<ty::Generics>>,
371     super_predicates_of: Table<DefIndex, LazyValue<ty::GenericPredicates<'static>>>,
372     type_of: Table<DefIndex, LazyValue<Ty<'static>>>,
373     variances_of: Table<DefIndex, LazyArray<ty::Variance>>,
374     fn_sig: Table<DefIndex, LazyValue<ty::EarlyBinder<ty::PolyFnSig<'static>>>>,
375     codegen_fn_attrs: Table<DefIndex, LazyValue<CodegenFnAttrs>>,
376     impl_trait_ref: Table<DefIndex, LazyValue<ty::EarlyBinder<ty::TraitRef<'static>>>>,
377     const_param_default: Table<DefIndex, LazyValue<ty::EarlyBinder<rustc_middle::ty::Const<'static>>>>,
378     object_lifetime_default: Table<DefIndex, LazyValue<ObjectLifetimeDefault>>,
379     optimized_mir: Table<DefIndex, LazyValue<mir::Body<'static>>>,
380     mir_for_ctfe: Table<DefIndex, LazyValue<mir::Body<'static>>>,
381     mir_generator_witnesses: Table<DefIndex, LazyValue<mir::GeneratorLayout<'static>>>,
382     promoted_mir: Table<DefIndex, LazyValue<IndexVec<mir::Promoted, mir::Body<'static>>>>,
383     // FIXME(compiler-errors): Why isn't this a LazyArray?
384     thir_abstract_const: Table<DefIndex, LazyValue<ty::Const<'static>>>,
385     impl_parent: Table<DefIndex, RawDefId>,
386     impl_polarity: Table<DefIndex, ty::ImplPolarity>,
387     constness: Table<DefIndex, hir::Constness>,
388     impl_defaultness: Table<DefIndex, hir::Defaultness>,
389     // FIXME(eddyb) perhaps compute this on the fly if cheap enough?
390     coerce_unsized_info: Table<DefIndex, LazyValue<ty::adjustment::CoerceUnsizedInfo>>,
391     mir_const_qualif: Table<DefIndex, LazyValue<mir::ConstQualifs>>,
392     rendered_const: Table<DefIndex, LazyValue<String>>,
393     asyncness: Table<DefIndex, hir::IsAsync>,
394     fn_arg_names: Table<DefIndex, LazyArray<Ident>>,
395     generator_kind: Table<DefIndex, LazyValue<hir::GeneratorKind>>,
396     trait_def: Table<DefIndex, LazyValue<ty::TraitDef>>,
397     trait_item_def_id: Table<DefIndex, RawDefId>,
398     expn_that_defined: Table<DefIndex, LazyValue<ExpnId>>,
399     unused_generic_params: Table<DefIndex, LazyValue<UnusedGenericParams>>,
400     params_in_repr: Table<DefIndex, LazyValue<BitSet<u32>>>,
401     repr_options: Table<DefIndex, LazyValue<ReprOptions>>,
402     // `def_keys` and `def_path_hashes` represent a lazy version of a
403     // `DefPathTable`. This allows us to avoid deserializing an entire
404     // `DefPathTable` up front, since we may only ever use a few
405     // definitions from any given crate.
406     def_keys: Table<DefIndex, LazyValue<DefKey>>,
407     proc_macro_quoted_spans: Table<usize, LazyValue<Span>>,
408     generator_diagnostic_data: Table<DefIndex, LazyValue<GeneratorDiagnosticData<'static>>>,
409     variant_data: Table<DefIndex, LazyValue<VariantData>>,
410     assoc_container: Table<DefIndex, ty::AssocItemContainer>,
411     macro_definition: Table<DefIndex, LazyValue<ast::DelimArgs>>,
412     proc_macro: Table<DefIndex, MacroKind>,
413     module_reexports: Table<DefIndex, LazyArray<ModChild>>,
414     deduced_param_attrs: Table<DefIndex, LazyArray<DeducedParamAttrs>>,
415     trait_impl_trait_tys: Table<DefIndex, LazyValue<FxHashMap<DefId, Ty<'static>>>>,
416 }
417
418 #[derive(TyEncodable, TyDecodable)]
419 struct VariantData {
420     discr: ty::VariantDiscr,
421     /// If this is unit or tuple-variant/struct, then this is the index of the ctor id.
422     ctor: Option<(CtorKind, DefIndex)>,
423     is_non_exhaustive: bool,
424 }
425
426 bitflags::bitflags! {
427     #[derive(Default)]
428     pub struct AttrFlags: u8 {
429         const MAY_HAVE_DOC_LINKS = 1 << 0;
430         const IS_DOC_HIDDEN      = 1 << 1;
431     }
432 }
433
434 // Tags used for encoding Spans:
435 const TAG_VALID_SPAN_LOCAL: u8 = 0;
436 const TAG_VALID_SPAN_FOREIGN: u8 = 1;
437 const TAG_PARTIAL_SPAN: u8 = 2;
438
439 // Tags for encoding Symbol's
440 const SYMBOL_STR: u8 = 0;
441 const SYMBOL_OFFSET: u8 = 1;
442 const SYMBOL_PREINTERNED: u8 = 2;
443
444 pub fn provide(providers: &mut Providers) {
445     encoder::provide(providers);
446     decoder::provide(providers);
447 }
448
449 trivially_parameterized_over_tcx! {
450     VariantData,
451     RawDefId,
452     TraitImpls,
453     IncoherentImpls,
454     CrateRoot,
455     CrateDep,
456     AttrFlags,
457 }