]>
Commit | Line | Data |
---|---|---|
3dfed10e | 1 | use crate::rmeta::table::{FixedSizeEncoding, TableBuilder}; |
dfeec247 | 2 | use crate::rmeta::*; |
92a42be0 | 3 | |
5869c6ff | 4 | use rustc_data_structures::fx::{FxHashMap, FxIndexSet}; |
ba9703b0 | 5 | use rustc_data_structures::stable_hasher::StableHasher; |
5869c6ff | 6 | use rustc_data_structures::sync::{join, par_iter, Lrc, ParallelIterator}; |
ba9703b0 | 7 | use rustc_hir as hir; |
5869c6ff | 8 | use rustc_hir::def::{CtorOf, DefKind}; |
6a06907d XL |
9 | use rustc_hir::def_id::{ |
10 | CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE, | |
11 | }; | |
fc512014 | 12 | use rustc_hir::definitions::DefPathData; |
ba9703b0 | 13 | use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor}; |
5869c6ff | 14 | use rustc_hir::itemlikevisit::ItemLikeVisitor; |
ba9703b0 | 15 | use rustc_hir::lang_items; |
dfeec247 | 16 | use rustc_hir::{AnonConst, GenericParamKind}; |
f035d41b | 17 | use rustc_index::bit_set::GrowableBitSet; |
dfeec247 | 18 | use rustc_index::vec::Idx; |
ba9703b0 | 19 | use rustc_middle::hir::map::Map; |
f9f354fc | 20 | use rustc_middle::middle::cstore::{EncodedMetadata, ForeignModule, LinkagePreference, NativeLib}; |
ba9703b0 XL |
21 | use rustc_middle::middle::dependency_format::Linkage; |
22 | use rustc_middle::middle::exported_symbols::{ | |
23 | metadata_symbol_name, ExportedSymbol, SymbolExportLevel, | |
24 | }; | |
3dfed10e | 25 | use rustc_middle::mir::interpret; |
ba9703b0 | 26 | use rustc_middle::traits::specialization_graph; |
3dfed10e | 27 | use rustc_middle::ty::codec::TyEncoder; |
ba9703b0 | 28 | use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt}; |
3dfed10e | 29 | use rustc_serialize::{opaque, Encodable, Encoder}; |
f9f354fc | 30 | use rustc_session::config::CrateType; |
f035d41b | 31 | use rustc_span::symbol::{sym, Ident, Symbol}; |
3dfed10e | 32 | use rustc_span::{self, ExternalSource, FileName, SourceFile, Span, SyntaxContext}; |
17df50a5 XL |
33 | use rustc_span::{ |
34 | hygiene::{ExpnDataEncodeMode, HygieneEncodeContext, MacroKind}, | |
35 | RealFileName, | |
36 | }; | |
ba9703b0 | 37 | use rustc_target::abi::VariantIdx; |
ff7c6d11 | 38 | use std::hash::Hash; |
e74abb32 | 39 | use std::num::NonZeroUsize; |
7cac9316 | 40 | use std::path::Path; |
3dfed10e | 41 | use tracing::{debug, trace}; |
9e0c209e | 42 | |
3dfed10e | 43 | pub(super) struct EncodeContext<'a, 'tcx> { |
8faf50e0 | 44 | opaque: opaque::Encoder, |
e74abb32 | 45 | tcx: TyCtxt<'tcx>, |
1b1a35ee | 46 | feat: &'tcx rustc_feature::Features, |
dc9dc135 | 47 | |
ba9703b0 | 48 | tables: TableBuilders<'tcx>, |
9e0c209e SL |
49 | |
50 | lazy_state: LazyState, | |
476ff2be | 51 | type_shorthands: FxHashMap<Ty<'tcx>, usize>, |
5869c6ff | 52 | predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>, |
2c00a5a8 | 53 | |
3dfed10e | 54 | interpret_allocs: FxIndexSet<interpret::AllocId>, |
0531ce1d | 55 | |
2c00a5a8 | 56 | // This is used to speed up Span encoding. |
f035d41b XL |
57 | // The `usize` is an index into the `MonotonicVec` |
58 | // that stores the `SourceFile` | |
59 | source_file_cache: (Lrc<SourceFile>, usize), | |
60 | // The indices (into the `SourceMap`'s `MonotonicVec`) | |
61 | // of all of the `SourceFiles` that we need to serialize. | |
62 | // When we serialize a `Span`, we insert the index of its | |
63 | // `SourceFile` into the `GrowableBitSet`. | |
64 | // | |
65 | // This needs to be a `GrowableBitSet` and not a | |
66 | // regular `BitSet` because we may actually import new `SourceFiles` | |
67 | // during metadata encoding, due to executing a query | |
68 | // with a result containing a foreign `Span`. | |
69 | required_source_files: Option<GrowableBitSet<usize>>, | |
70 | is_proc_macro: bool, | |
3dfed10e | 71 | hygiene_ctxt: &'a HygieneEncodeContext, |
9e0c209e SL |
72 | } |
73 | ||
1b1a35ee XL |
74 | /// If the current crate is a proc-macro, returns early with `Lazy:empty()`. |
75 | /// This is useful for skipping the encoding of things that aren't needed | |
76 | /// for proc-macro crates. | |
77 | macro_rules! empty_proc_macro { | |
78 | ($self:ident) => { | |
79 | if $self.is_proc_macro { | |
80 | return Lazy::empty(); | |
81 | } | |
82 | }; | |
83 | } | |
84 | ||
9e0c209e SL |
85 | macro_rules! encoder_methods { |
86 | ($($name:ident($ty:ty);)*) => { | |
87 | $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> { | |
88 | self.opaque.$name(value) | |
89 | })* | |
b039eaaf SL |
90 | } |
91 | } | |
92 | ||
3dfed10e | 93 | impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> { |
8faf50e0 | 94 | type Error = <opaque::Encoder as Encoder>::Error; |
b039eaaf | 95 | |
f9f354fc | 96 | #[inline] |
b7449926 | 97 | fn emit_unit(&mut self) -> Result<(), Self::Error> { |
9e0c209e | 98 | Ok(()) |
b039eaaf SL |
99 | } |
100 | ||
9e0c209e SL |
101 | encoder_methods! { |
102 | emit_usize(usize); | |
32a655c1 | 103 | emit_u128(u128); |
9e0c209e SL |
104 | emit_u64(u64); |
105 | emit_u32(u32); | |
106 | emit_u16(u16); | |
107 | emit_u8(u8); | |
108 | ||
109 | emit_isize(isize); | |
32a655c1 | 110 | emit_i128(i128); |
9e0c209e SL |
111 | emit_i64(i64); |
112 | emit_i32(i32); | |
113 | emit_i16(i16); | |
114 | emit_i8(i8); | |
115 | ||
116 | emit_bool(bool); | |
117 | emit_f64(f64); | |
118 | emit_f32(f32); | |
119 | emit_char(char); | |
120 | emit_str(&str); | |
cdc7bbd5 | 121 | emit_raw_bytes(&[u8]); |
b039eaaf SL |
122 | } |
123 | } | |
124 | ||
3dfed10e XL |
125 | impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>> |
126 | for Lazy<T> | |
127 | { | |
128 | fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { | |
129 | e.emit_lazy_distance(*self) | |
9e0c209e | 130 | } |
223e47cc LB |
131 | } |
132 | ||
3dfed10e XL |
133 | impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>> |
134 | for Lazy<[T]> | |
135 | { | |
136 | fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { | |
137 | e.emit_usize(self.meta)?; | |
138 | if self.meta == 0 { | |
9e0c209e SL |
139 | return Ok(()); |
140 | } | |
3dfed10e | 141 | e.emit_lazy_distance(*self) |
9e0c209e | 142 | } |
223e47cc LB |
143 | } |
144 | ||
3dfed10e XL |
145 | impl<'a, 'tcx, I: Idx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>> |
146 | for Lazy<Table<I, T>> | |
dfeec247 XL |
147 | where |
148 | Option<T>: FixedSizeEncoding, | |
e74abb32 | 149 | { |
3dfed10e XL |
150 | fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { |
151 | e.emit_usize(self.meta)?; | |
152 | e.emit_lazy_distance(*self) | |
e74abb32 XL |
153 | } |
154 | } | |
155 | ||
1b1a35ee XL |
156 | impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for CrateNum { |
157 | fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { | |
158 | if *self != LOCAL_CRATE && s.is_proc_macro { | |
159 | panic!("Attempted to encode non-local CrateNum {:?} for proc-macro crate", self); | |
160 | } | |
161 | s.emit_u32(self.as_u32()) | |
162 | } | |
163 | } | |
164 | ||
3dfed10e XL |
165 | impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for DefIndex { |
166 | fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { | |
167 | s.emit_u32(self.as_u32()) | |
abe05a73 XL |
168 | } |
169 | } | |
170 | ||
3dfed10e XL |
171 | impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for SyntaxContext { |
172 | fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { | |
173 | rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s) | |
abe05a73 XL |
174 | } |
175 | } | |
176 | ||
3dfed10e XL |
177 | impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnId { |
178 | fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { | |
179 | rustc_span::hygiene::raw_encode_expn_id( | |
180 | *self, | |
181 | &s.hygiene_ctxt, | |
182 | ExpnDataEncodeMode::Metadata, | |
183 | s, | |
184 | ) | |
2c00a5a8 XL |
185 | } |
186 | } | |
187 | ||
3dfed10e XL |
188 | impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Span { |
189 | fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { | |
cdc7bbd5 XL |
190 | let span = self.data(); |
191 | ||
192 | // Don't serialize any `SyntaxContext`s from a proc-macro crate, | |
193 | // since we don't load proc-macro dependencies during serialization. | |
194 | // This means that any hygiene information from macros used *within* | |
195 | // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro | |
196 | // definition) will be lost. | |
197 | // | |
198 | // This can show up in two ways: | |
199 | // | |
200 | // 1. Any hygiene information associated with identifier of | |
201 | // a proc macro (e.g. `#[proc_macro] pub fn $name`) will be lost. | |
202 | // Since proc-macros can only be invoked from a different crate, | |
203 | // real code should never need to care about this. | |
204 | // | |
205 | // 2. Using `Span::def_site` or `Span::mixed_site` will not | |
206 | // include any hygiene information associated with the definition | |
207 | // site. This means that a proc-macro cannot emit a `$crate` | |
208 | // identifier which resolves to one of its dependencies, | |
209 | // which also should never come up in practice. | |
210 | // | |
211 | // Additionally, this affects `Span::parent`, and any other | |
212 | // span inspection APIs that would otherwise allow traversing | |
213 | // the `SyntaxContexts` associated with a span. | |
214 | // | |
215 | // None of these user-visible effects should result in any | |
216 | // cross-crate inconsistencies (getting one behavior in the same | |
217 | // crate, and a different behavior in another crate) due to the | |
218 | // limited surface that proc-macros can expose. | |
219 | // | |
220 | // IMPORTANT: If this is ever changed, be sure to update | |
221 | // `rustc_span::hygiene::raw_encode_expn_id` to handle | |
222 | // encoding `ExpnData` for proc-macro crates. | |
223 | if s.is_proc_macro { | |
224 | SyntaxContext::root().encode(s)?; | |
225 | } else { | |
226 | span.ctxt.encode(s)?; | |
2c00a5a8 XL |
227 | } |
228 | ||
cdc7bbd5 XL |
229 | if self.is_dummy() { |
230 | return TAG_PARTIAL_SPAN.encode(s); | |
231 | } | |
2c00a5a8 XL |
232 | |
233 | // The Span infrastructure should make sure that this invariant holds: | |
234 | debug_assert!(span.lo <= span.hi); | |
235 | ||
3dfed10e XL |
236 | if !s.source_file_cache.0.contains(span.lo) { |
237 | let source_map = s.tcx.sess.source_map(); | |
b7449926 | 238 | let source_file_index = source_map.lookup_source_file_idx(span.lo); |
3dfed10e | 239 | s.source_file_cache = |
f035d41b | 240 | (source_map.files()[source_file_index].clone(), source_file_index); |
2c00a5a8 XL |
241 | } |
242 | ||
3dfed10e | 243 | if !s.source_file_cache.0.contains(span.hi) { |
2c00a5a8 XL |
244 | // Unfortunately, macro expansion still sometimes generates Spans |
245 | // that malformed in this way. | |
cdc7bbd5 | 246 | return TAG_PARTIAL_SPAN.encode(s); |
2c00a5a8 XL |
247 | } |
248 | ||
3dfed10e | 249 | let source_files = s.required_source_files.as_mut().expect("Already encoded SourceMap!"); |
f035d41b | 250 | // Record the fact that we need to encode the data for this `SourceFile` |
3dfed10e | 251 | source_files.insert(s.source_file_cache.1); |
f035d41b | 252 | |
ba9703b0 XL |
253 | // There are two possible cases here: |
254 | // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the | |
255 | // crate we are writing metadata for. When the metadata for *this* crate gets | |
256 | // deserialized, the deserializer will need to know which crate it originally came | |
257 | // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should | |
258 | // be deserialized after the rest of the span data, which tells the deserializer | |
259 | // which crate contains the source map information. | |
260 | // 2. This span comes from our own crate. No special hamdling is needed - we just | |
261 | // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use | |
262 | // our own source map information. | |
f035d41b XL |
263 | // |
264 | // If we're a proc-macro crate, we always treat this as a local `Span`. | |
265 | // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata | |
266 | // if we're a proc-macro crate. | |
267 | // This allows us to avoid loading the dependencies of proc-macro crates: all of | |
268 | // the information we need to decode `Span`s is stored in the proc-macro crate. | |
3dfed10e | 269 | let (tag, lo, hi) = if s.source_file_cache.0.is_imported() && !s.is_proc_macro { |
ba9703b0 XL |
270 | // To simplify deserialization, we 'rebase' this span onto the crate it originally came from |
271 | // (the crate that 'owns' the file it references. These rebased 'lo' and 'hi' values | |
272 | // are relative to the source map information for the 'foreign' crate whose CrateNum | |
273 | // we write into the metadata. This allows `imported_source_files` to binary | |
274 | // search through the 'foreign' crate's source map information, using the | |
275 | // deserialized 'lo' and 'hi' values directly. | |
276 | // | |
277 | // All of this logic ensures that the final result of deserialization is a 'normal' | |
278 | // Span that can be used without any additional trouble. | |
279 | let external_start_pos = { | |
280 | // Introduce a new scope so that we drop the 'lock()' temporary | |
3dfed10e | 281 | match &*s.source_file_cache.0.external_src.lock() { |
ba9703b0 XL |
282 | ExternalSource::Foreign { original_start_pos, .. } => *original_start_pos, |
283 | src => panic!("Unexpected external source {:?}", src), | |
284 | } | |
285 | }; | |
3dfed10e XL |
286 | let lo = (span.lo - s.source_file_cache.0.start_pos) + external_start_pos; |
287 | let hi = (span.hi - s.source_file_cache.0.start_pos) + external_start_pos; | |
e74abb32 | 288 | |
ba9703b0 XL |
289 | (TAG_VALID_SPAN_FOREIGN, lo, hi) |
290 | } else { | |
291 | (TAG_VALID_SPAN_LOCAL, span.lo, span.hi) | |
292 | }; | |
293 | ||
3dfed10e XL |
294 | tag.encode(s)?; |
295 | lo.encode(s)?; | |
2c00a5a8 XL |
296 | |
297 | // Encode length which is usually less than span.hi and profits more | |
298 | // from the variable-length integer encoding that we use. | |
ba9703b0 | 299 | let len = hi - lo; |
3dfed10e XL |
300 | len.encode(s)?; |
301 | ||
ba9703b0 | 302 | if tag == TAG_VALID_SPAN_FOREIGN { |
3dfed10e XL |
303 | // This needs to be two lines to avoid holding the `s.source_file_cache` |
304 | // while calling `cnum.encode(s)` | |
305 | let cnum = s.source_file_cache.0.cnum; | |
306 | cnum.encode(s)?; | |
ba9703b0 | 307 | } |
2c00a5a8 | 308 | |
3dfed10e | 309 | Ok(()) |
abe05a73 XL |
310 | } |
311 | } | |
312 | ||
3dfed10e XL |
313 | impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> { |
314 | const CLEAR_CROSS_CRATE: bool = true; | |
d9579d0f | 315 | |
3dfed10e XL |
316 | fn position(&self) -> usize { |
317 | self.opaque.position() | |
f035d41b | 318 | } |
f035d41b | 319 | |
3dfed10e XL |
320 | fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> { |
321 | &mut self.type_shorthands | |
0531ce1d | 322 | } |
0531ce1d | 323 | |
5869c6ff | 324 | fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> { |
3dfed10e | 325 | &mut self.predicate_shorthands |
2c00a5a8 | 326 | } |
2c00a5a8 | 327 | |
3dfed10e XL |
328 | fn encode_alloc_id( |
329 | &mut self, | |
330 | alloc_id: &rustc_middle::mir::interpret::AllocId, | |
331 | ) -> Result<(), Self::Error> { | |
332 | let (index, _) = self.interpret_allocs.insert_full(*alloc_id); | |
333 | ||
334 | index.encode(self) | |
ff7c6d11 XL |
335 | } |
336 | } | |
337 | ||
1b1a35ee XL |
338 | impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for &'tcx [mir::abstract_const::Node<'tcx>] { |
339 | fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { | |
340 | (**self).encode(s) | |
341 | } | |
342 | } | |
343 | ||
3dfed10e XL |
344 | impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for &'tcx [(ty::Predicate<'tcx>, Span)] { |
345 | fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { | |
346 | (**self).encode(s) | |
9e0c209e | 347 | } |
abe05a73 XL |
348 | } |
349 | ||
e1599b0c | 350 | /// Helper trait to allow overloading `EncodeContext::lazy` for iterators. |
3dfed10e XL |
351 | trait EncodeContentsForLazy<'a, 'tcx, T: ?Sized + LazyMeta> { |
352 | fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> T::Meta; | |
e1599b0c XL |
353 | } |
354 | ||
3dfed10e XL |
355 | impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, T> for &T { |
356 | fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) { | |
e1599b0c | 357 | self.encode(ecx).unwrap() |
9e0c209e | 358 | } |
e1599b0c XL |
359 | } |
360 | ||
3dfed10e XL |
361 | impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, T> for T { |
362 | fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) { | |
e1599b0c XL |
363 | self.encode(ecx).unwrap() |
364 | } | |
365 | } | |
85aaf69f | 366 | |
3dfed10e | 367 | impl<'a, 'tcx, I, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, [T]> for I |
dfeec247 XL |
368 | where |
369 | I: IntoIterator, | |
3dfed10e | 370 | I::Item: EncodeContentsForLazy<'a, 'tcx, T>, |
e1599b0c | 371 | { |
3dfed10e | 372 | fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> usize { |
e1599b0c XL |
373 | self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count() |
374 | } | |
375 | } | |
376 | ||
60c5eb7d | 377 | // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy($value))`, which would |
e74abb32 XL |
378 | // normally need extra variables to avoid errors about multiple mutable borrows. |
379 | macro_rules! record { | |
60c5eb7d | 380 | ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{ |
e74abb32 XL |
381 | { |
382 | let value = $value; | |
383 | let lazy = $self.lazy(value); | |
60c5eb7d | 384 | $self.$tables.$table.set($def_id.index, lazy); |
e74abb32 | 385 | } |
dfeec247 | 386 | }}; |
e74abb32 XL |
387 | } |
388 | ||
3dfed10e | 389 | impl<'a, 'tcx> EncodeContext<'a, 'tcx> { |
e1599b0c XL |
390 | fn emit_lazy_distance<T: ?Sized + LazyMeta>( |
391 | &mut self, | |
392 | lazy: Lazy<T>, | |
393 | ) -> Result<(), <Self as Encoder>::Error> { | |
e74abb32 | 394 | let min_end = lazy.position.get() + T::min_size(lazy.meta); |
9e0c209e | 395 | let distance = match self.lazy_state { |
c30ab7b3 | 396 | LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"), |
9e0c209e | 397 | LazyState::NodeStart(start) => { |
e74abb32 | 398 | let start = start.get(); |
9e0c209e SL |
399 | assert!(min_end <= start); |
400 | start - min_end | |
401 | } | |
402 | LazyState::Previous(last_min_end) => { | |
0531ce1d | 403 | assert!( |
e1599b0c | 404 | last_min_end <= lazy.position, |
0531ce1d | 405 | "make sure that the calls to `lazy*` \ |
74b04a01 | 406 | are in the same order as the metadata fields", |
0531ce1d | 407 | ); |
e74abb32 | 408 | lazy.position.get() - last_min_end.get() |
9e0c209e SL |
409 | } |
410 | }; | |
e74abb32 | 411 | self.lazy_state = LazyState::Previous(NonZeroUsize::new(min_end).unwrap()); |
9e0c209e SL |
412 | self.emit_usize(distance) |
413 | } | |
1a4d82fc | 414 | |
3dfed10e XL |
415 | fn lazy<T: ?Sized + LazyMeta>( |
416 | &mut self, | |
417 | value: impl EncodeContentsForLazy<'a, 'tcx, T>, | |
418 | ) -> Lazy<T> { | |
e74abb32 | 419 | let pos = NonZeroUsize::new(self.position()).unwrap(); |
223e47cc | 420 | |
e1599b0c XL |
421 | assert_eq!(self.lazy_state, LazyState::NoNode); |
422 | self.lazy_state = LazyState::NodeStart(pos); | |
423 | let meta = value.encode_contents_for_lazy(self); | |
424 | self.lazy_state = LazyState::NoNode; | |
1a4d82fc | 425 | |
e74abb32 | 426 | assert!(pos.get() + <T>::min_size(meta) <= self.position()); |
1a4d82fc | 427 | |
e1599b0c | 428 | Lazy::from_position_and_meta(pos, meta) |
1a4d82fc | 429 | } |
223e47cc | 430 | |
dc9dc135 | 431 | fn encode_info_for_items(&mut self) { |
0731742a | 432 | let krate = self.tcx.hir().krate(); |
cdc7bbd5 | 433 | self.encode_info_for_mod(CRATE_DEF_ID, &krate.item); |
1b1a35ee XL |
434 | |
435 | // Proc-macro crates only export proc-macro items, which are looked | |
436 | // up using `proc_macro_data` | |
437 | if self.is_proc_macro { | |
438 | return; | |
439 | } | |
440 | ||
dc9dc135 | 441 | krate.visit_all_item_likes(&mut self.as_deep_visitor()); |
dfeec247 | 442 | for macro_def in krate.exported_macros { |
dc9dc135 | 443 | self.visit_macro_def(macro_def); |
7cac9316 | 444 | } |
7cac9316 XL |
445 | } |
446 | ||
3dfed10e XL |
447 | fn encode_def_path_table(&mut self) { |
448 | let table = self.tcx.hir().definitions().def_path_table(); | |
1b1a35ee XL |
449 | if self.is_proc_macro { |
450 | for def_index in std::iter::once(CRATE_DEF_INDEX) | |
451 | .chain(self.tcx.hir().krate().proc_macros.iter().map(|p| p.owner.local_def_index)) | |
452 | { | |
453 | let def_key = self.lazy(table.def_key(def_index)); | |
454 | let def_path_hash = self.lazy(table.def_path_hash(def_index)); | |
455 | self.tables.def_keys.set(def_index, def_key); | |
456 | self.tables.def_path_hashes.set(def_index, def_path_hash); | |
457 | } | |
458 | } else { | |
459 | for (def_index, def_key, def_path_hash) in table.enumerated_keys_and_path_hashes() { | |
460 | let def_key = self.lazy(def_key); | |
461 | let def_path_hash = self.lazy(def_path_hash); | |
462 | self.tables.def_keys.set(def_index, def_key); | |
463 | self.tables.def_path_hashes.set(def_index, def_path_hash); | |
464 | } | |
3dfed10e | 465 | } |
7cac9316 XL |
466 | } |
467 | ||
dfeec247 | 468 | fn encode_source_map(&mut self) -> Lazy<[rustc_span::SourceFile]> { |
b7449926 XL |
469 | let source_map = self.tcx.sess.source_map(); |
470 | let all_source_files = source_map.files(); | |
7cac9316 | 471 | |
f035d41b XL |
472 | // By replacing the `Option` with `None`, we ensure that we can't |
473 | // accidentally serialize any more `Span`s after the source map encoding | |
474 | // is done. | |
475 | let required_source_files = self.required_source_files.take().unwrap(); | |
7cac9316 | 476 | |
dfeec247 XL |
477 | let adapted = all_source_files |
478 | .iter() | |
f035d41b XL |
479 | .enumerate() |
480 | .filter(|(idx, source_file)| { | |
481 | // Only serialize `SourceFile`s that were used | |
482 | // during the encoding of a `Span` | |
483 | required_source_files.contains(*idx) && | |
484 | // Don't serialize imported `SourceFile`s, unless | |
485 | // we're in a proc-macro crate. | |
486 | (!source_file.is_imported() || self.is_proc_macro) | |
7cac9316 | 487 | }) |
f035d41b XL |
488 | .map(|(_, source_file)| { |
489 | let mut adapted = match source_file.name { | |
17df50a5 | 490 | FileName::Real(ref realname) => { |
a1dfa0c6 | 491 | let mut adapted = (**source_file).clone(); |
17df50a5 XL |
492 | adapted.name = FileName::Real(match realname { |
493 | RealFileName::LocalPath(path_to_file) => { | |
494 | // Prepend path of working directory onto potentially | |
495 | // relative paths, because they could become relative | |
496 | // to a wrong directory. | |
497 | let working_dir = &self.tcx.sess.working_dir; | |
498 | match working_dir { | |
499 | RealFileName::LocalPath(absolute) => { | |
500 | // If working_dir has not been remapped, then we emit a | |
501 | // LocalPath variant as it's likely to be a valid path | |
502 | RealFileName::LocalPath( | |
503 | Path::new(absolute).join(path_to_file), | |
504 | ) | |
505 | } | |
506 | RealFileName::Remapped { local_path: _, virtual_name } => { | |
507 | // If working_dir has been remapped, then we emit | |
508 | // Remapped variant as the expanded path won't be valid | |
509 | RealFileName::Remapped { | |
510 | local_path: None, | |
511 | virtual_name: Path::new(virtual_name) | |
512 | .join(path_to_file), | |
513 | } | |
514 | } | |
515 | } | |
516 | } | |
517 | RealFileName::Remapped { local_path: _, virtual_name } => { | |
518 | RealFileName::Remapped { | |
519 | // We do not want any local path to be exported into metadata | |
520 | local_path: None, | |
521 | virtual_name: virtual_name.clone(), | |
522 | } | |
523 | } | |
524 | }); | |
a1dfa0c6 | 525 | adapted.name_hash = { |
e74abb32 | 526 | let mut hasher: StableHasher = StableHasher::new(); |
a1dfa0c6 | 527 | adapted.name.hash(&mut hasher); |
e74abb32 | 528 | hasher.finish::<u128>() |
a1dfa0c6 XL |
529 | }; |
530 | Lrc::new(adapted) | |
dfeec247 | 531 | } |
a1dfa0c6 | 532 | |
ff7c6d11 | 533 | // expanded code, not from a file |
b7449926 | 534 | _ => source_file.clone(), |
f035d41b XL |
535 | }; |
536 | ||
537 | // We're serializing this `SourceFile` into our crate metadata, | |
538 | // so mark it as coming from this crate. | |
539 | // This also ensures that we don't try to deserialize the | |
540 | // `CrateNum` for a proc-macro dependency - since proc macro | |
541 | // dependencies aren't loaded when we deserialize a proc-macro, | |
542 | // trying to remap the `CrateNum` would fail. | |
543 | if self.is_proc_macro { | |
544 | Lrc::make_mut(&mut adapted).cnum = LOCAL_CRATE; | |
7cac9316 | 545 | } |
f035d41b | 546 | adapted |
7cac9316 XL |
547 | }) |
548 | .collect::<Vec<_>>(); | |
549 | ||
e1599b0c | 550 | self.lazy(adapted.iter().map(|rc| &**rc)) |
7cac9316 XL |
551 | } |
552 | ||
dc9dc135 | 553 | fn encode_crate_root(&mut self) -> Lazy<CrateRoot<'tcx>> { |
7cac9316 XL |
554 | let mut i = self.position(); |
555 | ||
3dfed10e | 556 | // Encode the crate deps |
dc9dc135 XL |
557 | let crate_deps = self.encode_crate_deps(); |
558 | let dylib_dependency_formats = self.encode_dylib_dependency_formats(); | |
7cac9316 XL |
559 | let dep_bytes = self.position() - i; |
560 | ||
b7449926 XL |
561 | // Encode the lib features. |
562 | i = self.position(); | |
dc9dc135 | 563 | let lib_features = self.encode_lib_features(); |
b7449926 XL |
564 | let lib_feature_bytes = self.position() - i; |
565 | ||
7cac9316 XL |
566 | // Encode the language items. |
567 | i = self.position(); | |
dc9dc135 XL |
568 | let lang_items = self.encode_lang_items(); |
569 | let lang_items_missing = self.encode_lang_items_missing(); | |
7cac9316 XL |
570 | let lang_item_bytes = self.position() - i; |
571 | ||
e1599b0c XL |
572 | // Encode the diagnostic items. |
573 | i = self.position(); | |
574 | let diagnostic_items = self.encode_diagnostic_items(); | |
575 | let diagnostic_item_bytes = self.position() - i; | |
576 | ||
7cac9316 XL |
577 | // Encode the native libraries used |
578 | i = self.position(); | |
dc9dc135 | 579 | let native_libraries = self.encode_native_libraries(); |
7cac9316 XL |
580 | let native_lib_bytes = self.position() - i; |
581 | ||
dc9dc135 | 582 | let foreign_modules = self.encode_foreign_modules(); |
0531ce1d | 583 | |
7cac9316 XL |
584 | // Encode DefPathTable |
585 | i = self.position(); | |
3dfed10e | 586 | self.encode_def_path_table(); |
7cac9316 XL |
587 | let def_path_table_bytes = self.position() - i; |
588 | ||
589 | // Encode the def IDs of impls, for coherence checking. | |
590 | i = self.position(); | |
dc9dc135 | 591 | let impls = self.encode_impls(); |
7cac9316 XL |
592 | let impl_bytes = self.position() - i; |
593 | ||
0531ce1d XL |
594 | let tcx = self.tcx; |
595 | ||
6a06907d XL |
596 | // Encode MIR. |
597 | i = self.position(); | |
598 | self.encode_mir(); | |
599 | let mir_bytes = self.position() - i; | |
600 | ||
0531ce1d | 601 | // Encode the items. |
7cac9316 | 602 | i = self.position(); |
5869c6ff | 603 | self.encode_def_ids(); |
dc9dc135 | 604 | self.encode_info_for_items(); |
7cac9316 XL |
605 | let item_bytes = self.position() - i; |
606 | ||
0531ce1d XL |
607 | // Encode the allocation index |
608 | let interpret_alloc_index = { | |
609 | let mut interpret_alloc_index = Vec::new(); | |
610 | let mut n = 0; | |
611 | trace!("beginning to encode alloc ids"); | |
612 | loop { | |
3dfed10e | 613 | let new_n = self.interpret_allocs.len(); |
0531ce1d XL |
614 | // if we have found new ids, serialize those, too |
615 | if n == new_n { | |
616 | // otherwise, abort | |
617 | break; | |
618 | } | |
619 | trace!("encoding {} further alloc ids", new_n - n); | |
620 | for idx in n..new_n { | |
3dfed10e | 621 | let id = self.interpret_allocs[idx]; |
0531ce1d XL |
622 | let pos = self.position() as u32; |
623 | interpret_alloc_index.push(pos); | |
dfeec247 | 624 | interpret::specialized_encode_alloc_id(self, tcx, id).unwrap(); |
0531ce1d XL |
625 | } |
626 | n = new_n; | |
627 | } | |
e1599b0c | 628 | self.lazy(interpret_alloc_index) |
0531ce1d XL |
629 | }; |
630 | ||
1b1a35ee XL |
631 | // Encode the proc macro data. This affects 'tables', |
632 | // so we need to do this before we encode the tables | |
e1599b0c XL |
633 | i = self.position(); |
634 | let proc_macro_data = self.encode_proc_macros(); | |
635 | let proc_macro_data_bytes = self.position() - i; | |
636 | ||
1b1a35ee XL |
637 | i = self.position(); |
638 | let tables = self.tables.encode(&mut self.opaque); | |
639 | let tables_bytes = self.position() - i; | |
640 | ||
ba9703b0 | 641 | // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode |
3dfed10e | 642 | // this as late as possible to give the prefetching as much time as possible to complete. |
ba9703b0 | 643 | i = self.position(); |
3dfed10e | 644 | let exported_symbols = tcx.exported_symbols(LOCAL_CRATE); |
ba9703b0 XL |
645 | let exported_symbols = self.encode_exported_symbols(&exported_symbols); |
646 | let exported_symbols_bytes = self.position() - i; | |
647 | ||
3dfed10e XL |
648 | // Encode the hygiene data, |
649 | // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The process | |
650 | // of encoding other items (e.g. `optimized_mir`) may cause us to load | |
651 | // data from the incremental cache. If this causes us to deserialize a `Span`, | |
652 | // then we may load additional `SyntaxContext`s into the global `HygieneData`. | |
653 | // Therefore, we need to encode the hygiene data last to ensure that we encode | |
654 | // any `SyntaxContext`s that might be used. | |
655 | i = self.position(); | |
656 | let (syntax_contexts, expn_data) = self.encode_hygiene(); | |
657 | let hygiene_bytes = self.position() - i; | |
658 | ||
f035d41b XL |
659 | // Encode source_map. This needs to be done last, |
660 | // since encoding `Span`s tells us which `SourceFiles` we actually | |
661 | // need to encode. | |
662 | i = self.position(); | |
663 | let source_map = self.encode_source_map(); | |
664 | let source_map_bytes = self.position() - i; | |
665 | ||
0731742a | 666 | let attrs = tcx.hir().krate_attrs(); |
3dfed10e | 667 | let has_default_lib_allocator = tcx.sess.contains_name(&attrs, sym::default_lib_allocator); |
0531ce1d | 668 | |
e1599b0c | 669 | let root = self.lazy(CrateRoot { |
7cac9316 | 670 | name: tcx.crate_name(LOCAL_CRATE), |
83c7162d | 671 | extra_filename: tcx.sess.opts.cg.extra_filename.clone(), |
7cac9316 | 672 | triple: tcx.sess.opts.target_triple.clone(), |
b7449926 | 673 | hash: tcx.crate_hash(LOCAL_CRATE), |
7cac9316 | 674 | disambiguator: tcx.sess.local_crate_disambiguator(), |
6a06907d | 675 | stable_crate_id: tcx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(), |
ea8adc8c | 676 | panic_strategy: tcx.sess.panic_strategy(), |
dc9dc135 | 677 | edition: tcx.sess.edition(), |
60c5eb7d XL |
678 | has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE), |
679 | has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE), | |
74b04a01 | 680 | has_default_lib_allocator, |
e1599b0c | 681 | proc_macro_data, |
3dfed10e XL |
682 | compiler_builtins: tcx.sess.contains_name(&attrs, sym::compiler_builtins), |
683 | needs_allocator: tcx.sess.contains_name(&attrs, sym::needs_allocator), | |
684 | needs_panic_runtime: tcx.sess.contains_name(&attrs, sym::needs_panic_runtime), | |
685 | no_builtins: tcx.sess.contains_name(&attrs, sym::no_builtins), | |
686 | panic_runtime: tcx.sess.contains_name(&attrs, sym::panic_runtime), | |
687 | profiler_runtime: tcx.sess.contains_name(&attrs, sym::profiler_runtime), | |
fc512014 | 688 | symbol_mangling_version: tcx.sess.opts.debugging_opts.get_symbol_mangling_version(), |
94b46f34 | 689 | |
3b2f2976 XL |
690 | crate_deps, |
691 | dylib_dependency_formats, | |
b7449926 | 692 | lib_features, |
3b2f2976 | 693 | lang_items, |
e1599b0c | 694 | diagnostic_items, |
3b2f2976 XL |
695 | lang_items_missing, |
696 | native_libraries, | |
0531ce1d | 697 | foreign_modules, |
b7449926 | 698 | source_map, |
3b2f2976 XL |
699 | impls, |
700 | exported_symbols, | |
0531ce1d | 701 | interpret_alloc_index, |
ba9703b0 | 702 | tables, |
3dfed10e XL |
703 | syntax_contexts, |
704 | expn_data, | |
7cac9316 XL |
705 | }); |
706 | ||
707 | let total_bytes = self.position(); | |
708 | ||
3dfed10e | 709 | if tcx.sess.meta_stats() { |
7cac9316 | 710 | let mut zero_bytes = 0; |
8faf50e0 | 711 | for e in self.opaque.data.iter() { |
7cac9316 XL |
712 | if *e == 0 { |
713 | zero_bytes += 1; | |
714 | } | |
715 | } | |
716 | ||
6a06907d XL |
717 | eprintln!("metadata stats:"); |
718 | eprintln!(" dep bytes: {}", dep_bytes); | |
719 | eprintln!(" lib feature bytes: {}", lib_feature_bytes); | |
720 | eprintln!(" lang item bytes: {}", lang_item_bytes); | |
721 | eprintln!(" diagnostic item bytes: {}", diagnostic_item_bytes); | |
722 | eprintln!(" native bytes: {}", native_lib_bytes); | |
723 | eprintln!(" source_map bytes: {}", source_map_bytes); | |
724 | eprintln!(" impl bytes: {}", impl_bytes); | |
725 | eprintln!(" exp. symbols bytes: {}", exported_symbols_bytes); | |
726 | eprintln!(" def-path table bytes: {}", def_path_table_bytes); | |
727 | eprintln!(" proc-macro-data-bytes: {}", proc_macro_data_bytes); | |
728 | eprintln!(" mir bytes: {}", mir_bytes); | |
729 | eprintln!(" item bytes: {}", item_bytes); | |
730 | eprintln!(" table bytes: {}", tables_bytes); | |
731 | eprintln!(" hygiene bytes: {}", hygiene_bytes); | |
732 | eprintln!(" zero bytes: {}", zero_bytes); | |
733 | eprintln!(" total bytes: {}", total_bytes); | |
7cac9316 XL |
734 | } |
735 | ||
736 | root | |
737 | } | |
cc61c64b | 738 | } |
1a4d82fc | 739 | |
5869c6ff XL |
740 | fn should_encode_visibility(def_kind: DefKind) -> bool { |
741 | match def_kind { | |
742 | DefKind::Mod | |
743 | | DefKind::Struct | |
744 | | DefKind::Union | |
745 | | DefKind::Enum | |
746 | | DefKind::Variant | |
747 | | DefKind::Trait | |
748 | | DefKind::TyAlias | |
749 | | DefKind::ForeignTy | |
750 | | DefKind::TraitAlias | |
751 | | DefKind::AssocTy | |
752 | | DefKind::Fn | |
753 | | DefKind::Const | |
754 | | DefKind::Static | |
755 | | DefKind::Ctor(..) | |
756 | | DefKind::AssocFn | |
757 | | DefKind::AssocConst | |
758 | | DefKind::Macro(..) | |
759 | | DefKind::Use | |
760 | | DefKind::ForeignMod | |
761 | | DefKind::OpaqueTy | |
762 | | DefKind::Impl | |
763 | | DefKind::Field => true, | |
764 | DefKind::TyParam | |
765 | | DefKind::ConstParam | |
766 | | DefKind::LifetimeParam | |
767 | | DefKind::AnonConst | |
768 | | DefKind::GlobalAsm | |
769 | | DefKind::Closure | |
770 | | DefKind::Generator | |
771 | | DefKind::ExternCrate => false, | |
772 | } | |
773 | } | |
774 | ||
775 | fn should_encode_stability(def_kind: DefKind) -> bool { | |
776 | match def_kind { | |
777 | DefKind::Mod | |
778 | | DefKind::Ctor(..) | |
779 | | DefKind::Variant | |
780 | | DefKind::Field | |
781 | | DefKind::Struct | |
782 | | DefKind::AssocTy | |
783 | | DefKind::AssocFn | |
784 | | DefKind::AssocConst | |
785 | | DefKind::TyParam | |
786 | | DefKind::ConstParam | |
787 | | DefKind::Static | |
788 | | DefKind::Const | |
789 | | DefKind::Fn | |
790 | | DefKind::ForeignMod | |
791 | | DefKind::TyAlias | |
792 | | DefKind::OpaqueTy | |
793 | | DefKind::Enum | |
794 | | DefKind::Union | |
795 | | DefKind::Impl | |
796 | | DefKind::Trait | |
797 | | DefKind::TraitAlias | |
798 | | DefKind::Macro(..) | |
799 | | DefKind::ForeignTy => true, | |
800 | DefKind::Use | |
801 | | DefKind::LifetimeParam | |
802 | | DefKind::AnonConst | |
803 | | DefKind::GlobalAsm | |
804 | | DefKind::Closure | |
805 | | DefKind::Generator | |
806 | | DefKind::ExternCrate => false, | |
807 | } | |
808 | } | |
809 | ||
810 | /// Whether we should encode MIR. | |
811 | /// | |
812 | /// Computing, optimizing and encoding the MIR is a relatively expensive operation. | |
813 | /// We want to avoid this work when not required. Therefore: | |
814 | /// - we only compute `mir_for_ctfe` on items with const-eval semantics; | |
815 | /// - we skip `optimized_mir` for check runs. | |
816 | /// | |
817 | /// Return a pair, resp. for CTFE and for LLVM. | |
818 | fn should_encode_mir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> (bool, bool) { | |
819 | match tcx.def_kind(def_id) { | |
820 | // Constructors | |
821 | DefKind::Ctor(_, _) => { | |
822 | let mir_opt_base = tcx.sess.opts.output_types.should_codegen() | |
823 | || tcx.sess.opts.debugging_opts.always_encode_mir; | |
824 | (true, mir_opt_base) | |
825 | } | |
826 | // Constants | |
827 | DefKind::AnonConst | DefKind::AssocConst | DefKind::Static | DefKind::Const => { | |
828 | (true, false) | |
829 | } | |
830 | // Full-fledged functions | |
831 | DefKind::AssocFn | DefKind::Fn => { | |
832 | let generics = tcx.generics_of(def_id); | |
833 | let needs_inline = (generics.requires_monomorphization(tcx) | |
834 | || tcx.codegen_fn_attrs(def_id).requests_inline()) | |
835 | && tcx.sess.opts.output_types.should_codegen(); | |
836 | // Only check the presence of the `const` modifier. | |
837 | let is_const_fn = tcx.is_const_fn_raw(def_id.to_def_id()); | |
838 | let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir; | |
839 | (is_const_fn, needs_inline || always_encode_mir) | |
840 | } | |
841 | // Closures can't be const fn. | |
842 | DefKind::Closure => { | |
843 | let generics = tcx.generics_of(def_id); | |
844 | let needs_inline = (generics.requires_monomorphization(tcx) | |
845 | || tcx.codegen_fn_attrs(def_id).requests_inline()) | |
846 | && tcx.sess.opts.output_types.should_codegen(); | |
847 | let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir; | |
848 | (false, needs_inline || always_encode_mir) | |
849 | } | |
850 | // Generators require optimized MIR to compute layout. | |
851 | DefKind::Generator => (false, true), | |
852 | // The others don't have MIR. | |
853 | _ => (false, false), | |
854 | } | |
855 | } | |
856 | ||
6a06907d XL |
857 | fn should_encode_variances(def_kind: DefKind) -> bool { |
858 | match def_kind { | |
859 | DefKind::Struct | |
860 | | DefKind::Union | |
861 | | DefKind::Enum | |
862 | | DefKind::Variant | |
863 | | DefKind::Fn | |
864 | | DefKind::Ctor(..) | |
865 | | DefKind::AssocFn => true, | |
866 | DefKind::Mod | |
867 | | DefKind::Field | |
868 | | DefKind::AssocTy | |
869 | | DefKind::AssocConst | |
870 | | DefKind::TyParam | |
871 | | DefKind::ConstParam | |
872 | | DefKind::Static | |
873 | | DefKind::Const | |
874 | | DefKind::ForeignMod | |
875 | | DefKind::TyAlias | |
876 | | DefKind::OpaqueTy | |
877 | | DefKind::Impl | |
878 | | DefKind::Trait | |
879 | | DefKind::TraitAlias | |
880 | | DefKind::Macro(..) | |
881 | | DefKind::ForeignTy | |
882 | | DefKind::Use | |
883 | | DefKind::LifetimeParam | |
884 | | DefKind::AnonConst | |
885 | | DefKind::GlobalAsm | |
886 | | DefKind::Closure | |
887 | | DefKind::Generator | |
888 | | DefKind::ExternCrate => false, | |
889 | } | |
890 | } | |
891 | ||
892 | fn should_encode_generics(def_kind: DefKind) -> bool { | |
893 | match def_kind { | |
894 | DefKind::Struct | |
895 | | DefKind::Union | |
896 | | DefKind::Enum | |
897 | | DefKind::Variant | |
898 | | DefKind::Trait | |
899 | | DefKind::TyAlias | |
900 | | DefKind::ForeignTy | |
901 | | DefKind::TraitAlias | |
902 | | DefKind::AssocTy | |
903 | | DefKind::Fn | |
904 | | DefKind::Const | |
905 | | DefKind::Static | |
906 | | DefKind::Ctor(..) | |
907 | | DefKind::AssocFn | |
908 | | DefKind::AssocConst | |
909 | | DefKind::AnonConst | |
910 | | DefKind::OpaqueTy | |
911 | | DefKind::Impl | |
912 | | DefKind::Closure | |
913 | | DefKind::Generator => true, | |
914 | DefKind::Mod | |
915 | | DefKind::Field | |
916 | | DefKind::ForeignMod | |
917 | | DefKind::TyParam | |
918 | | DefKind::ConstParam | |
919 | | DefKind::Macro(..) | |
920 | | DefKind::Use | |
921 | | DefKind::LifetimeParam | |
922 | | DefKind::GlobalAsm | |
923 | | DefKind::ExternCrate => false, | |
924 | } | |
925 | } | |
926 | ||
3dfed10e | 927 | impl EncodeContext<'a, 'tcx> { |
5869c6ff XL |
928 | fn encode_def_ids(&mut self) { |
929 | if self.is_proc_macro { | |
930 | return; | |
931 | } | |
932 | let tcx = self.tcx; | |
933 | let hir = tcx.hir(); | |
934 | for local_id in hir.iter_local_def_id() { | |
935 | let def_id = local_id.to_def_id(); | |
936 | let def_kind = tcx.opt_def_kind(local_id); | |
937 | let def_kind = if let Some(def_kind) = def_kind { def_kind } else { continue }; | |
938 | record!(self.tables.def_kind[def_id] <- match def_kind { | |
939 | // Replace Ctor by the enclosing object to avoid leaking details in children crates. | |
940 | DefKind::Ctor(CtorOf::Struct, _) => DefKind::Struct, | |
941 | DefKind::Ctor(CtorOf::Variant, _) => DefKind::Variant, | |
942 | def_kind => def_kind, | |
943 | }); | |
944 | record!(self.tables.span[def_id] <- tcx.def_span(def_id)); | |
945 | record!(self.tables.attributes[def_id] <- tcx.get_attrs(def_id)); | |
17df50a5 | 946 | record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id)); |
5869c6ff XL |
947 | if should_encode_visibility(def_kind) { |
948 | record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id)); | |
949 | } | |
950 | if should_encode_stability(def_kind) { | |
951 | self.encode_stability(def_id); | |
952 | self.encode_const_stability(def_id); | |
953 | self.encode_deprecation(def_id); | |
954 | } | |
6a06907d XL |
955 | if should_encode_variances(def_kind) { |
956 | let v = self.tcx.variances_of(def_id); | |
957 | record!(self.tables.variances[def_id] <- v); | |
958 | } | |
959 | if should_encode_generics(def_kind) { | |
960 | let g = tcx.generics_of(def_id); | |
961 | record!(self.tables.generics[def_id] <- g); | |
962 | record!(self.tables.explicit_predicates[def_id] <- self.tcx.explicit_predicates_of(def_id)); | |
963 | let inferred_outlives = self.tcx.inferred_outlives_of(def_id); | |
964 | if !inferred_outlives.is_empty() { | |
965 | record!(self.tables.inferred_outlives[def_id] <- inferred_outlives); | |
966 | } | |
967 | } | |
968 | if let DefKind::Trait | DefKind::TraitAlias = def_kind { | |
969 | record!(self.tables.super_predicates[def_id] <- self.tcx.super_predicates_of(def_id)); | |
970 | } | |
971 | } | |
17df50a5 | 972 | let inherent_impls = tcx.crate_inherent_impls(()); |
6a06907d | 973 | for (def_id, implementations) in inherent_impls.inherent_impls.iter() { |
6a06907d XL |
974 | if implementations.is_empty() { |
975 | continue; | |
976 | } | |
17df50a5 | 977 | record!(self.tables.inherent_impls[def_id.to_def_id()] <- implementations.iter().map(|&def_id| { |
6a06907d XL |
978 | assert!(def_id.is_local()); |
979 | def_id.index | |
980 | })); | |
5869c6ff | 981 | } |
223e47cc | 982 | } |
970d7e83 | 983 | |
e74abb32 XL |
984 | fn encode_item_type(&mut self, def_id: DefId) { |
985 | debug!("EncodeContext::encode_item_type({:?})", def_id); | |
ba9703b0 | 986 | record!(self.tables.ty[def_id] <- self.tcx.type_of(def_id)); |
970d7e83 LB |
987 | } |
988 | ||
f9f354fc | 989 | fn encode_enum_variant_info(&mut self, def: &ty::AdtDef, index: VariantIdx) { |
9e0c209e | 990 | let tcx = self.tcx; |
9e0c209e | 991 | let variant = &def.variants[index]; |
532ac7d7 | 992 | let def_id = variant.def_id; |
dc9dc135 | 993 | debug!("EncodeContext::encode_enum_variant_info({:?})", def_id); |
9e0c209e SL |
994 | |
995 | let data = VariantData { | |
c30ab7b3 | 996 | ctor_kind: variant.ctor_kind, |
8bb4bdeb | 997 | discr: variant.discr, |
532ac7d7 | 998 | ctor: variant.ctor_def_id.map(|did| did.index), |
3dfed10e | 999 | is_non_exhaustive: variant.is_field_list_non_exhaustive(), |
9e0c209e | 1000 | }; |
970d7e83 | 1001 | |
ba9703b0 | 1002 | record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data))); |
ba9703b0 | 1003 | record!(self.tables.children[def_id] <- variant.fields.iter().map(|f| { |
e74abb32 XL |
1004 | assert!(f.did.is_local()); |
1005 | f.did.index | |
1006 | })); | |
ba9703b0 | 1007 | self.encode_ident_span(def_id, variant.ident); |
e74abb32 XL |
1008 | self.encode_item_type(def_id); |
1009 | if variant.ctor_kind == CtorKind::Fn { | |
1010 | // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`. | |
1011 | if let Some(ctor_def_id) = variant.ctor_def_id { | |
ba9703b0 | 1012 | record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id)); |
e74abb32 | 1013 | } |
9e0c209e | 1014 | } |
970d7e83 | 1015 | } |
223e47cc | 1016 | |
f9f354fc | 1017 | fn encode_enum_variant_ctor(&mut self, def: &ty::AdtDef, index: VariantIdx) { |
532ac7d7 | 1018 | let tcx = self.tcx; |
532ac7d7 XL |
1019 | let variant = &def.variants[index]; |
1020 | let def_id = variant.ctor_def_id.unwrap(); | |
dc9dc135 | 1021 | debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id); |
532ac7d7 | 1022 | |
e74abb32 | 1023 | // FIXME(eddyb) encode only the `CtorKind` for constructors. |
532ac7d7 XL |
1024 | let data = VariantData { |
1025 | ctor_kind: variant.ctor_kind, | |
1026 | discr: variant.discr, | |
1027 | ctor: Some(def_id.index), | |
3dfed10e | 1028 | is_non_exhaustive: variant.is_field_list_non_exhaustive(), |
532ac7d7 XL |
1029 | }; |
1030 | ||
ba9703b0 | 1031 | record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data))); |
e74abb32 XL |
1032 | self.encode_item_type(def_id); |
1033 | if variant.ctor_kind == CtorKind::Fn { | |
ba9703b0 | 1034 | record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); |
532ac7d7 XL |
1035 | } |
1036 | } | |
1037 | ||
6a06907d | 1038 | fn encode_info_for_mod(&mut self, local_def_id: LocalDefId, md: &hir::Mod<'_>) { |
9e0c209e | 1039 | let tcx = self.tcx; |
3dfed10e | 1040 | let def_id = local_def_id.to_def_id(); |
dc9dc135 | 1041 | debug!("EncodeContext::encode_info_for_mod({:?})", def_id); |
9e0c209e | 1042 | |
1b1a35ee XL |
1043 | // If we are encoding a proc-macro crates, `encode_info_for_mod` will |
1044 | // only ever get called for the crate root. We still want to encode | |
1045 | // the crate root for consistency with other crates (some of the resolver | |
1046 | // code uses it). However, we skip encoding anything relating to child | |
1047 | // items - we encode information about proc-macros later on. | |
1048 | let reexports = if !self.is_proc_macro { | |
1049 | match tcx.module_exports(local_def_id) { | |
f035d41b | 1050 | Some(exports) => { |
3dfed10e | 1051 | let hir = self.tcx.hir(); |
f035d41b XL |
1052 | self.lazy( |
1053 | exports | |
1054 | .iter() | |
3dfed10e | 1055 | .map(|export| export.map_id(|id| hir.local_def_id_to_hir_id(id))), |
f035d41b XL |
1056 | ) |
1057 | } | |
e1599b0c | 1058 | _ => Lazy::empty(), |
1b1a35ee XL |
1059 | } |
1060 | } else { | |
1061 | Lazy::empty() | |
1062 | }; | |
1063 | ||
1064 | let data = ModData { | |
1065 | reexports, | |
3dfed10e | 1066 | expansion: tcx.hir().definitions().expansion_that_defined(local_def_id), |
9e0c209e | 1067 | }; |
223e47cc | 1068 | |
ba9703b0 | 1069 | record!(self.tables.kind[def_id] <- EntryKind::Mod(self.lazy(data))); |
1b1a35ee XL |
1070 | if self.is_proc_macro { |
1071 | record!(self.tables.children[def_id] <- &[]); | |
1072 | } else { | |
1073 | record!(self.tables.children[def_id] <- md.item_ids.iter().map(|item_id| { | |
6a06907d | 1074 | item_id.def_id.local_def_index |
1b1a35ee XL |
1075 | })); |
1076 | } | |
9e0c209e | 1077 | } |
223e47cc | 1078 | |
f9f354fc XL |
1079 | fn encode_field( |
1080 | &mut self, | |
1081 | adt_def: &ty::AdtDef, | |
1082 | variant_index: VariantIdx, | |
1083 | field_index: usize, | |
1084 | ) { | |
f9f354fc | 1085 | let variant = &adt_def.variants[variant_index]; |
9e0c209e SL |
1086 | let field = &variant.fields[field_index]; |
1087 | ||
1088 | let def_id = field.did; | |
dc9dc135 | 1089 | debug!("EncodeContext::encode_field({:?})", def_id); |
cc61c64b | 1090 | |
ba9703b0 | 1091 | record!(self.tables.kind[def_id] <- EntryKind::Field); |
ba9703b0 | 1092 | self.encode_ident_span(def_id, field.ident); |
e74abb32 | 1093 | self.encode_item_type(def_id); |
223e47cc | 1094 | } |
223e47cc | 1095 | |
f9f354fc | 1096 | fn encode_struct_ctor(&mut self, adt_def: &ty::AdtDef, def_id: DefId) { |
dc9dc135 | 1097 | debug!("EncodeContext::encode_struct_ctor({:?})", def_id); |
c30ab7b3 | 1098 | let tcx = self.tcx; |
2c00a5a8 | 1099 | let variant = adt_def.non_enum_variant(); |
1a4d82fc | 1100 | |
9e0c209e | 1101 | let data = VariantData { |
c30ab7b3 | 1102 | ctor_kind: variant.ctor_kind, |
8bb4bdeb | 1103 | discr: variant.discr, |
532ac7d7 | 1104 | ctor: Some(def_id.index), |
3dfed10e | 1105 | is_non_exhaustive: variant.is_field_list_non_exhaustive(), |
9e0c209e | 1106 | }; |
223e47cc | 1107 | |
ba9703b0 | 1108 | record!(self.tables.kind[def_id] <- EntryKind::Struct(self.lazy(data), adt_def.repr)); |
e74abb32 XL |
1109 | self.encode_item_type(def_id); |
1110 | if variant.ctor_kind == CtorKind::Fn { | |
ba9703b0 | 1111 | record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); |
9e0c209e | 1112 | } |
e74abb32 XL |
1113 | } |
1114 | ||
29967ef6 XL |
1115 | fn encode_explicit_item_bounds(&mut self, def_id: DefId) { |
1116 | debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id); | |
1117 | let bounds = self.tcx.explicit_item_bounds(def_id); | |
1118 | if !bounds.is_empty() { | |
1119 | record!(self.tables.explicit_item_bounds[def_id] <- bounds); | |
1120 | } | |
1121 | } | |
1122 | ||
e74abb32 | 1123 | fn encode_info_for_trait_item(&mut self, def_id: DefId) { |
dc9dc135 | 1124 | debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id); |
9e0c209e | 1125 | let tcx = self.tcx; |
c34b1796 | 1126 | |
3dfed10e | 1127 | let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local()); |
532ac7d7 | 1128 | let ast_item = tcx.hir().expect_trait_item(hir_id); |
476ff2be SL |
1129 | let trait_item = tcx.associated_item(def_id); |
1130 | ||
1131 | let container = match trait_item.defaultness { | |
dfeec247 XL |
1132 | hir::Defaultness::Default { has_value: true } => AssocContainer::TraitWithDefault, |
1133 | hir::Defaultness::Default { has_value: false } => AssocContainer::TraitRequired, | |
1134 | hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"), | |
b039eaaf | 1135 | }; |
1a4d82fc | 1136 | |
5869c6ff | 1137 | match trait_item.kind { |
dc9dc135 | 1138 | ty::AssocKind::Const => { |
ba9703b0 XL |
1139 | let rendered = rustc_hir_pretty::to_string( |
1140 | &(&self.tcx.hir() as &dyn intravisit::Map<'_>), | |
5869c6ff | 1141 | |s| s.print_trait_item(ast_item), |
ba9703b0 | 1142 | ); |
e1599b0c | 1143 | let rendered_const = self.lazy(RenderedConst(rendered)); |
83c7162d | 1144 | |
5869c6ff | 1145 | record!(self.tables.kind[def_id] <- EntryKind::AssocConst( |
60c5eb7d XL |
1146 | container, |
1147 | Default::default(), | |
1148 | rendered_const, | |
5869c6ff | 1149 | )); |
8bb4bdeb | 1150 | } |
ba9703b0 XL |
1151 | ty::AssocKind::Fn => { |
1152 | let fn_data = if let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind { | |
e1599b0c | 1153 | let param_names = match *m { |
5869c6ff XL |
1154 | hir::TraitFn::Required(ref names) => self.encode_fn_param_names(names), |
1155 | hir::TraitFn::Provided(body) => self.encode_fn_param_names_for_body(body), | |
32a655c1 | 1156 | }; |
9e0c209e | 1157 | FnData { |
e74abb32 | 1158 | asyncness: m_sig.header.asyncness, |
9e0c209e | 1159 | constness: hir::Constness::NotConst, |
e1599b0c | 1160 | param_names, |
9e0c209e SL |
1161 | } |
1162 | } else { | |
1163 | bug!() | |
1164 | }; | |
5869c6ff | 1165 | record!(self.tables.kind[def_id] <- EntryKind::AssocFn(self.lazy(AssocFnData { |
3b2f2976 XL |
1166 | fn_data, |
1167 | container, | |
ba9703b0 | 1168 | has_self: trait_item.fn_has_self_parameter, |
5869c6ff | 1169 | }))); |
9e0c209e | 1170 | } |
29967ef6 XL |
1171 | ty::AssocKind::Type => { |
1172 | self.encode_explicit_item_bounds(def_id); | |
5869c6ff | 1173 | record!(self.tables.kind[def_id] <- EntryKind::AssocType(container)); |
29967ef6 | 1174 | } |
5869c6ff | 1175 | } |
ba9703b0 | 1176 | self.encode_ident_span(def_id, ast_item.ident); |
e74abb32 | 1177 | match trait_item.kind { |
ba9703b0 | 1178 | ty::AssocKind::Const | ty::AssocKind::Fn => { |
e74abb32 XL |
1179 | self.encode_item_type(def_id); |
1180 | } | |
1181 | ty::AssocKind::Type => { | |
1182 | if trait_item.defaultness.has_value() { | |
1183 | self.encode_item_type(def_id); | |
9e0c209e | 1184 | } |
e74abb32 | 1185 | } |
e74abb32 | 1186 | } |
ba9703b0 XL |
1187 | if trait_item.kind == ty::AssocKind::Fn { |
1188 | record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); | |
1a4d82fc | 1189 | } |
83c7162d XL |
1190 | } |
1191 | ||
e74abb32 | 1192 | fn encode_info_for_impl_item(&mut self, def_id: DefId) { |
dc9dc135 | 1193 | debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id); |
041b39d2 XL |
1194 | let tcx = self.tcx; |
1195 | ||
3dfed10e | 1196 | let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local()); |
532ac7d7 | 1197 | let ast_item = self.tcx.hir().expect_impl_item(hir_id); |
476ff2be | 1198 | let impl_item = self.tcx.associated_item(def_id); |
d9579d0f | 1199 | |
476ff2be | 1200 | let container = match impl_item.defaultness { |
dc9dc135 XL |
1201 | hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault, |
1202 | hir::Defaultness::Final => AssocContainer::ImplFinal, | |
dfeec247 XL |
1203 | hir::Defaultness::Default { has_value: false } => { |
1204 | span_bug!(ast_item.span, "impl items always have values (currently)") | |
1205 | } | |
9e0c209e | 1206 | }; |
d9579d0f | 1207 | |
5869c6ff | 1208 | match impl_item.kind { |
dc9dc135 | 1209 | ty::AssocKind::Const => { |
e74abb32 | 1210 | if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind { |
60c5eb7d | 1211 | let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id); |
83c7162d | 1212 | |
5869c6ff | 1213 | record!(self.tables.kind[def_id] <- EntryKind::AssocConst( |
60c5eb7d XL |
1214 | container, |
1215 | qualifs, | |
83c7162d | 1216 | self.encode_rendered_const_for_body(body_id)) |
5869c6ff | 1217 | ); |
83c7162d XL |
1218 | } else { |
1219 | bug!() | |
1220 | } | |
8bb4bdeb | 1221 | } |
ba9703b0 XL |
1222 | ty::AssocKind::Fn => { |
1223 | let fn_data = if let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind { | |
9e0c209e | 1224 | FnData { |
e1599b0c | 1225 | asyncness: sig.header.asyncness, |
8faf50e0 | 1226 | constness: sig.header.constness, |
e1599b0c | 1227 | param_names: self.encode_fn_param_names_for_body(body), |
9e0c209e SL |
1228 | } |
1229 | } else { | |
1230 | bug!() | |
1231 | }; | |
5869c6ff | 1232 | record!(self.tables.kind[def_id] <- EntryKind::AssocFn(self.lazy(AssocFnData { |
3b2f2976 XL |
1233 | fn_data, |
1234 | container, | |
ba9703b0 | 1235 | has_self: impl_item.fn_has_self_parameter, |
5869c6ff | 1236 | }))); |
9e0c209e | 1237 | } |
5869c6ff XL |
1238 | ty::AssocKind::Type => { |
1239 | record!(self.tables.kind[def_id] <- EntryKind::AssocType(container)); | |
1240 | } | |
1241 | } | |
ba9703b0 | 1242 | self.encode_ident_span(def_id, impl_item.ident); |
e74abb32 | 1243 | self.encode_item_type(def_id); |
ba9703b0 XL |
1244 | if impl_item.kind == ty::AssocKind::Fn { |
1245 | record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); | |
e74abb32 | 1246 | } |
223e47cc | 1247 | } |
1a4d82fc | 1248 | |
f035d41b | 1249 | fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId) -> Lazy<[Ident]> { |
3dfed10e | 1250 | self.lazy(self.tcx.hir().body_param_names(body_id)) |
1a4d82fc | 1251 | } |
1a4d82fc | 1252 | |
f035d41b XL |
1253 | fn encode_fn_param_names(&mut self, param_names: &[Ident]) -> Lazy<[Ident]> { |
1254 | self.lazy(param_names.iter()) | |
32a655c1 SL |
1255 | } |
1256 | ||
5869c6ff XL |
1257 | fn encode_mir(&mut self) { |
1258 | if self.is_proc_macro { | |
1259 | return; | |
1260 | } | |
3dfed10e | 1261 | |
5869c6ff XL |
1262 | let mut keys_and_jobs = self |
1263 | .tcx | |
17df50a5 | 1264 | .mir_keys(()) |
5869c6ff XL |
1265 | .iter() |
1266 | .filter_map(|&def_id| { | |
1267 | let (encode_const, encode_opt) = should_encode_mir(self.tcx, def_id); | |
1268 | if encode_const || encode_opt { | |
1269 | Some((def_id, encode_const, encode_opt)) | |
1270 | } else { | |
1271 | None | |
1272 | } | |
1273 | }) | |
1274 | .collect::<Vec<_>>(); | |
1275 | // Sort everything to ensure a stable order for diagnotics. | |
1276 | keys_and_jobs.sort_by_key(|&(def_id, _, _)| def_id); | |
1277 | for (def_id, encode_const, encode_opt) in keys_and_jobs.into_iter() { | |
1278 | debug_assert!(encode_const || encode_opt); | |
1279 | ||
1280 | debug!("EntryBuilder::encode_mir({:?})", def_id); | |
1281 | if encode_opt { | |
1282 | record!(self.tables.mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id)); | |
3dfed10e | 1283 | } |
5869c6ff XL |
1284 | if encode_const { |
1285 | record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- self.tcx.mir_for_ctfe(def_id)); | |
1b1a35ee | 1286 | |
5869c6ff XL |
1287 | let abstract_const = self.tcx.mir_abstract_const(def_id); |
1288 | if let Ok(Some(abstract_const)) = abstract_const { | |
1289 | record!(self.tables.mir_abstract_consts[def_id.to_def_id()] <- abstract_const); | |
1290 | } | |
1b1a35ee | 1291 | } |
f9f354fc | 1292 | record!(self.tables.promoted_mir[def_id.to_def_id()] <- self.tcx.promoted_mir(def_id)); |
5869c6ff XL |
1293 | |
1294 | let unused = self.tcx.unused_generic_params(def_id); | |
1295 | if !unused.is_empty() { | |
1296 | record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused); | |
1297 | } | |
7cac9316 | 1298 | } |
9cc50fc6 | 1299 | } |
223e47cc | 1300 | |
e74abb32 | 1301 | fn encode_stability(&mut self, def_id: DefId) { |
dc9dc135 | 1302 | debug!("EncodeContext::encode_stability({:?})", def_id); |
1b1a35ee XL |
1303 | |
1304 | // The query lookup can take a measurable amount of time in crates with many items. Check if | |
1305 | // the stability attributes are even enabled before using their queries. | |
1306 | if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked { | |
1307 | if let Some(stab) = self.tcx.lookup_stability(def_id) { | |
1308 | record!(self.tables.stability[def_id] <- stab) | |
1309 | } | |
e74abb32 | 1310 | } |
9e0c209e | 1311 | } |
1a4d82fc | 1312 | |
60c5eb7d XL |
1313 | fn encode_const_stability(&mut self, def_id: DefId) { |
1314 | debug!("EncodeContext::encode_const_stability({:?})", def_id); | |
1b1a35ee XL |
1315 | |
1316 | // The query lookup can take a measurable amount of time in crates with many items. Check if | |
1317 | // the stability attributes are even enabled before using their queries. | |
1318 | if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked { | |
1319 | if let Some(stab) = self.tcx.lookup_const_stability(def_id) { | |
1320 | record!(self.tables.const_stability[def_id] <- stab) | |
1321 | } | |
60c5eb7d XL |
1322 | } |
1323 | } | |
1324 | ||
e74abb32 | 1325 | fn encode_deprecation(&mut self, def_id: DefId) { |
dc9dc135 | 1326 | debug!("EncodeContext::encode_deprecation({:?})", def_id); |
e74abb32 | 1327 | if let Some(depr) = self.tcx.lookup_deprecation(def_id) { |
ba9703b0 | 1328 | record!(self.tables.deprecation[def_id] <- depr); |
e74abb32 | 1329 | } |
9e0c209e | 1330 | } |
9cc50fc6 | 1331 | |
83c7162d | 1332 | fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> { |
ba9703b0 XL |
1333 | let hir = self.tcx.hir(); |
1334 | let body = hir.body(body_id); | |
1335 | let rendered = rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| { | |
1336 | s.print_expr(&body.value) | |
1337 | }); | |
83c7162d XL |
1338 | let rendered_const = &RenderedConst(rendered); |
1339 | self.lazy(rendered_const) | |
1340 | } | |
1341 | ||
dfeec247 | 1342 | fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) { |
9e0c209e SL |
1343 | let tcx = self.tcx; |
1344 | ||
dc9dc135 | 1345 | debug!("EncodeContext::encode_info_for_item({:?})", def_id); |
9e0c209e | 1346 | |
ba9703b0 XL |
1347 | self.encode_ident_span(def_id, item.ident); |
1348 | ||
5869c6ff | 1349 | let entry_kind = match item.kind { |
dfeec247 XL |
1350 | hir::ItemKind::Static(_, hir::Mutability::Mut, _) => EntryKind::MutStatic, |
1351 | hir::ItemKind::Static(_, hir::Mutability::Not, _) => EntryKind::ImmStatic, | |
8faf50e0 | 1352 | hir::ItemKind::Const(_, body_id) => { |
60c5eb7d | 1353 | let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id); |
5869c6ff | 1354 | EntryKind::Const(qualifs, self.encode_rendered_const_for_body(body_id)) |
8bb4bdeb | 1355 | } |
60c5eb7d | 1356 | hir::ItemKind::Fn(ref sig, .., body) => { |
9e0c209e | 1357 | let data = FnData { |
60c5eb7d XL |
1358 | asyncness: sig.header.asyncness, |
1359 | constness: sig.header.constness, | |
e1599b0c | 1360 | param_names: self.encode_fn_param_names_for_body(body), |
9e0c209e | 1361 | }; |
54a0048b | 1362 | |
e1599b0c | 1363 | EntryKind::Fn(self.lazy(data)) |
b039eaaf | 1364 | } |
8faf50e0 | 1365 | hir::ItemKind::Mod(ref m) => { |
6a06907d | 1366 | return self.encode_info_for_mod(item.def_id, m); |
9e0c209e | 1367 | } |
fc512014 | 1368 | hir::ItemKind::ForeignMod { .. } => EntryKind::ForeignMod, |
8faf50e0 | 1369 | hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm, |
416331ca | 1370 | hir::ItemKind::TyAlias(..) => EntryKind::Type, |
29967ef6 XL |
1371 | hir::ItemKind::OpaqueTy(..) => { |
1372 | self.encode_explicit_item_bounds(def_id); | |
1373 | EntryKind::OpaqueTy | |
1374 | } | |
e74abb32 | 1375 | hir::ItemKind::Enum(..) => EntryKind::Enum(self.tcx.adt_def(def_id).repr), |
8faf50e0 | 1376 | hir::ItemKind::Struct(ref struct_def, _) => { |
e74abb32 XL |
1377 | let adt_def = self.tcx.adt_def(def_id); |
1378 | let variant = adt_def.non_enum_variant(); | |
9e0c209e | 1379 | |
c30ab7b3 SL |
1380 | // Encode def_ids for each field and method |
1381 | // for methods, write all the stuff get_trait_method | |
1382 | // needs to know | |
5869c6ff XL |
1383 | let ctor = struct_def |
1384 | .ctor_hir_id() | |
1385 | .map(|ctor_hir_id| self.tcx.hir().local_def_id(ctor_hir_id).local_def_index); | |
1386 | ||
1387 | EntryKind::Struct( | |
1388 | self.lazy(VariantData { | |
1389 | ctor_kind: variant.ctor_kind, | |
1390 | discr: variant.discr, | |
1391 | ctor, | |
1392 | is_non_exhaustive: variant.is_field_list_non_exhaustive(), | |
1393 | }), | |
1394 | adt_def.repr, | |
1395 | ) | |
9e0c209e | 1396 | } |
8faf50e0 | 1397 | hir::ItemKind::Union(..) => { |
e74abb32 XL |
1398 | let adt_def = self.tcx.adt_def(def_id); |
1399 | let variant = adt_def.non_enum_variant(); | |
9e0c209e | 1400 | |
5869c6ff XL |
1401 | EntryKind::Union( |
1402 | self.lazy(VariantData { | |
1403 | ctor_kind: variant.ctor_kind, | |
1404 | discr: variant.discr, | |
1405 | ctor: None, | |
1406 | is_non_exhaustive: variant.is_field_list_non_exhaustive(), | |
1407 | }), | |
1408 | adt_def.repr, | |
1409 | ) | |
9e0c209e | 1410 | } |
5869c6ff | 1411 | hir::ItemKind::Impl(hir::Impl { defaultness, .. }) => { |
e74abb32 XL |
1412 | let trait_ref = self.tcx.impl_trait_ref(def_id); |
1413 | let polarity = self.tcx.impl_polarity(def_id); | |
9e0c209e | 1414 | let parent = if let Some(trait_ref) = trait_ref { |
e74abb32 | 1415 | let trait_def = self.tcx.trait_def(trait_ref.def_id); |
5869c6ff XL |
1416 | trait_def.ancestors(self.tcx, def_id).ok().and_then(|mut an| { |
1417 | an.nth(1).and_then(|node| match node { | |
1418 | specialization_graph::Node::Impl(parent) => Some(parent), | |
1419 | _ => None, | |
1420 | }) | |
1421 | }) | |
9e0c209e SL |
1422 | } else { |
1423 | None | |
1424 | }; | |
b039eaaf | 1425 | |
cc61c64b XL |
1426 | // if this is an impl of `CoerceUnsized`, create its |
1427 | // "unsized info", else just store None | |
5869c6ff XL |
1428 | let coerce_unsized_info = trait_ref.and_then(|t| { |
1429 | if Some(t.def_id) == self.tcx.lang_items().coerce_unsized_trait() { | |
1430 | Some(self.tcx.at(item.span).coerce_unsized_info(def_id)) | |
1431 | } else { | |
1432 | None | |
1433 | } | |
1434 | }); | |
1435 | ||
1436 | let data = | |
1437 | ImplData { polarity, defaultness, parent_impl: parent, coerce_unsized_info }; | |
1a4d82fc | 1438 | |
e1599b0c | 1439 | EntryKind::Impl(self.lazy(data)) |
9e0c209e | 1440 | } |
9fa01778 | 1441 | hir::ItemKind::Trait(..) => { |
e74abb32 | 1442 | let trait_def = self.tcx.trait_def(def_id); |
9e0c209e SL |
1443 | let data = TraitData { |
1444 | unsafety: trait_def.unsafety, | |
1445 | paren_sugar: trait_def.paren_sugar, | |
e74abb32 | 1446 | has_auto_impl: self.tcx.trait_is_auto(def_id), |
0bf4aa26 | 1447 | is_marker: trait_def.is_marker, |
cdc7bbd5 | 1448 | skip_array_during_method_dispatch: trait_def.skip_array_during_method_dispatch, |
ba9703b0 | 1449 | specialization_kind: trait_def.specialization_kind, |
9e0c209e | 1450 | }; |
b039eaaf | 1451 | |
e1599b0c | 1452 | EntryKind::Trait(self.lazy(data)) |
d9579d0f | 1453 | } |
e74abb32 | 1454 | hir::ItemKind::TraitAlias(..) => EntryKind::TraitAlias, |
5869c6ff XL |
1455 | hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => { |
1456 | bug!("cannot encode info for item {:?}", item) | |
1457 | } | |
1458 | }; | |
1459 | record!(self.tables.kind[def_id] <- entry_kind); | |
e74abb32 XL |
1460 | // FIXME(eddyb) there should be a nicer way to do this. |
1461 | match item.kind { | |
fc512014 XL |
1462 | hir::ItemKind::ForeignMod { items, .. } => record!(self.tables.children[def_id] <- |
1463 | items | |
e74abb32 | 1464 | .iter() |
6a06907d | 1465 | .map(|foreign_item| foreign_item.id.def_id.local_def_index) |
e74abb32 | 1466 | ), |
ba9703b0 | 1467 | hir::ItemKind::Enum(..) => record!(self.tables.children[def_id] <- |
e74abb32 XL |
1468 | self.tcx.adt_def(def_id).variants.iter().map(|v| { |
1469 | assert!(v.def_id.is_local()); | |
1470 | v.def_id.index | |
1471 | }) | |
1472 | ), | |
dfeec247 | 1473 | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => { |
ba9703b0 | 1474 | record!(self.tables.children[def_id] <- |
dfeec247 XL |
1475 | self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| { |
1476 | assert!(f.did.is_local()); | |
1477 | f.did.index | |
1478 | }) | |
1479 | ) | |
1480 | } | |
1481 | hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => { | |
e74abb32 | 1482 | let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id); |
ba9703b0 | 1483 | record!(self.tables.children[def_id] <- |
e74abb32 XL |
1484 | associated_item_def_ids.iter().map(|&def_id| { |
1485 | assert!(def_id.is_local()); | |
1486 | def_id.index | |
1487 | }) | |
1488 | ); | |
1489 | } | |
1490 | _ => {} | |
1491 | } | |
e74abb32 | 1492 | match item.kind { |
dfeec247 XL |
1493 | hir::ItemKind::Static(..) |
1494 | | hir::ItemKind::Const(..) | |
1495 | | hir::ItemKind::Fn(..) | |
1496 | | hir::ItemKind::TyAlias(..) | |
1497 | | hir::ItemKind::OpaqueTy(..) | |
1498 | | hir::ItemKind::Enum(..) | |
1499 | | hir::ItemKind::Struct(..) | |
1500 | | hir::ItemKind::Union(..) | |
1501 | | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id), | |
e74abb32 XL |
1502 | _ => {} |
1503 | } | |
1504 | if let hir::ItemKind::Fn(..) = item.kind { | |
ba9703b0 | 1505 | record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); |
e74abb32 | 1506 | } |
dfeec247 | 1507 | if let hir::ItemKind::Impl { .. } = item.kind { |
e74abb32 | 1508 | if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) { |
ba9703b0 | 1509 | record!(self.tables.impl_trait_ref[def_id] <- trait_ref); |
e74abb32 XL |
1510 | } |
1511 | } | |
9e0c209e | 1512 | } |
476ff2be SL |
1513 | |
1514 | /// Serialize the text of exported macros | |
dfeec247 | 1515 | fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef<'_>) { |
6a06907d | 1516 | let def_id = macro_def.def_id.to_def_id(); |
ba9703b0 | 1517 | record!(self.tables.kind[def_id] <- EntryKind::MacroDef(self.lazy(macro_def.ast.clone()))); |
ba9703b0 | 1518 | self.encode_ident_span(def_id, macro_def.ident); |
476ff2be | 1519 | } |
223e47cc | 1520 | |
74b04a01 | 1521 | fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) { |
ba9703b0 | 1522 | record!(self.tables.kind[def_id] <- kind); |
e74abb32 XL |
1523 | if encode_type { |
1524 | self.encode_item_type(def_id); | |
223e47cc | 1525 | } |
223e47cc | 1526 | } |
223e47cc | 1527 | |
f9f354fc | 1528 | fn encode_info_for_closure(&mut self, def_id: LocalDefId) { |
dc9dc135 | 1529 | debug!("EncodeContext::encode_info_for_closure({:?})", def_id); |
223e47cc | 1530 | |
e74abb32 | 1531 | // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic, |
3dfed10e XL |
1532 | // including on the signature, which is inferred in `typeck. |
1533 | let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id); | |
1534 | let ty = self.tcx.typeck(def_id).node_type(hir_id); | |
e74abb32 | 1535 | |
5869c6ff | 1536 | match ty.kind() { |
74b04a01 XL |
1537 | ty::Generator(..) => { |
1538 | let data = self.tcx.generator_kind(def_id).unwrap(); | |
5869c6ff | 1539 | record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Generator(data)); |
ff7c6d11 XL |
1540 | } |
1541 | ||
5869c6ff XL |
1542 | ty::Closure(..) => { |
1543 | record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Closure); | |
1544 | } | |
223e47cc | 1545 | |
e74abb32 | 1546 | _ => bug!("closure that is neither generator nor closure"), |
5869c6ff | 1547 | } |
f9f354fc | 1548 | self.encode_item_type(def_id.to_def_id()); |
1b1a35ee | 1549 | if let ty::Closure(def_id, substs) = *ty.kind() { |
ba9703b0 | 1550 | record!(self.tables.fn_sig[def_id] <- substs.as_closure().sig()); |
223e47cc | 1551 | } |
223e47cc LB |
1552 | } |
1553 | ||
f9f354fc | 1554 | fn encode_info_for_anon_const(&mut self, def_id: LocalDefId) { |
dc9dc135 | 1555 | debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id); |
3dfed10e | 1556 | let id = self.tcx.hir().local_def_id_to_hir_id(def_id); |
e74abb32 | 1557 | let body_id = self.tcx.hir().body_owned_by(id); |
83c7162d | 1558 | let const_data = self.encode_rendered_const_for_body(body_id); |
60c5eb7d | 1559 | let qualifs = self.tcx.mir_const_qualif(def_id); |
cc61c64b | 1560 | |
f035d41b | 1561 | record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::AnonConst(qualifs, const_data)); |
f9f354fc | 1562 | self.encode_item_type(def_id.to_def_id()); |
cc61c64b | 1563 | } |
cc61c64b | 1564 | |
f9f354fc | 1565 | fn encode_native_libraries(&mut self) -> Lazy<[NativeLib]> { |
1b1a35ee | 1566 | empty_proc_macro!(self); |
ea8adc8c | 1567 | let used_libraries = self.tcx.native_libraries(LOCAL_CRATE); |
e1599b0c | 1568 | self.lazy(used_libraries.iter().cloned()) |
1a4d82fc | 1569 | } |
1a4d82fc | 1570 | |
e1599b0c | 1571 | fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> { |
1b1a35ee | 1572 | empty_proc_macro!(self); |
0531ce1d | 1573 | let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE); |
29967ef6 | 1574 | self.lazy(foreign_modules.iter().map(|(_, m)| m).cloned()) |
e1599b0c XL |
1575 | } |
1576 | ||
3dfed10e XL |
1577 | fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable) { |
1578 | let mut syntax_contexts: TableBuilder<_, _> = Default::default(); | |
1579 | let mut expn_data_table: TableBuilder<_, _> = Default::default(); | |
1580 | ||
1581 | let _: Result<(), !> = self.hygiene_ctxt.encode( | |
1582 | &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table), | |
1583 | |(this, syntax_contexts, _), index, ctxt_data| { | |
1584 | syntax_contexts.set(index, this.lazy(ctxt_data)); | |
1585 | Ok(()) | |
1586 | }, | |
1587 | |(this, _, expn_data_table), index, expn_data| { | |
1588 | expn_data_table.set(index, this.lazy(expn_data)); | |
1589 | Ok(()) | |
1590 | }, | |
1591 | ); | |
1592 | ||
1593 | (syntax_contexts.encode(&mut self.opaque), expn_data_table.encode(&mut self.opaque)) | |
1594 | } | |
1595 | ||
1b1a35ee | 1596 | fn encode_proc_macros(&mut self) -> Option<ProcMacroData> { |
f9f354fc | 1597 | let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro); |
e1599b0c XL |
1598 | if is_proc_macro { |
1599 | let tcx = self.tcx; | |
1b1a35ee XL |
1600 | let hir = tcx.hir(); |
1601 | ||
17df50a5 | 1602 | let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index; |
1b1a35ee XL |
1603 | let stability = tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).copied(); |
1604 | let macros = self.lazy(hir.krate().proc_macros.iter().map(|p| p.owner.local_def_index)); | |
17df50a5 XL |
1605 | let spans = self.tcx.sess.parse_sess.proc_macro_quoted_spans(); |
1606 | for (i, span) in spans.into_iter().enumerate() { | |
1607 | let span = self.lazy(span); | |
1608 | self.tables.proc_macro_quoted_spans.set(i, span); | |
1609 | } | |
1b1a35ee | 1610 | |
5869c6ff XL |
1611 | record!(self.tables.def_kind[LOCAL_CRATE.as_def_id()] <- DefKind::Mod); |
1612 | record!(self.tables.span[LOCAL_CRATE.as_def_id()] <- tcx.def_span(LOCAL_CRATE.as_def_id())); | |
1613 | record!(self.tables.attributes[LOCAL_CRATE.as_def_id()] <- tcx.get_attrs(LOCAL_CRATE.as_def_id())); | |
1614 | record!(self.tables.visibility[LOCAL_CRATE.as_def_id()] <- tcx.visibility(LOCAL_CRATE.as_def_id())); | |
1615 | if let Some(stability) = stability { | |
1616 | record!(self.tables.stability[LOCAL_CRATE.as_def_id()] <- stability); | |
1617 | } | |
1618 | self.encode_deprecation(LOCAL_CRATE.as_def_id()); | |
1619 | ||
1b1a35ee XL |
1620 | // Normally, this information is encoded when we walk the items |
1621 | // defined in this crate. However, we skip doing that for proc-macro crates, | |
1622 | // so we manually encode just the information that we need | |
1623 | for proc_macro in &hir.krate().proc_macros { | |
1624 | let id = proc_macro.owner.local_def_index; | |
fc512014 XL |
1625 | let mut name = hir.name(*proc_macro); |
1626 | let span = hir.span(*proc_macro); | |
1b1a35ee XL |
1627 | // Proc-macros may have attributes like `#[allow_internal_unstable]`, |
1628 | // so downstream crates need access to them. | |
fc512014 XL |
1629 | let attrs = hir.attrs(*proc_macro); |
1630 | let macro_kind = if tcx.sess.contains_name(attrs, sym::proc_macro) { | |
1631 | MacroKind::Bang | |
1632 | } else if tcx.sess.contains_name(attrs, sym::proc_macro_attribute) { | |
1633 | MacroKind::Attr | |
1634 | } else if let Some(attr) = tcx.sess.find_by_name(attrs, sym::proc_macro_derive) { | |
1635 | // This unwrap chain should have been checked by the proc-macro harness. | |
1636 | name = attr.meta_item_list().unwrap()[0] | |
1637 | .meta_item() | |
1638 | .unwrap() | |
1639 | .ident() | |
1640 | .unwrap() | |
1641 | .name; | |
1642 | MacroKind::Derive | |
1643 | } else { | |
1644 | bug!("Unknown proc-macro type for item {:?}", id); | |
1645 | }; | |
1646 | ||
1647 | let mut def_key = self.tcx.hir().def_key(proc_macro.owner); | |
1648 | def_key.disambiguated_data.data = DefPathData::MacroNs(name); | |
1649 | ||
1650 | let def_id = DefId::local(id); | |
5869c6ff | 1651 | record!(self.tables.def_kind[def_id] <- DefKind::Macro(macro_kind)); |
fc512014 XL |
1652 | record!(self.tables.kind[def_id] <- EntryKind::ProcMacro(macro_kind)); |
1653 | record!(self.tables.attributes[def_id] <- attrs); | |
1654 | record!(self.tables.def_keys[def_id] <- def_key); | |
1655 | record!(self.tables.ident_span[def_id] <- span); | |
1656 | record!(self.tables.span[def_id] <- span); | |
1657 | record!(self.tables.visibility[def_id] <- ty::Visibility::Public); | |
1658 | if let Some(stability) = stability { | |
1659 | record!(self.tables.stability[def_id] <- stability); | |
1660 | } | |
1b1a35ee XL |
1661 | } |
1662 | ||
1663 | Some(ProcMacroData { proc_macro_decls_static, stability, macros }) | |
e1599b0c XL |
1664 | } else { |
1665 | None | |
1666 | } | |
0531ce1d XL |
1667 | } |
1668 | ||
e1599b0c | 1669 | fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> { |
1b1a35ee | 1670 | empty_proc_macro!(self); |
ea8adc8c | 1671 | let crates = self.tcx.crates(); |
9e0c209e | 1672 | |
7cac9316 XL |
1673 | let mut deps = crates |
1674 | .iter() | |
1675 | .map(|&cnum| { | |
1676 | let dep = CrateDep { | |
17df50a5 | 1677 | name: self.tcx.crate_name(cnum), |
ea8adc8c | 1678 | hash: self.tcx.crate_hash(cnum), |
e74abb32 | 1679 | host_hash: self.tcx.crate_host_hash(cnum), |
ea8adc8c | 1680 | kind: self.tcx.dep_kind(cnum), |
83c7162d | 1681 | extra_filename: self.tcx.extra_filename(cnum), |
7cac9316 XL |
1682 | }; |
1683 | (cnum, dep) | |
1684 | }) | |
1685 | .collect::<Vec<_>>(); | |
1686 | ||
1687 | deps.sort_by_key(|&(cnum, _)| cnum); | |
9e0c209e | 1688 | |
7cac9316 | 1689 | { |
9e0c209e SL |
1690 | // Sanity-check the crate numbers |
1691 | let mut expected_cnum = 1; | |
1692 | for &(n, _) in &deps { | |
1693 | assert_eq!(n, CrateNum::new(expected_cnum)); | |
1694 | expected_cnum += 1; | |
1a4d82fc JJ |
1695 | } |
1696 | } | |
1a4d82fc | 1697 | |
9e0c209e SL |
1698 | // We're just going to write a list of crate 'name-hash-version's, with |
1699 | // the assumption that they are numbered 1 to n. | |
1700 | // FIXME (#2166): This is not nearly enough to support correct versioning | |
1701 | // but is enough to get transitive crate dependencies working. | |
e1599b0c | 1702 | self.lazy(deps.iter().map(|&(_, ref dep)| dep)) |
223e47cc | 1703 | } |
1a4d82fc | 1704 | |
f9f354fc | 1705 | fn encode_lib_features(&mut self) -> Lazy<[(Symbol, Option<Symbol>)]> { |
1b1a35ee | 1706 | empty_proc_macro!(self); |
b7449926 XL |
1707 | let tcx = self.tcx; |
1708 | let lib_features = tcx.lib_features(); | |
e1599b0c XL |
1709 | self.lazy(lib_features.to_vec()) |
1710 | } | |
1711 | ||
1712 | fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> { | |
1b1a35ee | 1713 | empty_proc_macro!(self); |
e1599b0c XL |
1714 | let tcx = self.tcx; |
1715 | let diagnostic_items = tcx.diagnostic_items(LOCAL_CRATE); | |
1716 | self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index))) | |
b7449926 XL |
1717 | } |
1718 | ||
e1599b0c | 1719 | fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> { |
1b1a35ee | 1720 | empty_proc_macro!(self); |
9e0c209e | 1721 | let tcx = self.tcx; |
ea8adc8c XL |
1722 | let lang_items = tcx.lang_items(); |
1723 | let lang_items = lang_items.items().iter(); | |
e1599b0c | 1724 | self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| { |
9e0c209e SL |
1725 | if let Some(def_id) = opt_def_id { |
1726 | if def_id.is_local() { | |
1727 | return Some((def_id.index, i)); | |
1728 | } | |
1a4d82fc | 1729 | } |
9e0c209e | 1730 | None |
7cac9316 | 1731 | })) |
1a4d82fc | 1732 | } |
476ff2be | 1733 | |
e1599b0c | 1734 | fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> { |
1b1a35ee | 1735 | empty_proc_macro!(self); |
7cac9316 | 1736 | let tcx = self.tcx; |
e1599b0c | 1737 | self.lazy(&tcx.lang_items().missing) |
476ff2be | 1738 | } |
1a4d82fc | 1739 | |
9e0c209e | 1740 | /// Encodes an index, mapping each trait to its (local) implementations. |
e1599b0c | 1741 | fn encode_impls(&mut self) -> Lazy<[TraitImpls]> { |
1b1a35ee | 1742 | empty_proc_macro!(self); |
dc9dc135 | 1743 | debug!("EncodeContext::encode_impls()"); |
7cac9316 | 1744 | let tcx = self.tcx; |
dfeec247 | 1745 | let mut visitor = ImplVisitor { tcx, impls: FxHashMap::default() }; |
0731742a | 1746 | tcx.hir().krate().visit_all_item_likes(&mut visitor); |
1a4d82fc | 1747 | |
7cac9316 XL |
1748 | let mut all_impls: Vec<_> = visitor.impls.into_iter().collect(); |
1749 | ||
1750 | // Bring everything into deterministic order for hashing | |
dfeec247 | 1751 | all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id)); |
7cac9316 XL |
1752 | |
1753 | let all_impls: Vec<_> = all_impls | |
c30ab7b3 | 1754 | .into_iter() |
7cac9316 XL |
1755 | .map(|(trait_def_id, mut impls)| { |
1756 | // Bring everything into deterministic order for hashing | |
3dfed10e | 1757 | impls.sort_by_cached_key(|&(index, _)| { |
ba9703b0 | 1758 | tcx.hir().definitions().def_path_hash(LocalDefId { local_def_index: index }) |
7cac9316 XL |
1759 | }); |
1760 | ||
c30ab7b3 SL |
1761 | TraitImpls { |
1762 | trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index), | |
e1599b0c | 1763 | impls: self.lazy(&impls), |
c30ab7b3 SL |
1764 | } |
1765 | }) | |
1766 | .collect(); | |
1a4d82fc | 1767 | |
e1599b0c | 1768 | self.lazy(&all_impls) |
1a4d82fc | 1769 | } |
970d7e83 | 1770 | |
476ff2be | 1771 | // Encodes all symbols exported from this crate into the metadata. |
9e0c209e SL |
1772 | // |
1773 | // This pass is seeded off the reachability list calculated in the | |
1774 | // middle::reachable module but filters out items that either don't have a | |
1775 | // symbol associated with them (they weren't translated) or if they're an FFI | |
1776 | // definition (as that's not defined in this crate). | |
dfeec247 XL |
1777 | fn encode_exported_symbols( |
1778 | &mut self, | |
1779 | exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)], | |
1780 | ) -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> { | |
1b1a35ee | 1781 | empty_proc_macro!(self); |
0531ce1d XL |
1782 | // The metadata symbol name is special. It should not show up in |
1783 | // downstream crates. | |
3dfed10e | 1784 | let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx)); |
0531ce1d | 1785 | |
dfeec247 XL |
1786 | self.lazy( |
1787 | exported_symbols | |
1788 | .iter() | |
1789 | .filter(|&&(ref exported_symbol, _)| match *exported_symbol { | |
1790 | ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name, | |
0531ce1d | 1791 | _ => true, |
dfeec247 XL |
1792 | }) |
1793 | .cloned(), | |
1794 | ) | |
0531ce1d XL |
1795 | } |
1796 | ||
e1599b0c | 1797 | fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option<LinkagePreference>]> { |
1b1a35ee | 1798 | empty_proc_macro!(self); |
17df50a5 | 1799 | let formats = self.tcx.dependency_formats(()); |
e74abb32 | 1800 | for (ty, arr) in formats.iter() { |
f9f354fc | 1801 | if *ty != CrateType::Dylib { |
e74abb32 | 1802 | continue; |
9e0c209e | 1803 | } |
dfeec247 XL |
1804 | return self.lazy(arr.iter().map(|slot| match *slot { |
1805 | Linkage::NotLinked | Linkage::IncludedFromDylib => None, | |
e74abb32 | 1806 | |
dfeec247 XL |
1807 | Linkage::Dynamic => Some(LinkagePreference::RequireDynamic), |
1808 | Linkage::Static => Some(LinkagePreference::RequireStatic), | |
e74abb32 | 1809 | })); |
a7813a04 | 1810 | } |
e74abb32 | 1811 | Lazy::empty() |
a7813a04 | 1812 | } |
1a4d82fc | 1813 | |
dfeec247 | 1814 | fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) { |
7cac9316 | 1815 | let tcx = self.tcx; |
9e0c209e | 1816 | |
dc9dc135 | 1817 | debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id); |
9e0c209e | 1818 | |
5869c6ff | 1819 | match nitem.kind { |
8faf50e0 | 1820 | hir::ForeignItemKind::Fn(_, ref names, _) => { |
7cac9316 | 1821 | let data = FnData { |
e1599b0c | 1822 | asyncness: hir::IsAsync::NotAsync, |
60c5eb7d XL |
1823 | constness: if self.tcx.is_const_fn_raw(def_id) { |
1824 | hir::Constness::Const | |
1825 | } else { | |
1826 | hir::Constness::NotConst | |
1827 | }, | |
e1599b0c | 1828 | param_names: self.encode_fn_param_names(names), |
7cac9316 | 1829 | }; |
5869c6ff | 1830 | record!(self.tables.kind[def_id] <- EntryKind::ForeignFn(self.lazy(data))); |
7cac9316 | 1831 | } |
5869c6ff XL |
1832 | hir::ForeignItemKind::Static(_, hir::Mutability::Mut) => { |
1833 | record!(self.tables.kind[def_id] <- EntryKind::ForeignMutStatic); | |
1834 | } | |
1835 | hir::ForeignItemKind::Static(_, hir::Mutability::Not) => { | |
1836 | record!(self.tables.kind[def_id] <- EntryKind::ForeignImmStatic); | |
1837 | } | |
1838 | hir::ForeignItemKind::Type => { | |
1839 | record!(self.tables.kind[def_id] <- EntryKind::ForeignType); | |
1840 | } | |
1841 | } | |
ba9703b0 | 1842 | self.encode_ident_span(def_id, nitem.ident); |
e74abb32 XL |
1843 | self.encode_item_type(def_id); |
1844 | if let hir::ForeignItemKind::Fn(..) = nitem.kind { | |
ba9703b0 | 1845 | record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); |
7cac9316 XL |
1846 | } |
1847 | } | |
1848 | } | |
9e0c209e | 1849 | |
e74abb32 | 1850 | // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR. |
3dfed10e | 1851 | impl Visitor<'tcx> for EncodeContext<'a, 'tcx> { |
dfeec247 XL |
1852 | type Map = Map<'tcx>; |
1853 | ||
ba9703b0 XL |
1854 | fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> { |
1855 | NestedVisitorMap::OnlyBodies(self.tcx.hir()) | |
7cac9316 | 1856 | } |
dfeec247 | 1857 | fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) { |
7cac9316 | 1858 | intravisit::walk_expr(self, ex); |
dc9dc135 | 1859 | self.encode_info_for_expr(ex); |
7cac9316 | 1860 | } |
e74abb32 XL |
1861 | fn visit_anon_const(&mut self, c: &'tcx AnonConst) { |
1862 | intravisit::walk_anon_const(self, c); | |
1863 | let def_id = self.tcx.hir().local_def_id(c.hir_id); | |
1864 | self.encode_info_for_anon_const(def_id); | |
1865 | } | |
dfeec247 | 1866 | fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { |
7cac9316 | 1867 | intravisit::walk_item(self, item); |
e74abb32 | 1868 | match item.kind { |
dfeec247 | 1869 | hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these |
6a06907d | 1870 | _ => self.encode_info_for_item(item.def_id.to_def_id(), item), |
7cac9316 | 1871 | } |
dc9dc135 | 1872 | self.encode_addl_info_for_item(item); |
7cac9316 | 1873 | } |
dfeec247 | 1874 | fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) { |
7cac9316 | 1875 | intravisit::walk_foreign_item(self, ni); |
6a06907d | 1876 | self.encode_info_for_foreign_item(ni.def_id.to_def_id(), ni); |
7cac9316 | 1877 | } |
dfeec247 | 1878 | fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) { |
7cac9316 | 1879 | intravisit::walk_generics(self, generics); |
dc9dc135 | 1880 | self.encode_info_for_generics(generics); |
7cac9316 | 1881 | } |
dfeec247 | 1882 | fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef<'tcx>) { |
e74abb32 | 1883 | self.encode_info_for_macro_def(macro_def); |
7cac9316 XL |
1884 | } |
1885 | } | |
9e0c209e | 1886 | |
3dfed10e | 1887 | impl EncodeContext<'a, 'tcx> { |
f9f354fc XL |
1888 | fn encode_fields(&mut self, adt_def: &ty::AdtDef) { |
1889 | for (variant_index, variant) in adt_def.variants.iter_enumerated() { | |
e74abb32 | 1890 | for (field_index, _field) in variant.fields.iter().enumerate() { |
f9f354fc | 1891 | self.encode_field(adt_def, variant_index, field_index); |
7cac9316 XL |
1892 | } |
1893 | } | |
1894 | } | |
9e0c209e | 1895 | |
dfeec247 XL |
1896 | fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) { |
1897 | for param in generics.params { | |
416331ca | 1898 | let def_id = self.tcx.hir().local_def_id(param.hir_id); |
b7449926 | 1899 | match param.kind { |
532ac7d7 | 1900 | GenericParamKind::Lifetime { .. } => continue, |
5869c6ff | 1901 | GenericParamKind::Type { default, .. } => { |
e74abb32 | 1902 | self.encode_info_for_generic_param( |
f9f354fc | 1903 | def_id.to_def_id(), |
e74abb32 XL |
1904 | EntryKind::TypeParam, |
1905 | default.is_some(), | |
532ac7d7 | 1906 | ); |
b7449926 | 1907 | } |
cdc7bbd5 XL |
1908 | GenericParamKind::Const { ref default, .. } => { |
1909 | let def_id = def_id.to_def_id(); | |
1910 | self.encode_info_for_generic_param(def_id, EntryKind::ConstParam, true); | |
1911 | if default.is_some() { | |
1912 | record!(self.tables.const_defaults[def_id] <- self.tcx.const_param_default(def_id)) | |
1913 | } | |
9fa01778 | 1914 | } |
8faf50e0 | 1915 | } |
b7449926 | 1916 | } |
7cac9316 | 1917 | } |
9cc50fc6 | 1918 | |
dfeec247 | 1919 | fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) { |
ba9703b0 XL |
1920 | if let hir::ExprKind::Closure(..) = expr.kind { |
1921 | let def_id = self.tcx.hir().local_def_id(expr.hir_id); | |
1922 | self.encode_info_for_closure(def_id); | |
7cac9316 XL |
1923 | } |
1924 | } | |
1925 | ||
ba9703b0 XL |
1926 | fn encode_ident_span(&mut self, def_id: DefId, ident: Ident) { |
1927 | record!(self.tables.ident_span[def_id] <- ident.span); | |
1928 | } | |
1929 | ||
7cac9316 XL |
1930 | /// In some cases, along with the item itself, we also |
1931 | /// encode some sub-items. Usually we want some info from the item | |
1932 | /// so it's easier to do that here then to wait until we would encounter | |
1933 | /// normally in the visitor walk. | |
dfeec247 | 1934 | fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) { |
e74abb32 | 1935 | match item.kind { |
dfeec247 XL |
1936 | hir::ItemKind::Static(..) |
1937 | | hir::ItemKind::Const(..) | |
1938 | | hir::ItemKind::Fn(..) | |
1939 | | hir::ItemKind::Mod(..) | |
fc512014 | 1940 | | hir::ItemKind::ForeignMod { .. } |
dfeec247 XL |
1941 | | hir::ItemKind::GlobalAsm(..) |
1942 | | hir::ItemKind::ExternCrate(..) | |
1943 | | hir::ItemKind::Use(..) | |
1944 | | hir::ItemKind::TyAlias(..) | |
1945 | | hir::ItemKind::OpaqueTy(..) | |
1946 | | hir::ItemKind::TraitAlias(..) => { | |
7cac9316 XL |
1947 | // no sub-item recording needed in these cases |
1948 | } | |
8faf50e0 | 1949 | hir::ItemKind::Enum(..) => { |
6a06907d | 1950 | let def = self.tcx.adt_def(item.def_id.to_def_id()); |
f9f354fc | 1951 | self.encode_fields(def); |
7cac9316 | 1952 | |
a1dfa0c6 | 1953 | for (i, variant) in def.variants.iter_enumerated() { |
f9f354fc | 1954 | self.encode_enum_variant_info(def, i); |
e74abb32 | 1955 | |
e74abb32 | 1956 | if let Some(_ctor_def_id) = variant.ctor_def_id { |
f9f354fc | 1957 | self.encode_enum_variant_ctor(def, i); |
532ac7d7 | 1958 | } |
7cac9316 XL |
1959 | } |
1960 | } | |
8faf50e0 | 1961 | hir::ItemKind::Struct(ref struct_def, _) => { |
6a06907d | 1962 | let def = self.tcx.adt_def(item.def_id.to_def_id()); |
f9f354fc | 1963 | self.encode_fields(def); |
7cac9316 XL |
1964 | |
1965 | // If the struct has a constructor, encode it. | |
532ac7d7 | 1966 | if let Some(ctor_hir_id) = struct_def.ctor_hir_id() { |
416331ca | 1967 | let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id); |
f9f354fc | 1968 | self.encode_struct_ctor(def, ctor_def_id.to_def_id()); |
7cac9316 XL |
1969 | } |
1970 | } | |
8faf50e0 | 1971 | hir::ItemKind::Union(..) => { |
6a06907d | 1972 | let def = self.tcx.adt_def(item.def_id.to_def_id()); |
f9f354fc | 1973 | self.encode_fields(def); |
7cac9316 | 1974 | } |
dfeec247 | 1975 | hir::ItemKind::Impl { .. } => { |
f9f354fc | 1976 | for &trait_item_def_id in |
6a06907d | 1977 | self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter() |
f9f354fc | 1978 | { |
e74abb32 | 1979 | self.encode_info_for_impl_item(trait_item_def_id); |
7cac9316 XL |
1980 | } |
1981 | } | |
8faf50e0 | 1982 | hir::ItemKind::Trait(..) => { |
6a06907d XL |
1983 | for &item_def_id in self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter() |
1984 | { | |
e74abb32 | 1985 | self.encode_info_for_trait_item(item_def_id); |
9e0c209e | 1986 | } |
223e47cc | 1987 | } |
7cac9316 XL |
1988 | } |
1989 | } | |
1990 | } | |
9e0c209e | 1991 | |
dc9dc135 XL |
1992 | struct ImplVisitor<'tcx> { |
1993 | tcx: TyCtxt<'tcx>, | |
3dfed10e | 1994 | impls: FxHashMap<DefId, Vec<(DefIndex, Option<ty::fast_reject::SimplifiedType>)>>, |
7cac9316 XL |
1995 | } |
1996 | ||
dc9dc135 | 1997 | impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> { |
dfeec247 XL |
1998 | fn visit_item(&mut self, item: &hir::Item<'_>) { |
1999 | if let hir::ItemKind::Impl { .. } = item.kind { | |
6a06907d | 2000 | if let Some(trait_ref) = self.tcx.impl_trait_ref(item.def_id.to_def_id()) { |
3dfed10e XL |
2001 | let simplified_self_ty = |
2002 | ty::fast_reject::simplify_type(self.tcx, trait_ref.self_ty(), false); | |
2003 | ||
2004 | self.impls | |
2005 | .entry(trait_ref.def_id) | |
2006 | .or_default() | |
6a06907d | 2007 | .push((item.def_id.local_def_index, simplified_self_ty)); |
7cac9316 | 2008 | } |
223e47cc | 2009 | } |
7cac9316 | 2010 | } |
223e47cc | 2011 | |
dfeec247 | 2012 | fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem<'v>) {} |
7cac9316 | 2013 | |
dfeec247 | 2014 | fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem<'v>) { |
7cac9316 | 2015 | // handled in `visit_item` above |
223e47cc | 2016 | } |
fc512014 XL |
2017 | |
2018 | fn visit_foreign_item(&mut self, _foreign_item: &'v hir::ForeignItem<'v>) {} | |
223e47cc LB |
2019 | } |
2020 | ||
ba9703b0 XL |
2021 | /// Used to prefetch queries which will be needed later by metadata encoding. |
2022 | /// Only a subset of the queries are actually prefetched to keep this code smaller. | |
5869c6ff XL |
2023 | fn prefetch_mir(tcx: TyCtxt<'_>) { |
2024 | if !tcx.sess.opts.output_types.should_codegen() { | |
2025 | // We won't emit MIR, so don't prefetch it. | |
2026 | return; | |
ba9703b0 | 2027 | } |
ba9703b0 | 2028 | |
17df50a5 | 2029 | par_iter(tcx.mir_keys(())).for_each(|&def_id| { |
5869c6ff | 2030 | let (encode_const, encode_opt) = should_encode_mir(tcx, def_id); |
ba9703b0 | 2031 | |
5869c6ff XL |
2032 | if encode_const { |
2033 | tcx.ensure().mir_for_ctfe(def_id); | |
ba9703b0 | 2034 | } |
5869c6ff XL |
2035 | if encode_opt { |
2036 | tcx.ensure().optimized_mir(def_id); | |
2037 | } | |
2038 | if encode_opt || encode_const { | |
2039 | tcx.ensure().promoted_mir(def_id); | |
2040 | } | |
2041 | }) | |
ba9703b0 XL |
2042 | } |
2043 | ||
9e0c209e SL |
2044 | // NOTE(eddyb) The following comment was preserved for posterity, even |
2045 | // though it's no longer relevant as EBML (which uses nested & tagged | |
2046 | // "documents") was replaced with a scheme that can't go out of bounds. | |
2047 | // | |
2048 | // And here we run into yet another obscure archive bug: in which metadata | |
2049 | // loaded from archives may have trailing garbage bytes. Awhile back one of | |
cc61c64b | 2050 | // our tests was failing sporadically on the macOS 64-bit builders (both nopt |
9e0c209e SL |
2051 | // and opt) by having ebml generate an out-of-bounds panic when looking at |
2052 | // metadata. | |
2053 | // | |
2054 | // Upon investigation it turned out that the metadata file inside of an rlib | |
2055 | // (and ar archive) was being corrupted. Some compilations would generate a | |
2056 | // metadata file which would end in a few extra bytes, while other | |
2057 | // compilations would not have these extra bytes appended to the end. These | |
2058 | // extra bytes were interpreted by ebml as an extra tag, so they ended up | |
2059 | // being interpreted causing the out-of-bounds. | |
2060 | // | |
2061 | // The root cause of why these extra bytes were appearing was never | |
2062 | // discovered, and in the meantime the solution we're employing is to insert | |
2063 | // the length of the metadata to the start of the metadata. Later on this | |
2064 | // will allow us to slice the metadata to the precise length that we just | |
2065 | // generated regardless of trailing bytes that end up in it. | |
2066 | ||
60c5eb7d | 2067 | pub(super) fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata { |
ba9703b0 XL |
2068 | // Since encoding metadata is not in a query, and nothing is cached, |
2069 | // there's no need to do dep-graph tracking for any of it. | |
2070 | tcx.dep_graph.assert_ignored(); | |
2071 | ||
2072 | join( | |
2073 | || encode_metadata_impl(tcx), | |
2074 | || { | |
2075 | if tcx.sess.threads() == 1 { | |
2076 | return; | |
2077 | } | |
2078 | // Prefetch some queries used by metadata encoding. | |
2079 | // This is not necessary for correctness, but is only done for performance reasons. | |
2080 | // It can be removed if it turns out to cause trouble or be detrimental to performance. | |
5869c6ff | 2081 | join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE)); |
ba9703b0 XL |
2082 | }, |
2083 | ) | |
2084 | .0 | |
2085 | } | |
2086 | ||
2087 | fn encode_metadata_impl(tcx: TyCtxt<'_>) -> EncodedMetadata { | |
8faf50e0 | 2088 | let mut encoder = opaque::Encoder::new(vec![]); |
cdc7bbd5 | 2089 | encoder.emit_raw_bytes(METADATA_HEADER).unwrap(); |
9e0c209e | 2090 | |
7cac9316 | 2091 | // Will be filled with the root position after encoding everything. |
cdc7bbd5 | 2092 | encoder.emit_raw_bytes(&[0, 0, 0, 0]).unwrap(); |
9e0c209e | 2093 | |
f035d41b | 2094 | let source_map_files = tcx.sess.source_map().files(); |
29967ef6 XL |
2095 | let source_file_cache = (source_map_files[0].clone(), 0); |
2096 | let required_source_files = Some(GrowableBitSet::with_capacity(source_map_files.len())); | |
2097 | drop(source_map_files); | |
2098 | ||
3dfed10e | 2099 | let hygiene_ctxt = HygieneEncodeContext::default(); |
f035d41b | 2100 | |
ba9703b0 XL |
2101 | let mut ecx = EncodeContext { |
2102 | opaque: encoder, | |
2103 | tcx, | |
1b1a35ee | 2104 | feat: tcx.features(), |
ba9703b0 XL |
2105 | tables: Default::default(), |
2106 | lazy_state: LazyState::NoNode, | |
2107 | type_shorthands: Default::default(), | |
2108 | predicate_shorthands: Default::default(), | |
29967ef6 | 2109 | source_file_cache, |
ba9703b0 | 2110 | interpret_allocs: Default::default(), |
29967ef6 | 2111 | required_source_files, |
f035d41b | 2112 | is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro), |
3dfed10e | 2113 | hygiene_ctxt: &hygiene_ctxt, |
ba9703b0 XL |
2114 | }; |
2115 | ||
2116 | // Encode the rustc version string in a predictable location. | |
2117 | rustc_version().encode(&mut ecx).unwrap(); | |
2118 | ||
2119 | // Encode all the entries and extra information in the crate, | |
2120 | // culminating in the `CrateRoot` which points to all of it. | |
2121 | let root = ecx.encode_crate_root(); | |
2122 | ||
2123 | let mut result = ecx.opaque.into_inner(); | |
9e0c209e SL |
2124 | |
2125 | // Encode the root position. | |
2126 | let header = METADATA_HEADER.len(); | |
e74abb32 | 2127 | let pos = root.position.get(); |
9e0c209e SL |
2128 | result[header + 0] = (pos >> 24) as u8; |
2129 | result[header + 1] = (pos >> 16) as u8; | |
c30ab7b3 SL |
2130 | result[header + 2] = (pos >> 8) as u8; |
2131 | result[header + 3] = (pos >> 0) as u8; | |
9e0c209e | 2132 | |
ff7c6d11 | 2133 | EncodedMetadata { raw_data: result } |
223e47cc | 2134 | } |