]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_metadata/src/rmeta/mod.rs
New upstream version 1.68.2+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;
487cf647 15use rustc_hir::lang_items::LangItem;
f25598a0 16use rustc_index::bit_set::BitSet;
2b03887a 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;
f25598a0 25use rustc_middle::ty::{self, ReprOptions, Ty, UnusedGenericParams};
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,
487cf647 226 has_alloc_error_handler: bool,
60c5eb7d
XL
227 has_panic_handler: bool,
228 has_default_lib_allocator: bool,
60c5eb7d 229
923072b8
FG
230 crate_deps: LazyArray<CrateDep>,
231 dylib_dependency_formats: LazyArray<Option<LinkagePreference>>,
232 lib_features: LazyArray<(Symbol, Option<Symbol>)>,
064997fb 233 stability_implications: LazyArray<(Symbol, Symbol)>,
487cf647
FG
234 lang_items: LazyArray<(DefIndex, LangItem)>,
235 lang_items_missing: LazyArray<LangItem>,
923072b8
FG
236 diagnostic_items: LazyArray<(Symbol, DefIndex)>,
237 native_libraries: LazyArray<NativeLib>,
238 foreign_modules: LazyArray<ForeignModule>,
239 traits: LazyArray<DefIndex>,
240 impls: LazyArray<TraitImpls>,
241 incoherent_impls: LazyArray<IncoherentImpls>,
242 interpret_alloc_index: LazyArray<u32>,
1b1a35ee 243 proc_macro_data: Option<ProcMacroData>,
60c5eb7d 244
923072b8
FG
245 tables: LazyTables,
246 debugger_visualizers: LazyArray<rustc_span::DebuggerVisualizerFile>,
60c5eb7d 247
923072b8 248 exported_symbols: LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)>,
3dfed10e
XL
249
250 syntax_contexts: SyntaxContextTable,
251 expn_data: ExpnDataTable,
136023e0 252 expn_hashes: ExpnHashTable,
3dfed10e 253
923072b8 254 def_path_hash_map: LazyValue<DefPathHashMapRef<'static>>,
c295e0f8 255
f2b60f7d 256 source_map: LazyTable<u32, LazyValue<rustc_span::SourceFile>>,
ba9703b0 257
60c5eb7d
XL
258 compiler_builtins: bool,
259 needs_allocator: bool,
260 needs_panic_runtime: bool,
261 no_builtins: bool,
262 panic_runtime: bool,
263 profiler_runtime: bool,
60c5eb7d 264 symbol_mangling_version: SymbolManglingVersion,
9e0c209e
SL
265}
266
04454e1e
FG
267/// On-disk representation of `DefId`.
268/// This creates a type-safe way to enforce that we remap the CrateNum between the on-disk
269/// representation and the compilation session.
270#[derive(Copy, Clone)]
923072b8 271pub(crate) struct RawDefId {
04454e1e
FG
272 krate: u32,
273 index: u32,
274}
275
276impl Into<RawDefId> for DefId {
277 fn into(self) -> RawDefId {
278 RawDefId { krate: self.krate.as_u32(), index: self.index.as_u32() }
279 }
280}
281
282impl RawDefId {
923072b8
FG
283 /// This exists so that `provide_one!` is happy
284 fn decode(self, meta: (CrateMetadataRef<'_>, TyCtxt<'_>)) -> DefId {
285 self.decode_from_cdata(meta.0)
286 }
287
288 fn decode_from_cdata(self, cdata: CrateMetadataRef<'_>) -> DefId {
04454e1e
FG
289 let krate = CrateNum::from_u32(self.krate);
290 let krate = cdata.map_encoded_cnum_to_current(krate);
291 DefId { krate, index: DefIndex::from_u32(self.index) }
292 }
293}
294
3dfed10e 295#[derive(Encodable, Decodable)]
923072b8 296pub(crate) struct CrateDep {
f9f354fc 297 pub name: Symbol,
b7449926 298 pub hash: Svh,
e74abb32 299 pub host_hash: Option<Svh>,
3dfed10e 300 pub kind: CrateDepKind,
83c7162d 301 pub extra_filename: String,
9e0c209e
SL
302}
303
3dfed10e 304#[derive(MetadataEncodable, MetadataDecodable)]
923072b8 305pub(crate) struct TraitImpls {
60c5eb7d 306 trait_id: (u32, DefIndex),
923072b8 307 impls: LazyArray<(DefIndex, Option<SimplifiedType>)>,
9e0c209e
SL
308}
309
5e7ed085 310#[derive(MetadataEncodable, MetadataDecodable)]
923072b8 311pub(crate) struct IncoherentImpls {
5e7ed085 312 self_ty: SimplifiedType,
923072b8 313 impls: LazyArray<DefIndex>,
5e7ed085
FG
314}
315
ba9703b0
XL
316/// Define `LazyTables` and `TableBuilders` at the same time.
317macro_rules! define_tables {
17df50a5 318 ($($name:ident: Table<$IDX:ty, $T:ty>),+ $(,)?) => {
3dfed10e 319 #[derive(MetadataEncodable, MetadataDecodable)]
923072b8
FG
320 pub(crate) struct LazyTables {
321 $($name: LazyTable<$IDX, $T>),+
60c5eb7d
XL
322 }
323
324 #[derive(Default)]
923072b8 325 struct TableBuilders {
17df50a5 326 $($name: TableBuilder<$IDX, $T>),+
60c5eb7d
XL
327 }
328
923072b8 329 impl TableBuilders {
064997fb 330 fn encode(&self, buf: &mut FileEncoder) -> LazyTables {
ba9703b0 331 LazyTables {
60c5eb7d
XL
332 $($name: self.$name.encode(buf)),+
333 }
334 }
335 }
336 }
337}
338
ba9703b0 339define_tables! {
923072b8
FG
340 attributes: Table<DefIndex, LazyArray<ast::Attribute>>,
341 children: Table<DefIndex, LazyArray<DefIndex>>,
5e7ed085 342
04454e1e 343 opt_def_kind: Table<DefIndex, DefKind>,
f2b60f7d 344 visibility: Table<DefIndex, LazyValue<ty::Visibility<DefIndex>>>,
923072b8
FG
345 def_span: Table<DefIndex, LazyValue<Span>>,
346 def_ident_span: Table<DefIndex, LazyValue<Span>>,
347 lookup_stability: Table<DefIndex, LazyValue<attr::Stability>>,
348 lookup_const_stability: Table<DefIndex, LazyValue<attr::ConstStability>>,
f2b60f7d 349 lookup_default_body_stability: Table<DefIndex, LazyValue<attr::DefaultBodyStability>>,
923072b8 350 lookup_deprecation_entry: Table<DefIndex, LazyValue<attr::Deprecation>>,
5e7ed085 351 // As an optimization, a missing entry indicates an empty `&[]`.
923072b8
FG
352 explicit_item_bounds: Table<DefIndex, LazyArray<(ty::Predicate<'static>, Span)>>,
353 explicit_predicates_of: Table<DefIndex, LazyValue<ty::GenericPredicates<'static>>>,
354 generics_of: Table<DefIndex, LazyValue<ty::Generics>>,
5e7ed085 355 // As an optimization, a missing entry indicates an empty `&[]`.
487cf647 356 inferred_outlives_of: Table<DefIndex, LazyArray<(ty::Clause<'static>, Span)>>,
923072b8
FG
357 super_predicates_of: Table<DefIndex, LazyValue<ty::GenericPredicates<'static>>>,
358 type_of: Table<DefIndex, LazyValue<Ty<'static>>>,
359 variances_of: Table<DefIndex, LazyArray<ty::Variance>>,
360 fn_sig: Table<DefIndex, LazyValue<ty::PolyFnSig<'static>>>,
361 codegen_fn_attrs: Table<DefIndex, LazyValue<CodegenFnAttrs>>,
f25598a0
FG
362 impl_trait_ref: Table<DefIndex, LazyValue<ty::EarlyBinder<ty::TraitRef<'static>>>>,
363 const_param_default: Table<DefIndex, LazyValue<ty::EarlyBinder<rustc_middle::ty::Const<'static>>>>,
f2b60f7d 364 object_lifetime_default: Table<DefIndex, LazyValue<ObjectLifetimeDefault>>,
923072b8
FG
365 optimized_mir: Table<DefIndex, LazyValue<mir::Body<'static>>>,
366 mir_for_ctfe: Table<DefIndex, LazyValue<mir::Body<'static>>>,
367 promoted_mir: Table<DefIndex, LazyValue<IndexVec<mir::Promoted, mir::Body<'static>>>>,
368 // FIXME(compiler-errors): Why isn't this a LazyArray?
487cf647 369 thir_abstract_const: Table<DefIndex, LazyValue<ty::Const<'static>>>,
04454e1e
FG
370 impl_parent: Table<DefIndex, RawDefId>,
371 impl_polarity: Table<DefIndex, ty::ImplPolarity>,
923072b8
FG
372 constness: Table<DefIndex, hir::Constness>,
373 is_intrinsic: Table<DefIndex, ()>,
04454e1e 374 impl_defaultness: Table<DefIndex, hir::Defaultness>,
5e7ed085 375 // FIXME(eddyb) perhaps compute this on the fly if cheap enough?
923072b8
FG
376 coerce_unsized_info: Table<DefIndex, LazyValue<ty::adjustment::CoerceUnsizedInfo>>,
377 mir_const_qualif: Table<DefIndex, LazyValue<mir::ConstQualifs>>,
378 rendered_const: Table<DefIndex, LazyValue<String>>,
04454e1e 379 asyncness: Table<DefIndex, hir::IsAsync>,
923072b8
FG
380 fn_arg_names: Table<DefIndex, LazyArray<Ident>>,
381 generator_kind: Table<DefIndex, LazyValue<hir::GeneratorKind>>,
382 trait_def: Table<DefIndex, LazyValue<ty::TraitDef>>,
5e7ed085 383
04454e1e 384 trait_item_def_id: Table<DefIndex, RawDefId>,
923072b8
FG
385 inherent_impls: Table<DefIndex, LazyArray<DefIndex>>,
386 expn_that_defined: Table<DefIndex, LazyValue<ExpnId>>,
f25598a0 387 unused_generic_params: Table<DefIndex, LazyValue<UnusedGenericParams>>,
2b03887a 388 params_in_repr: Table<DefIndex, LazyValue<BitSet<u32>>>,
923072b8 389 repr_options: Table<DefIndex, LazyValue<ReprOptions>>,
3dfed10e
XL
390 // `def_keys` and `def_path_hashes` represent a lazy version of a
391 // `DefPathTable`. This allows us to avoid deserializing an entire
392 // `DefPathTable` up front, since we may only ever use a few
393 // definitions from any given crate.
923072b8 394 def_keys: Table<DefIndex, LazyValue<DefKey>>,
04454e1e 395 def_path_hashes: Table<DefIndex, DefPathHash>,
923072b8
FG
396 proc_macro_quoted_spans: Table<usize, LazyValue<Span>>,
397 generator_diagnostic_data: Table<DefIndex, LazyValue<GeneratorDiagnosticData<'static>>>,
04454e1e 398 may_have_doc_links: Table<DefIndex, ()>,
f2b60f7d
FG
399 variant_data: Table<DefIndex, LazyValue<VariantData>>,
400 assoc_container: Table<DefIndex, ty::AssocItemContainer>,
401 // Slot is full when macro is macro_rules.
402 macro_rules: Table<DefIndex, ()>,
487cf647 403 macro_definition: Table<DefIndex, LazyValue<ast::DelimArgs>>,
f2b60f7d
FG
404 proc_macro: Table<DefIndex, MacroKind>,
405 module_reexports: Table<DefIndex, LazyArray<ModChild>>,
2b03887a 406 deduced_param_attrs: Table<DefIndex, LazyArray<DeducedParamAttrs>>,
487cf647
FG
407 // Slot is full when opaque is TAIT.
408 is_type_alias_impl_trait: Table<DefIndex, ()>,
2b03887a
FG
409
410 trait_impl_trait_tys: Table<DefIndex, LazyValue<FxHashMap<DefId, Ty<'static>>>>,
32a655c1
SL
411}
412
3dfed10e 413#[derive(TyEncodable, TyDecodable)]
60c5eb7d 414struct VariantData {
60c5eb7d 415 discr: ty::VariantDiscr,
532ac7d7 416 /// If this is unit or tuple-variant/struct, then this is the index of the ctor id.
487cf647 417 ctor: Option<(CtorKind, DefIndex)>,
3dfed10e 418 is_non_exhaustive: bool,
9e0c209e
SL
419}
420
2c00a5a8 421// Tags used for encoding Spans:
ba9703b0
XL
422const TAG_VALID_SPAN_LOCAL: u8 = 0;
423const TAG_VALID_SPAN_FOREIGN: u8 = 1;
cdc7bbd5 424const TAG_PARTIAL_SPAN: u8 = 2;
a2a8927a 425
f2b60f7d
FG
426// Tags for encoding Symbol's
427const SYMBOL_STR: u8 = 0;
428const SYMBOL_OFFSET: u8 = 1;
429const SYMBOL_PREINTERNED: u8 = 2;
430
a2a8927a
XL
431pub fn provide(providers: &mut Providers) {
432 encoder::provide(providers);
433 decoder::provide(providers);
434}
923072b8
FG
435
436trivially_parameterized_over_tcx! {
437 VariantData,
923072b8
FG
438 RawDefId,
439 TraitImpls,
440 IncoherentImpls,
441 CrateRoot,
442 CrateDep,
443}