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