1 use crate::creader::CrateMetadataRef;
3 use def_path_hash_map::DefPathHashMapRef;
4 use table::TableBuilder;
7 use rustc_attr as attr;
8 use rustc_data_structures::svh::Svh;
9 use rustc_data_structures::sync::MetadataRef;
11 use rustc_hir::def::{CtorKind, DefKind};
12 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, DefPathHash, StableCrateId};
13 use rustc_hir::definitions::DefKey;
14 use rustc_hir::lang_items;
15 use rustc_index::{bit_set::FiniteBitSet, vec::IndexVec};
16 use rustc_middle::metadata::ModChild;
17 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
18 use rustc_middle::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo};
19 use rustc_middle::mir;
20 use rustc_middle::thir;
21 use rustc_middle::ty::fast_reject::SimplifiedType;
22 use rustc_middle::ty::query::Providers;
23 use rustc_middle::ty::{self, ReprOptions, Ty};
24 use rustc_middle::ty::{GeneratorDiagnosticData, TyCtxt};
25 use rustc_serialize::opaque::Encoder;
26 use rustc_session::config::SymbolManglingVersion;
27 use rustc_session::cstore::{CrateDepKind, ForeignModule, LinkagePreference, NativeLib};
28 use rustc_span::edition::Edition;
29 use rustc_span::hygiene::{ExpnIndex, MacroKind};
30 use rustc_span::symbol::{Ident, Symbol};
31 use rustc_span::{self, ExpnData, ExpnHash, ExpnId, Span};
32 use rustc_target::spec::{PanicStrategy, TargetTriple};
34 use std::marker::PhantomData;
35 use std::num::NonZeroUsize;
37 pub use decoder::provide_extern;
38 use decoder::DecodeContext;
39 pub(crate) use decoder::{CrateMetadata, CrateNumMap, MetadataBlob};
40 use encoder::EncodeContext;
41 pub use encoder::{encode_metadata, EncodedMetadata};
42 use rustc_span::hygiene::SyntaxContextData;
45 mod def_path_hash_map;
49 pub(crate) fn rustc_version() -> String {
50 format!("rustc {}", option_env!("CFG_VERSION").unwrap_or("unknown version"))
53 /// Metadata encoding version.
54 /// N.B., increment this if you change the format of metadata such that
55 /// the rustc version can't be found to compare with `rustc_version()`.
56 const METADATA_VERSION: u8 = 6;
58 /// Metadata header which includes `METADATA_VERSION`.
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.
63 pub const METADATA_HEADER: &[u8] = &[b'r', b'u', b's', b't', 0, 0, 0, METADATA_VERSION];
65 /// A value of type T referred to by its absolute position
66 /// in the metadata, and which can be decoded lazily.
68 /// Metadata is effective a tree, encoded in post-order,
69 /// and with the root's position written next to the header.
70 /// That means every single `Lazy` points to some previous
71 /// location in the metadata and is part of a larger node.
73 /// The first `Lazy` in a node is encoded as the backwards
74 /// distance from the position where the containing node
75 /// starts and where the `Lazy` points to, while the rest
76 /// use the forward distance from the previous `Lazy`.
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.
82 position: NonZeroUsize,
83 _marker: PhantomData<fn() -> T>,
86 impl<T> LazyValue<T> {
87 fn from_position(position: NonZeroUsize) -> LazyValue<T> {
88 LazyValue { position, _marker: PhantomData }
92 /// A list of lazily-decoded values.
94 /// Unlike `Lazy<Vec<T>>`, the length is encoded next to the
95 /// position, not at the position, which means that the length
96 /// doesn't need to be known before encoding all the elements.
98 /// If the length is 0, no position is encoded, but otherwise,
99 /// the encoding is that of `Lazy`, with the distinction that
100 /// the minimal distance the length of the sequence, i.e.
101 /// it's assumed there's no 0-byte element in the sequence.
102 struct LazyArray<T> {
103 position: NonZeroUsize,
105 _marker: PhantomData<fn() -> T>,
108 impl<T> LazyArray<T> {
109 fn from_position_and_num_elems(position: NonZeroUsize, num_elems: usize) -> LazyArray<T> {
110 LazyArray { position, num_elems, _marker: PhantomData }
113 fn empty() -> LazyArray<T> {
114 LazyArray::from_position_and_num_elems(NonZeroUsize::new(1).unwrap(), 0)
118 /// A list of lazily-decoded values, with the added capability of random access.
120 /// Random-access table (i.e. offering constant-time `get`/`set`), similar to
121 /// `LazyArray<T>`, but without requiring encoding or decoding all the values
122 /// eagerly and in-order.
123 struct LazyTable<I, T> {
124 position: NonZeroUsize,
126 _marker: PhantomData<fn(I) -> T>,
129 impl<I, T> LazyTable<I, T> {
130 fn from_position_and_encoded_size(
131 position: NonZeroUsize,
133 ) -> LazyTable<I, T> {
134 LazyTable { position, encoded_size, _marker: PhantomData }
138 impl<T> Copy for LazyValue<T> {}
139 impl<T> Clone for LazyValue<T> {
140 fn clone(&self) -> Self {
145 impl<T> Copy for LazyArray<T> {}
146 impl<T> Clone for LazyArray<T> {
147 fn clone(&self) -> Self {
152 impl<I, T> Copy for LazyTable<I, T> {}
153 impl<I, T> Clone for LazyTable<I, T> {
154 fn clone(&self) -> Self {
159 /// Encoding / decoding state for `Lazy`.
160 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
162 /// Outside of a metadata node.
165 /// Inside a metadata node, and before any `Lazy`.
166 /// The position is that of the node itself.
167 NodeStart(NonZeroUsize),
169 /// Inside a metadata node, with a previous `Lazy`.
170 /// The position is where that previous `Lazy` would start.
171 Previous(NonZeroUsize),
174 type SyntaxContextTable = LazyTable<u32, LazyValue<SyntaxContextData>>;
175 type ExpnDataTable = LazyTable<ExpnIndex, LazyValue<ExpnData>>;
176 type ExpnHashTable = LazyTable<ExpnIndex, LazyValue<ExpnHash>>;
178 #[derive(MetadataEncodable, MetadataDecodable)]
179 pub(crate) struct ProcMacroData {
180 proc_macro_decls_static: DefIndex,
181 stability: Option<attr::Stability>,
182 macros: LazyArray<DefIndex>,
185 /// Serialized metadata for a crate.
186 /// When compiling a proc-macro crate, we encode many of
187 /// the `LazyArray<T>` fields as `Lazy::empty()`. This serves two purposes:
189 /// 1. We avoid performing unnecessary work. Proc-macro crates can only
190 /// export proc-macros functions, which are compiled into a shared library.
191 /// As a result, a large amount of the information we normally store
192 /// (e.g. optimized MIR) is unneeded by downstream crates.
193 /// 2. We avoid serializing invalid `CrateNum`s. When we deserialize
194 /// a proc-macro crate, we don't load any of its dependencies (since we
195 /// just need to invoke a native function from the shared library).
196 /// This means that any foreign `CrateNum`s that we serialize cannot be
197 /// deserialized, since we will not know how to map them into the current
198 /// compilation session. If we were to serialize a proc-macro crate like
199 /// a normal crate, much of what we serialized would be unusable in addition
201 #[derive(MetadataEncodable, MetadataDecodable)]
202 pub(crate) struct CrateRoot<'tcx> {
204 triple: TargetTriple,
205 extra_filename: String,
207 stable_crate_id: StableCrateId,
208 panic_strategy: PanicStrategy,
209 panic_in_drop_strategy: PanicStrategy,
211 has_global_allocator: bool,
212 has_panic_handler: bool,
213 has_default_lib_allocator: bool,
215 crate_deps: LazyArray<CrateDep>,
216 dylib_dependency_formats: LazyArray<Option<LinkagePreference>>,
217 lib_features: LazyArray<(Symbol, Option<Symbol>)>,
218 lang_items: LazyArray<(DefIndex, usize)>,
219 lang_items_missing: LazyArray<lang_items::LangItem>,
220 diagnostic_items: LazyArray<(Symbol, DefIndex)>,
221 native_libraries: LazyArray<NativeLib>,
222 foreign_modules: LazyArray<ForeignModule>,
223 traits: LazyArray<DefIndex>,
224 impls: LazyArray<TraitImpls>,
225 incoherent_impls: LazyArray<IncoherentImpls>,
226 interpret_alloc_index: LazyArray<u32>,
227 proc_macro_data: Option<ProcMacroData>,
229 tables: LazyTables<'tcx>,
230 debugger_visualizers: LazyArray<rustc_span::DebuggerVisualizerFile>,
232 exported_symbols: LazyArray<(ExportedSymbol<'tcx>, SymbolExportInfo)>,
234 syntax_contexts: SyntaxContextTable,
235 expn_data: ExpnDataTable,
236 expn_hashes: ExpnHashTable,
238 def_path_hash_map: LazyValue<DefPathHashMapRef<'tcx>>,
240 source_map: LazyArray<rustc_span::SourceFile>,
242 compiler_builtins: bool,
243 needs_allocator: bool,
244 needs_panic_runtime: bool,
247 profiler_runtime: bool,
248 symbol_mangling_version: SymbolManglingVersion,
251 /// On-disk representation of `DefId`.
252 /// This creates a type-safe way to enforce that we remap the CrateNum between the on-disk
253 /// representation and the compilation session.
254 #[derive(Copy, Clone)]
255 pub(crate) struct RawDefId {
260 impl Into<RawDefId> for DefId {
261 fn into(self) -> RawDefId {
262 RawDefId { krate: self.krate.as_u32(), index: self.index.as_u32() }
267 /// This exists so that `provide_one!` is happy
268 fn decode(self, meta: (CrateMetadataRef<'_>, TyCtxt<'_>)) -> DefId {
269 self.decode_from_cdata(meta.0)
272 fn decode_from_cdata(self, cdata: CrateMetadataRef<'_>) -> DefId {
273 let krate = CrateNum::from_u32(self.krate);
274 let krate = cdata.map_encoded_cnum_to_current(krate);
275 DefId { krate, index: DefIndex::from_u32(self.index) }
279 #[derive(Encodable, Decodable)]
280 pub(crate) struct CrateDep {
283 pub host_hash: Option<Svh>,
284 pub kind: CrateDepKind,
285 pub extra_filename: String,
288 #[derive(MetadataEncodable, MetadataDecodable)]
289 pub(crate) struct TraitImpls {
290 trait_id: (u32, DefIndex),
291 impls: LazyArray<(DefIndex, Option<SimplifiedType>)>,
294 #[derive(MetadataEncodable, MetadataDecodable)]
295 pub(crate) struct IncoherentImpls {
296 self_ty: SimplifiedType,
297 impls: LazyArray<DefIndex>,
300 /// Define `LazyTables` and `TableBuilders` at the same time.
301 macro_rules! define_tables {
302 ($($name:ident: Table<$IDX:ty, $T:ty>),+ $(,)?) => {
303 #[derive(MetadataEncodable, MetadataDecodable)]
304 pub(crate) struct LazyTables<'tcx> {
305 $($name: LazyTable<$IDX, $T>),+
309 struct TableBuilders<'tcx> {
310 $($name: TableBuilder<$IDX, $T>),+
313 impl<'tcx> TableBuilders<'tcx> {
314 fn encode(&self, buf: &mut Encoder) -> LazyTables<'tcx> {
316 $($name: self.$name.encode(buf)),+
324 kind: Table<DefIndex, LazyValue<EntryKind>>,
325 attributes: Table<DefIndex, LazyArray<ast::Attribute>>,
326 children: Table<DefIndex, LazyArray<DefIndex>>,
328 opt_def_kind: Table<DefIndex, DefKind>,
329 visibility: Table<DefIndex, LazyValue<ty::Visibility>>,
330 def_span: Table<DefIndex, LazyValue<Span>>,
331 def_ident_span: Table<DefIndex, LazyValue<Span>>,
332 lookup_stability: Table<DefIndex, LazyValue<attr::Stability>>,
333 lookup_const_stability: Table<DefIndex, LazyValue<attr::ConstStability>>,
334 lookup_deprecation_entry: Table<DefIndex, LazyValue<attr::Deprecation>>,
335 // As an optimization, a missing entry indicates an empty `&[]`.
336 explicit_item_bounds: Table<DefIndex, LazyArray<(ty::Predicate<'tcx>, Span)>>,
337 explicit_predicates_of: Table<DefIndex, LazyValue<ty::GenericPredicates<'tcx>>>,
338 generics_of: Table<DefIndex, LazyValue<ty::Generics>>,
339 // As an optimization, a missing entry indicates an empty `&[]`.
340 inferred_outlives_of: Table<DefIndex, LazyArray<(ty::Predicate<'tcx>, Span)>>,
341 super_predicates_of: Table<DefIndex, LazyValue<ty::GenericPredicates<'tcx>>>,
342 type_of: Table<DefIndex, LazyValue<Ty<'tcx>>>,
343 variances_of: Table<DefIndex, LazyArray<ty::Variance>>,
344 fn_sig: Table<DefIndex, LazyValue<ty::PolyFnSig<'tcx>>>,
345 codegen_fn_attrs: Table<DefIndex, LazyValue<CodegenFnAttrs>>,
346 impl_trait_ref: Table<DefIndex, LazyValue<ty::TraitRef<'tcx>>>,
347 const_param_default: Table<DefIndex, LazyValue<rustc_middle::ty::Const<'tcx>>>,
348 optimized_mir: Table<DefIndex, LazyValue<mir::Body<'tcx>>>,
349 mir_for_ctfe: Table<DefIndex, LazyValue<mir::Body<'tcx>>>,
350 promoted_mir: Table<DefIndex, LazyValue<IndexVec<mir::Promoted, mir::Body<'tcx>>>>,
351 // FIXME(compiler-errors): Why isn't this a LazyArray?
352 thir_abstract_const: Table<DefIndex, LazyValue<&'tcx [thir::abstract_const::Node<'tcx>]>>,
353 impl_parent: Table<DefIndex, RawDefId>,
354 impl_polarity: Table<DefIndex, ty::ImplPolarity>,
355 impl_constness: Table<DefIndex, hir::Constness>,
356 is_intrinsic: Table<DefIndex, ()>,
357 impl_defaultness: Table<DefIndex, hir::Defaultness>,
358 // FIXME(eddyb) perhaps compute this on the fly if cheap enough?
359 coerce_unsized_info: Table<DefIndex, LazyValue<ty::adjustment::CoerceUnsizedInfo>>,
360 mir_const_qualif: Table<DefIndex, LazyValue<mir::ConstQualifs>>,
361 rendered_const: Table<DefIndex, LazyValue<String>>,
362 asyncness: Table<DefIndex, hir::IsAsync>,
363 fn_arg_names: Table<DefIndex, LazyArray<Ident>>,
364 generator_kind: Table<DefIndex, LazyValue<hir::GeneratorKind>>,
365 trait_def: Table<DefIndex, LazyValue<ty::TraitDef>>,
367 trait_item_def_id: Table<DefIndex, RawDefId>,
368 inherent_impls: Table<DefIndex, LazyArray<DefIndex>>,
369 expn_that_defined: Table<DefIndex, LazyValue<ExpnId>>,
370 unused_generic_params: Table<DefIndex, LazyValue<FiniteBitSet<u32>>>,
371 repr_options: Table<DefIndex, LazyValue<ReprOptions>>,
372 // `def_keys` and `def_path_hashes` represent a lazy version of a
373 // `DefPathTable`. This allows us to avoid deserializing an entire
374 // `DefPathTable` up front, since we may only ever use a few
375 // definitions from any given crate.
376 def_keys: Table<DefIndex, LazyValue<DefKey>>,
377 def_path_hashes: Table<DefIndex, DefPathHash>,
378 proc_macro_quoted_spans: Table<usize, LazyValue<Span>>,
379 generator_diagnostic_data: Table<DefIndex, LazyValue<GeneratorDiagnosticData<'tcx>>>,
380 may_have_doc_links: Table<DefIndex, ()>,
383 #[derive(Copy, Clone, MetadataEncodable, MetadataDecodable)]
398 Variant(LazyValue<VariantData>),
399 Struct(LazyValue<VariantData>),
400 Union(LazyValue<VariantData>),
403 Mod(LazyArray<ModChild>),
404 MacroDef(LazyValue<ast::MacArgs>, /*macro_rules*/ bool),
405 ProcMacro(MacroKind),
410 AssocFn(LazyValue<AssocFnData>),
411 AssocType(AssocContainer),
412 AssocConst(AssocContainer),
416 #[derive(TyEncodable, TyDecodable)]
419 discr: ty::VariantDiscr,
420 /// If this is unit or tuple-variant/struct, then this is the index of the ctor id.
421 ctor: Option<DefIndex>,
422 is_non_exhaustive: bool,
425 /// Describes whether the container of an associated item
426 /// is a trait or an impl and whether, in a trait, it has
427 /// a default, or an in impl, whether it's marked "default".
428 #[derive(Copy, Clone, TyEncodable, TyDecodable)]
429 enum AssocContainer {
436 impl AssocContainer {
437 fn with_def_id(&self, def_id: DefId) -> ty::AssocItemContainer {
439 AssocContainer::TraitRequired | AssocContainer::TraitWithDefault => {
440 ty::TraitContainer(def_id)
443 AssocContainer::ImplDefault | AssocContainer::ImplFinal => ty::ImplContainer(def_id),
447 fn defaultness(&self) -> hir::Defaultness {
449 AssocContainer::TraitRequired => hir::Defaultness::Default { has_value: false },
451 AssocContainer::TraitWithDefault | AssocContainer::ImplDefault => {
452 hir::Defaultness::Default { has_value: true }
455 AssocContainer::ImplFinal => hir::Defaultness::Final,
460 #[derive(MetadataEncodable, MetadataDecodable)]
462 container: AssocContainer,
466 #[derive(TyEncodable, TyDecodable)]
467 struct GeneratorData<'tcx> {
468 layout: mir::GeneratorLayout<'tcx>,
471 // Tags used for encoding Spans:
472 const TAG_VALID_SPAN_LOCAL: u8 = 0;
473 const TAG_VALID_SPAN_FOREIGN: u8 = 1;
474 const TAG_PARTIAL_SPAN: u8 = 2;
476 pub fn provide(providers: &mut Providers) {
477 encoder::provide(providers);
478 decoder::provide(providers);