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