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