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