1use std::collections::hash_map::Entry;
2use std::sync::Arc;
3use std::{fmt, mem};
4
5use rustc_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet};
6use rustc_data_structures::memmap::Mmap;
7use rustc_data_structures::sync::{HashMapExt, Lock, RwLock};
8use rustc_data_structures::unhash::UnhashMap;
9use rustc_data_structures::unord::{UnordMap, UnordSet};
10use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LOCAL_CRATE, LocalDefId, StableCrateId};
11use rustc_hir::definitions::DefPathHash;
12use rustc_index::{Idx, IndexVec};
13use rustc_macros::{Decodable, Encodable};
14use rustc_serialize::opaque::{FileEncodeResult, FileEncoder, IntEncodedWithFixedSize, MemDecoder};
15use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
16use rustc_session::Session;
17use rustc_span::hygiene::{
18 ExpnId, HygieneDecodeContext, HygieneEncodeContext, SyntaxContext, SyntaxContextKey,
19};
20use rustc_span::{
21 BlobDecoder, BytePos, ByteSymbol, CachingSourceMapView, ExpnData, ExpnHash, RelativeBytePos,
22 SourceFile, Span, SpanDecoder, SpanEncoder, Spanned, StableSourceFileId, Symbol,
23};
24
25use crate::dep_graph::{DepNodeIndex, QuerySideEffect, SerializedDepNodeIndex};
26use crate::mir::interpret::{AllocDecodingSession, AllocDecodingState};
27use crate::mir::mono::MonoItem;
28use crate::mir::{self, interpret};
29use crate::ty::codec::{RefDecodable, TyDecoder, TyEncoder};
30use crate::ty::{self, Ty, TyCtxt};
31
32const TAG_FILE_FOOTER: u128 = 0xC0FFEE_C0FFEE_C0FFEE_C0FFEE_C0FFEE;
33
34const TAG_FULL_SPAN: u8 = 0;
36const TAG_PARTIAL_SPAN: u8 = 1;
38const TAG_RELATIVE_SPAN: u8 = 2;
39
40const TAG_SYNTAX_CONTEXT: u8 = 0;
41const TAG_EXPN_DATA: u8 = 1;
42
43const SYMBOL_STR: u8 = 0;
45const SYMBOL_OFFSET: u8 = 1;
46const SYMBOL_PREDEFINED: u8 = 2;
47
48pub struct OnDiskCache {
53 serialized_data: RwLock<Option<Mmap>>,
55
56 current_side_effects: Lock<FxIndexMap<DepNodeIndex, QuerySideEffect>>,
59
60 file_index_to_stable_id: FxHashMap<SourceFileIndex, EncodedSourceFileId>,
61
62 file_index_to_file: Lock<FxHashMap<SourceFileIndex, Arc<SourceFile>>>,
64
65 query_result_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
68
69 prev_side_effects_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
72
73 alloc_decoding_state: AllocDecodingState,
74
75 syntax_contexts: FxHashMap<u32, AbsoluteBytePos>,
81 expn_data: UnhashMap<ExpnHash, AbsoluteBytePos>,
91 hygiene_context: HygieneDecodeContext,
93 foreign_expn_data: UnhashMap<ExpnHash, u32>,
98}
99
100#[derive(const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for Footer {
fn encode(&self, __encoder: &mut __E) {
match *self {
Footer {
file_index_to_stable_id: ref __binding_0,
query_result_index: ref __binding_1,
side_effects_index: ref __binding_2,
interpret_alloc_index: ref __binding_3,
syntax_contexts: ref __binding_4,
expn_data: ref __binding_5,
foreign_expn_data: ref __binding_6 } => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_2,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_3,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_4,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_5,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_6,
__encoder);
}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for Footer {
fn decode(__decoder: &mut __D) -> Self {
Footer {
file_index_to_stable_id: ::rustc_serialize::Decodable::decode(__decoder),
query_result_index: ::rustc_serialize::Decodable::decode(__decoder),
side_effects_index: ::rustc_serialize::Decodable::decode(__decoder),
interpret_alloc_index: ::rustc_serialize::Decodable::decode(__decoder),
syntax_contexts: ::rustc_serialize::Decodable::decode(__decoder),
expn_data: ::rustc_serialize::Decodable::decode(__decoder),
foreign_expn_data: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
102struct Footer {
103 file_index_to_stable_id: FxHashMap<SourceFileIndex, EncodedSourceFileId>,
104 query_result_index: EncodedDepNodeIndex,
105 side_effects_index: EncodedDepNodeIndex,
106 interpret_alloc_index: Vec<u64>,
110 syntax_contexts: FxHashMap<u32, AbsoluteBytePos>,
112 expn_data: UnhashMap<ExpnHash, AbsoluteBytePos>,
114 foreign_expn_data: UnhashMap<ExpnHash, u32>,
115}
116
117pub type EncodedDepNodeIndex = Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>;
118
119#[derive(#[automatically_derived]
impl ::core::marker::Copy for SourceFileIndex { }Copy, #[automatically_derived]
impl ::core::clone::Clone for SourceFileIndex {
#[inline]
fn clone(&self) -> SourceFileIndex {
let _: ::core::clone::AssertParamIsClone<u32>;
*self
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for SourceFileIndex {
#[inline]
fn eq(&self, other: &SourceFileIndex) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for SourceFileIndex {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<u32>;
}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for SourceFileIndex {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}Hash, #[automatically_derived]
impl ::core::fmt::Debug for SourceFileIndex {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"SourceFileIndex", &&self.0)
}
}Debug, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for SourceFileIndex {
fn encode(&self, __encoder: &mut __E) {
match *self {
SourceFileIndex(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for SourceFileIndex {
fn decode(__decoder: &mut __D) -> Self {
SourceFileIndex(::rustc_serialize::Decodable::decode(__decoder))
}
}
};Decodable)]
120struct SourceFileIndex(u32);
121
122#[derive(#[automatically_derived]
impl ::core::marker::Copy for AbsoluteBytePos { }Copy, #[automatically_derived]
impl ::core::clone::Clone for AbsoluteBytePos {
#[inline]
fn clone(&self) -> AbsoluteBytePos {
let _: ::core::clone::AssertParamIsClone<u64>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for AbsoluteBytePos {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"AbsoluteBytePos", &&self.0)
}
}Debug, #[automatically_derived]
impl ::core::hash::Hash for AbsoluteBytePos {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}Hash, #[automatically_derived]
impl ::core::cmp::Eq for AbsoluteBytePos {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<u64>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for AbsoluteBytePos {
#[inline]
fn eq(&self, other: &AbsoluteBytePos) -> bool { self.0 == other.0 }
}PartialEq, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for AbsoluteBytePos {
fn encode(&self, __encoder: &mut __E) {
match *self {
AbsoluteBytePos(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for AbsoluteBytePos {
fn decode(__decoder: &mut __D) -> Self {
AbsoluteBytePos(::rustc_serialize::Decodable::decode(__decoder))
}
}
};Decodable)]
123pub struct AbsoluteBytePos(u64);
124
125impl AbsoluteBytePos {
126 #[inline]
127 pub fn new(pos: usize) -> AbsoluteBytePos {
128 AbsoluteBytePos(pos.try_into().expect("Incremental cache file size overflowed u64."))
129 }
130
131 #[inline]
132 fn to_usize(self) -> usize {
133 self.0 as usize
134 }
135}
136
137#[derive(const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for EncodedSourceFileId {
fn encode(&self, __encoder: &mut __E) {
match *self {
EncodedSourceFileId {
stable_source_file_id: ref __binding_0,
stable_crate_id: ref __binding_1 } => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for EncodedSourceFileId {
fn decode(__decoder: &mut __D) -> Self {
EncodedSourceFileId {
stable_source_file_id: ::rustc_serialize::Decodable::decode(__decoder),
stable_crate_id: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable, #[automatically_derived]
impl ::core::clone::Clone for EncodedSourceFileId {
#[inline]
fn clone(&self) -> EncodedSourceFileId {
EncodedSourceFileId {
stable_source_file_id: ::core::clone::Clone::clone(&self.stable_source_file_id),
stable_crate_id: ::core::clone::Clone::clone(&self.stable_crate_id),
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for EncodedSourceFileId {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"EncodedSourceFileId", "stable_source_file_id",
&self.stable_source_file_id, "stable_crate_id",
&&self.stable_crate_id)
}
}Debug)]
138struct EncodedSourceFileId {
139 stable_source_file_id: StableSourceFileId,
140 stable_crate_id: StableCrateId,
141}
142
143impl EncodedSourceFileId {
144 #[inline]
145 fn new(tcx: TyCtxt<'_>, file: &SourceFile) -> EncodedSourceFileId {
146 EncodedSourceFileId {
147 stable_source_file_id: file.stable_id,
148 stable_crate_id: tcx.stable_crate_id(file.cnum),
149 }
150 }
151}
152
153impl OnDiskCache {
154 pub fn new(sess: &Session, data: Mmap, start_pos: usize) -> Result<Self, ()> {
159 if !sess.opts.incremental.is_some() {
::core::panicking::panic("assertion failed: sess.opts.incremental.is_some()")
};assert!(sess.opts.incremental.is_some());
160
161 let mut decoder = MemDecoder::new(&data, start_pos)?;
162
163 let footer_pos = decoder
166 .with_position(decoder.len() - IntEncodedWithFixedSize::ENCODED_SIZE, |decoder| {
167 IntEncodedWithFixedSize::decode(decoder).0 as usize
168 });
169 let footer: Footer =
171 decoder.with_position(footer_pos, |decoder| decode_tagged(decoder, TAG_FILE_FOOTER));
172
173 Ok(Self {
174 serialized_data: RwLock::new(Some(data)),
175 file_index_to_stable_id: footer.file_index_to_stable_id,
176 file_index_to_file: Default::default(),
177 current_side_effects: Default::default(),
178 query_result_index: footer.query_result_index.into_iter().collect(),
179 prev_side_effects_index: footer.side_effects_index.into_iter().collect(),
180 alloc_decoding_state: AllocDecodingState::new(footer.interpret_alloc_index),
181 syntax_contexts: footer.syntax_contexts,
182 expn_data: footer.expn_data,
183 foreign_expn_data: footer.foreign_expn_data,
184 hygiene_context: Default::default(),
185 })
186 }
187
188 pub fn new_empty() -> Self {
189 Self {
190 serialized_data: RwLock::new(None),
191 file_index_to_stable_id: Default::default(),
192 file_index_to_file: Default::default(),
193 current_side_effects: Default::default(),
194 query_result_index: Default::default(),
195 prev_side_effects_index: Default::default(),
196 alloc_decoding_state: AllocDecodingState::new(Vec::new()),
197 syntax_contexts: FxHashMap::default(),
198 expn_data: UnhashMap::default(),
199 foreign_expn_data: UnhashMap::default(),
200 hygiene_context: Default::default(),
201 }
202 }
203
204 pub fn close_serialized_data_mmap(&self) {
206 *self.serialized_data.write() = None;
208 }
209
210 pub fn serialize(&self, tcx: TyCtxt<'_>, encoder: FileEncoder) -> FileEncodeResult {
211 tcx.dep_graph.with_ignore(|| {
213 let (file_to_file_index, file_index_to_stable_id) = {
215 let files = tcx.sess.source_map().files();
216 let mut file_to_file_index =
217 FxHashMap::with_capacity_and_hasher(files.len(), Default::default());
218 let mut file_index_to_stable_id =
219 FxHashMap::with_capacity_and_hasher(files.len(), Default::default());
220
221 for (index, file) in files.iter().enumerate() {
222 let index = SourceFileIndex(index as u32);
223 let file_ptr: *const SourceFile = &raw const **file;
224 file_to_file_index.insert(file_ptr, index);
225 let source_file_id = EncodedSourceFileId::new(tcx, file);
226 file_index_to_stable_id.insert(index, source_file_id);
227 }
228
229 (file_to_file_index, file_index_to_stable_id)
230 };
231
232 let hygiene_encode_context = HygieneEncodeContext::default();
233
234 let mut encoder = CacheEncoder {
235 tcx,
236 encoder,
237 type_shorthands: Default::default(),
238 predicate_shorthands: Default::default(),
239 interpret_allocs: Default::default(),
240 source_map: CachingSourceMapView::new(tcx.sess.source_map()),
241 file_to_file_index,
242 hygiene_context: &hygiene_encode_context,
243 symbol_index_table: Default::default(),
244 };
245
246 let mut query_result_index = EncodedDepNodeIndex::new();
248
249 tcx.sess.time("encode_query_results", || {
250 let enc = &mut encoder;
251 let qri = &mut query_result_index;
252 tcx.encode_all_query_results(enc, qri);
253 });
254
255 let side_effects_index: EncodedDepNodeIndex = self
257 .current_side_effects
258 .borrow()
259 .iter()
260 .map(|(dep_node_index, side_effect)| {
261 let pos = AbsoluteBytePos::new(encoder.position());
262 let dep_node_index = SerializedDepNodeIndex::new(dep_node_index.index());
263 encoder.encode_tagged(dep_node_index, side_effect);
264
265 (dep_node_index, pos)
266 })
267 .collect();
268
269 let interpret_alloc_index = {
270 let mut interpret_alloc_index = Vec::new();
271 let mut n = 0;
272 loop {
273 let new_n = encoder.interpret_allocs.len();
274 if n == new_n {
276 break;
278 }
279 interpret_alloc_index.reserve(new_n - n);
280 for idx in n..new_n {
281 let id = encoder.interpret_allocs[idx];
282 let pos: u64 = encoder.position().try_into().unwrap();
283 interpret_alloc_index.push(pos);
284 interpret::specialized_encode_alloc_id(&mut encoder, tcx, id);
285 }
286 n = new_n;
287 }
288 interpret_alloc_index
289 };
290
291 let mut syntax_contexts = FxHashMap::default();
292 let mut expn_data = UnhashMap::default();
293 let mut foreign_expn_data = UnhashMap::default();
294
295 hygiene_encode_context.encode(
299 &mut encoder,
300 |encoder, index, ctxt_data| {
301 let pos = AbsoluteBytePos::new(encoder.position());
302 encoder.encode_tagged(TAG_SYNTAX_CONTEXT, ctxt_data);
303 syntax_contexts.insert(index, pos);
304 },
305 |encoder, expn_id, data, hash| {
306 if expn_id.krate == LOCAL_CRATE {
307 let pos = AbsoluteBytePos::new(encoder.position());
308 encoder.encode_tagged(TAG_EXPN_DATA, data);
309 expn_data.insert(hash, pos);
310 } else {
311 foreign_expn_data.insert(hash, expn_id.local_id.as_u32());
312 }
313 },
314 );
315
316 let footer_pos = encoder.position() as u64;
318 encoder.encode_tagged(
319 TAG_FILE_FOOTER,
320 &Footer {
321 file_index_to_stable_id,
322 query_result_index,
323 side_effects_index,
324 interpret_alloc_index,
325 syntax_contexts,
326 expn_data,
327 foreign_expn_data,
328 },
329 );
330
331 IntEncodedWithFixedSize(footer_pos).encode(&mut encoder.encoder);
334
335 encoder.finish()
339 })
340 }
341
342 pub fn load_side_effect(
344 &self,
345 tcx: TyCtxt<'_>,
346 dep_node_index: SerializedDepNodeIndex,
347 ) -> Option<QuerySideEffect> {
348 let side_effect: Option<QuerySideEffect> =
349 self.load_indexed(tcx, dep_node_index, &self.prev_side_effects_index);
350 side_effect
351 }
352
353 pub fn store_side_effect(&self, dep_node_index: DepNodeIndex, side_effect: QuerySideEffect) {
357 let mut current_side_effects = self.current_side_effects.borrow_mut();
358 let prev = current_side_effects.insert(dep_node_index, side_effect);
359 if true {
if !prev.is_none() {
::core::panicking::panic("assertion failed: prev.is_none()")
};
};debug_assert!(prev.is_none());
360 }
361
362 #[inline]
364 pub fn loadable_from_disk(&self, dep_node_index: SerializedDepNodeIndex) -> bool {
365 self.query_result_index.contains_key(&dep_node_index)
366 }
368
369 pub fn try_load_query_result<'tcx, T>(
372 &self,
373 tcx: TyCtxt<'tcx>,
374 dep_node_index: SerializedDepNodeIndex,
375 ) -> Option<T>
376 where
377 T: for<'a> Decodable<CacheDecoder<'a, 'tcx>>,
378 {
379 let opt_value = self.load_indexed(tcx, dep_node_index, &self.query_result_index);
380 if true {
match (&opt_value.is_some(), &self.loadable_from_disk(dep_node_index)) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
};debug_assert_eq!(opt_value.is_some(), self.loadable_from_disk(dep_node_index));
381 opt_value
382 }
383
384 fn load_indexed<'tcx, T>(
385 &self,
386 tcx: TyCtxt<'tcx>,
387 dep_node_index: SerializedDepNodeIndex,
388 index: &FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
389 ) -> Option<T>
390 where
391 T: for<'a> Decodable<CacheDecoder<'a, 'tcx>>,
392 {
393 let pos = index.get(&dep_node_index).cloned()?;
394 let value = self.with_decoder(tcx, pos, |decoder| decode_tagged(decoder, dep_node_index));
395 Some(value)
396 }
397
398 fn with_decoder<'a, 'tcx, T, F: for<'s> FnOnce(&mut CacheDecoder<'s, 'tcx>) -> T>(
399 &self,
400 tcx: TyCtxt<'tcx>,
401 pos: AbsoluteBytePos,
402 f: F,
403 ) -> T
404 where
405 T: Decodable<CacheDecoder<'a, 'tcx>>,
406 {
407 let serialized_data = self.serialized_data.read();
408 let mut decoder = CacheDecoder {
409 tcx,
410 opaque: MemDecoder::new(serialized_data.as_deref().unwrap_or(&[]), pos.to_usize())
411 .unwrap(),
412 file_index_to_file: &self.file_index_to_file,
413 file_index_to_stable_id: &self.file_index_to_stable_id,
414 alloc_decoding_session: self.alloc_decoding_state.new_decoding_session(),
415 syntax_contexts: &self.syntax_contexts,
416 expn_data: &self.expn_data,
417 foreign_expn_data: &self.foreign_expn_data,
418 hygiene_context: &self.hygiene_context,
419 };
420 f(&mut decoder)
421 }
422}
423
424pub struct CacheDecoder<'a, 'tcx> {
430 tcx: TyCtxt<'tcx>,
431 opaque: MemDecoder<'a>,
432 file_index_to_file: &'a Lock<FxHashMap<SourceFileIndex, Arc<SourceFile>>>,
433 file_index_to_stable_id: &'a FxHashMap<SourceFileIndex, EncodedSourceFileId>,
434 alloc_decoding_session: AllocDecodingSession<'a>,
435 syntax_contexts: &'a FxHashMap<u32, AbsoluteBytePos>,
436 expn_data: &'a UnhashMap<ExpnHash, AbsoluteBytePos>,
437 foreign_expn_data: &'a UnhashMap<ExpnHash, u32>,
438 hygiene_context: &'a HygieneDecodeContext,
439}
440
441impl<'a, 'tcx> CacheDecoder<'a, 'tcx> {
442 #[inline]
443 fn file_index_to_file(&self, index: SourceFileIndex) -> Arc<SourceFile> {
444 let CacheDecoder { tcx, file_index_to_file, file_index_to_stable_id, .. } = *self;
445
446 Arc::clone(file_index_to_file.borrow_mut().entry(index).or_insert_with(|| {
447 let source_file_id = &file_index_to_stable_id[&index];
448 let source_file_cnum = tcx.stable_crate_id_to_crate_num(source_file_id.stable_crate_id);
449
450 if source_file_cnum != LOCAL_CRATE {
460 self.tcx.import_source_files(source_file_cnum);
461 }
462
463 tcx.sess
464 .source_map()
465 .source_file_by_stable_id(source_file_id.stable_source_file_id)
466 .expect("failed to lookup `SourceFile` in new context")
467 }))
468 }
469
470 #[inline]
472 fn decode_symbol_or_byte_symbol<S>(
473 &mut self,
474 new_from_index: impl Fn(u32) -> S,
475 read_and_intern_str_or_byte_str_this: impl Fn(&mut Self) -> S,
476 read_and_intern_str_or_byte_str_opaque: impl Fn(&mut MemDecoder<'a>) -> S,
477 ) -> S {
478 let tag = self.read_u8();
479
480 match tag {
481 SYMBOL_STR => read_and_intern_str_or_byte_str_this(self),
482 SYMBOL_OFFSET => {
483 let pos = self.read_usize();
485
486 self.opaque.with_position(pos, |d| read_and_intern_str_or_byte_str_opaque(d))
488 }
489 SYMBOL_PREDEFINED => new_from_index(self.read_u32()),
490 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
491 }
492 }
493}
494
495fn decode_tagged<D, T, V>(decoder: &mut D, expected_tag: T) -> V
498where
499 T: Decodable<D> + Eq + fmt::Debug,
500 V: Decodable<D>,
501 D: Decoder,
502{
503 let start_pos = decoder.position();
504
505 let actual_tag = T::decode(decoder);
506 match (&actual_tag, &expected_tag) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(actual_tag, expected_tag);
507 let value = V::decode(decoder);
508 let end_pos = decoder.position();
509
510 let expected_len: u64 = Decodable::decode(decoder);
511 match (&((end_pos - start_pos) as u64), &expected_len) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!((end_pos - start_pos) as u64, expected_len);
512
513 value
514}
515
516impl<'a, 'tcx> TyDecoder<'tcx> for CacheDecoder<'a, 'tcx> {
517 const CLEAR_CROSS_CRATE: bool = false;
518
519 #[inline]
520 fn interner(&self) -> TyCtxt<'tcx> {
521 self.tcx
522 }
523
524 fn cached_ty_for_shorthand<F>(&mut self, shorthand: usize, or_insert_with: F) -> Ty<'tcx>
525 where
526 F: FnOnce(&mut Self) -> Ty<'tcx>,
527 {
528 let tcx = self.tcx;
529
530 let cache_key = ty::CReaderCacheKey { cnum: None, pos: shorthand };
531
532 if let Some(&ty) = tcx.ty_rcache.borrow().get(&cache_key) {
533 return ty;
534 }
535
536 let ty = or_insert_with(self);
537 tcx.ty_rcache.borrow_mut().insert_same(cache_key, ty);
539 ty
540 }
541
542 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
543 where
544 F: FnOnce(&mut Self) -> R,
545 {
546 if true {
if !(pos < self.opaque.len()) {
::core::panicking::panic("assertion failed: pos < self.opaque.len()")
};
};debug_assert!(pos < self.opaque.len());
547
548 let new_opaque = self.opaque.split_at(pos);
549 let old_opaque = mem::replace(&mut self.opaque, new_opaque);
550 let r = f(self);
551 self.opaque = old_opaque;
552 r
553 }
554
555 fn decode_alloc_id(&mut self) -> interpret::AllocId {
556 let alloc_decoding_session = self.alloc_decoding_session;
557 alloc_decoding_session.decode_alloc_id(self)
558 }
559}
560
561mod __ty_decoder_impl {
use rustc_serialize::Decoder;
use super::CacheDecoder;
impl<'a, 'tcx> Decoder for CacheDecoder<'a, 'tcx> {
#[inline]
fn read_usize(&mut self) -> usize { self.opaque.read_usize() }
#[inline]
fn read_u128(&mut self) -> u128 { self.opaque.read_u128() }
#[inline]
fn read_u64(&mut self) -> u64 { self.opaque.read_u64() }
#[inline]
fn read_u32(&mut self) -> u32 { self.opaque.read_u32() }
#[inline]
fn read_u16(&mut self) -> u16 { self.opaque.read_u16() }
#[inline]
fn read_u8(&mut self) -> u8 { self.opaque.read_u8() }
#[inline]
fn read_isize(&mut self) -> isize { self.opaque.read_isize() }
#[inline]
fn read_i128(&mut self) -> i128 { self.opaque.read_i128() }
#[inline]
fn read_i64(&mut self) -> i64 { self.opaque.read_i64() }
#[inline]
fn read_i32(&mut self) -> i32 { self.opaque.read_i32() }
#[inline]
fn read_i16(&mut self) -> i16 { self.opaque.read_i16() }
#[inline]
fn read_raw_bytes(&mut self, len: usize) -> &[u8] {
self.opaque.read_raw_bytes(len)
}
#[inline]
fn peek_byte(&self) -> u8 { self.opaque.peek_byte() }
#[inline]
fn position(&self) -> usize { self.opaque.position() }
}
}crate::implement_ty_decoder!(CacheDecoder<'a, 'tcx>);
562
563impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for Vec<u8> {
567 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
568 Decodable::decode(&mut d.opaque)
569 }
570}
571
572impl<'a, 'tcx> SpanDecoder for CacheDecoder<'a, 'tcx> {
573 fn decode_syntax_context(&mut self) -> SyntaxContext {
574 let syntax_contexts = self.syntax_contexts;
575 rustc_span::hygiene::decode_syntax_context(self, self.hygiene_context, |this, id| {
576 let pos = syntax_contexts.get(&id).unwrap();
579 this.with_position(pos.to_usize(), |decoder| {
580 let data: SyntaxContextKey = decode_tagged(decoder, TAG_SYNTAX_CONTEXT);
581 data
582 })
583 })
584 }
585
586 fn decode_expn_id(&mut self) -> ExpnId {
587 let hash = ExpnHash::decode(self);
588 if hash.is_root() {
589 return ExpnId::root();
590 }
591
592 if let Some(expn_id) = ExpnId::from_hash(hash) {
593 return expn_id;
594 }
595
596 let krate = self.tcx.stable_crate_id_to_crate_num(hash.stable_crate_id());
597
598 let expn_id = if krate == LOCAL_CRATE {
599 let pos = self
601 .expn_data
602 .get(&hash)
603 .unwrap_or_else(|| {
::core::panicking::panic_fmt(format_args!("Bad hash {0:?} (map {1:?})",
hash, self.expn_data));
}panic!("Bad hash {:?} (map {:?})", hash, self.expn_data));
604
605 let data: ExpnData =
606 self.with_position(pos.to_usize(), |decoder| decode_tagged(decoder, TAG_EXPN_DATA));
607 let expn_id = rustc_span::hygiene::register_local_expn_id(data, hash);
608
609 #[cfg(debug_assertions)]
610 {
611 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
612 let local_hash = self.tcx.with_stable_hashing_context(|mut hcx| {
613 let mut hasher = StableHasher::new();
614 expn_id.expn_data().hash_stable(&mut hcx, &mut hasher);
615 hasher.finish()
616 });
617 if true {
match (&hash.local_hash(), &local_hash) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
};debug_assert_eq!(hash.local_hash(), local_hash);
618 }
619
620 expn_id
621 } else {
622 let index_guess = self.foreign_expn_data[&hash];
623 self.tcx.expn_hash_to_expn_id(krate, index_guess, hash)
624 };
625
626 if true {
match (&expn_id.krate, &krate) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
};debug_assert_eq!(expn_id.krate, krate);
627 expn_id
628 }
629
630 fn decode_span(&mut self) -> Span {
631 let ctxt = SyntaxContext::decode(self);
632 let parent = Option::<LocalDefId>::decode(self);
633 let tag: u8 = Decodable::decode(self);
634
635 let (lo, hi) = match tag {
636 TAG_PARTIAL_SPAN => (BytePos(0), BytePos(0)),
637 TAG_RELATIVE_SPAN => {
638 let dlo = u32::decode(self);
639 let dto = u32::decode(self);
640
641 let enclosing = self.tcx.source_span_untracked(parent.unwrap()).data_untracked();
642 (
643 BytePos(enclosing.lo.0.wrapping_add(dlo)),
644 BytePos(enclosing.lo.0.wrapping_add(dto)),
645 )
646 }
647 TAG_FULL_SPAN => {
648 let file_lo_index = SourceFileIndex::decode(self);
649 let line_lo = usize::decode(self);
650 let col_lo = RelativeBytePos::decode(self);
651 let len = BytePos::decode(self);
652
653 let file_lo = self.file_index_to_file(file_lo_index);
654 let lo = file_lo.lines()[line_lo - 1] + col_lo;
655 let lo = file_lo.absolute_position(lo);
656 let hi = lo + len;
657 (lo, hi)
658 }
659 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
660 };
661
662 Span::new(lo, hi, ctxt, parent)
663 }
664
665 fn decode_crate_num(&mut self) -> CrateNum {
666 let stable_id = StableCrateId::decode(self);
667 let cnum = self.tcx.stable_crate_id_to_crate_num(stable_id);
668 cnum
669 }
670
671 fn decode_def_id(&mut self) -> DefId {
675 let def_path_hash = DefPathHash::decode(self);
677
678 match self.tcx.def_path_hash_to_def_id(def_path_hash) {
684 Some(r) => r,
685 None => {
::core::panicking::panic_fmt(format_args!("Failed to convert DefPathHash {0:?}",
def_path_hash));
}panic!("Failed to convert DefPathHash {def_path_hash:?}"),
686 }
687 }
688
689 fn decode_attr_id(&mut self) -> rustc_span::AttrId {
690 {
::core::panicking::panic_fmt(format_args!("cannot decode `AttrId` with `CacheDecoder`"));
};panic!("cannot decode `AttrId` with `CacheDecoder`");
691 }
692}
693
694impl<'a, 'tcx> BlobDecoder for CacheDecoder<'a, 'tcx> {
695 fn decode_symbol(&mut self) -> Symbol {
696 self.decode_symbol_or_byte_symbol(
697 Symbol::new,
698 |this| Symbol::intern(this.read_str()),
699 |opaque| Symbol::intern(opaque.read_str()),
700 )
701 }
702
703 fn decode_byte_symbol(&mut self) -> ByteSymbol {
704 self.decode_symbol_or_byte_symbol(
705 ByteSymbol::new,
706 |this| ByteSymbol::intern(this.read_byte_str()),
707 |opaque| ByteSymbol::intern(opaque.read_byte_str()),
708 )
709 }
710
711 fn decode_def_index(&mut self) -> DefIndex {
716 {
::core::panicking::panic_fmt(format_args!("trying to decode `DefIndex` outside the context of a `DefId`"));
}panic!("trying to decode `DefIndex` outside the context of a `DefId`")
717 }
718}
719
720impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx UnordSet<LocalDefId> {
721 #[inline]
722 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
723 RefDecodable::decode(d)
724 }
725}
726
727impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>>
728 for &'tcx UnordMap<DefId, ty::EarlyBinder<'tcx, Ty<'tcx>>>
729{
730 #[inline]
731 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
732 RefDecodable::decode(d)
733 }
734}
735
736impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>>
737 for &'tcx IndexVec<mir::Promoted, mir::Body<'tcx>>
738{
739 #[inline]
740 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
741 RefDecodable::decode(d)
742 }
743}
744
745impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [(ty::Clause<'tcx>, Span)] {
746 #[inline]
747 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
748 RefDecodable::decode(d)
749 }
750}
751
752impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [rustc_ast::InlineAsmTemplatePiece] {
753 #[inline]
754 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
755 RefDecodable::decode(d)
756 }
757}
758
759impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [Spanned<MonoItem<'tcx>>] {
760 #[inline]
761 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
762 RefDecodable::decode(d)
763 }
764}
765
766impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>>
767 for &'tcx crate::traits::specialization_graph::Graph
768{
769 #[inline]
770 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
771 RefDecodable::decode(d)
772 }
773}
774
775impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx rustc_ast::tokenstream::TokenStream {
776 #[inline]
777 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
778 RefDecodable::decode(d)
779 }
780}
781
782macro_rules! impl_ref_decoder {
783 (<$tcx:tt> $($ty:ty,)*) => {
784 $(impl<'a, $tcx> Decodable<CacheDecoder<'a, $tcx>> for &$tcx [$ty] {
785 #[inline]
786 fn decode(d: &mut CacheDecoder<'a, $tcx>) -> Self {
787 RefDecodable::decode(d)
788 }
789 })*
790 };
791}
792
793impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for
&'tcx [rustc_middle::middle::deduced_param_attrs::DeducedParamAttrs] {
#[inline]
fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
RefDecodable::decode(d)
}
}impl_ref_decoder! {<'tcx>
794 Span,
795 rustc_hir::Attribute,
796 rustc_span::Ident,
797 ty::Variance,
798 rustc_span::def_id::DefId,
799 rustc_span::def_id::LocalDefId,
800 (rustc_middle::middle::exported_symbols::ExportedSymbol<'tcx>, rustc_middle::middle::exported_symbols::SymbolExportInfo),
801 rustc_middle::middle::deduced_param_attrs::DeducedParamAttrs,
802}
803
804pub struct CacheEncoder<'a, 'tcx> {
808 tcx: TyCtxt<'tcx>,
809 encoder: FileEncoder,
810 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
811 predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
812 interpret_allocs: FxIndexSet<interpret::AllocId>,
813 source_map: CachingSourceMapView<'tcx>,
814 file_to_file_index: FxHashMap<*const SourceFile, SourceFileIndex>,
815 hygiene_context: &'a HygieneEncodeContext,
816 symbol_index_table: FxHashMap<u32, usize>,
818}
819
820impl<'a, 'tcx> fmt::Debug for CacheEncoder<'a, 'tcx> {
821 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
822 f.write_str("CacheEncoder")
824 }
825}
826
827impl<'a, 'tcx> CacheEncoder<'a, 'tcx> {
828 #[inline]
829 fn source_file_index(&mut self, source_file: Arc<SourceFile>) -> SourceFileIndex {
830 self.file_to_file_index[&(&raw const *source_file)]
831 }
832
833 pub fn encode_tagged<T: Encodable<Self>, V: Encodable<Self>>(&mut self, tag: T, value: &V) {
839 let start_pos = self.position();
840
841 tag.encode(self);
842 value.encode(self);
843
844 let end_pos = self.position();
845 ((end_pos - start_pos) as u64).encode(self);
846 }
847
848 fn encode_symbol_or_byte_symbol(
850 &mut self,
851 index: u32,
852 emit_str_or_byte_str: impl Fn(&mut Self),
853 ) {
854 if Symbol::is_predefined(index) {
856 self.encoder.emit_u8(SYMBOL_PREDEFINED);
857 self.encoder.emit_u32(index);
858 } else {
859 match self.symbol_index_table.entry(index) {
861 Entry::Vacant(o) => {
862 self.encoder.emit_u8(SYMBOL_STR);
863 let pos = self.encoder.position();
864 o.insert(pos);
865 emit_str_or_byte_str(self);
866 }
867 Entry::Occupied(o) => {
868 let x = *o.get();
869 self.emit_u8(SYMBOL_OFFSET);
870 self.emit_usize(x);
871 }
872 }
873 }
874 }
875
876 #[inline]
877 fn finish(mut self) -> FileEncodeResult {
878 self.encoder.finish()
879 }
880}
881
882impl<'a, 'tcx> SpanEncoder for CacheEncoder<'a, 'tcx> {
883 fn encode_syntax_context(&mut self, syntax_context: SyntaxContext) {
884 rustc_span::hygiene::raw_encode_syntax_context(syntax_context, self.hygiene_context, self);
885 }
886
887 fn encode_expn_id(&mut self, expn_id: ExpnId) {
888 self.hygiene_context.schedule_expn_data_for_encoding(expn_id);
889 expn_id.expn_hash().encode(self);
890 }
891
892 fn encode_span(&mut self, span: Span) {
893 let span_data = span.data_untracked();
894 span_data.ctxt.encode(self);
895 span_data.parent.encode(self);
896
897 if span_data.is_dummy() {
898 return TAG_PARTIAL_SPAN.encode(self);
899 }
900
901 let parent =
902 span_data.parent.map(|parent| self.tcx.source_span_untracked(parent).data_untracked());
903 if let Some(parent) = parent
904 && parent.contains(span_data)
905 {
906 TAG_RELATIVE_SPAN.encode(self);
907 (span_data.lo.0.wrapping_sub(parent.lo.0)).encode(self);
908 (span_data.hi.0.wrapping_sub(parent.lo.0)).encode(self);
909 return;
910 }
911
912 let Some((file_lo, line_lo, col_lo)) =
913 self.source_map.byte_pos_to_line_and_col(span_data.lo)
914 else {
915 return TAG_PARTIAL_SPAN.encode(self);
916 };
917
918 if let Some(parent) = parent
919 && file_lo.contains(parent.lo)
920 {
921 TAG_RELATIVE_SPAN.encode(self);
922 (span_data.lo.0.wrapping_sub(parent.lo.0)).encode(self);
923 (span_data.hi.0.wrapping_sub(parent.lo.0)).encode(self);
924 return;
925 }
926
927 let len = span_data.hi - span_data.lo;
928 let source_file_index = self.source_file_index(file_lo);
929
930 TAG_FULL_SPAN.encode(self);
931 source_file_index.encode(self);
932 line_lo.encode(self);
933 col_lo.encode(self);
934 len.encode(self);
935 }
936
937 fn encode_symbol(&mut self, sym: Symbol) {
938 self.encode_symbol_or_byte_symbol(sym.as_u32(), |this| this.emit_str(sym.as_str()));
939 }
940
941 fn encode_byte_symbol(&mut self, byte_sym: ByteSymbol) {
942 self.encode_symbol_or_byte_symbol(byte_sym.as_u32(), |this| {
943 this.emit_byte_str(byte_sym.as_byte_str())
944 });
945 }
946
947 fn encode_crate_num(&mut self, crate_num: CrateNum) {
948 self.tcx.stable_crate_id(crate_num).encode(self);
949 }
950
951 fn encode_def_id(&mut self, def_id: DefId) {
952 self.tcx.def_path_hash(def_id).encode(self);
953 }
954
955 fn encode_def_index(&mut self, _def_index: DefIndex) {
956 crate::util::bug::bug_fmt(format_args!("encoding `DefIndex` without context"));bug!("encoding `DefIndex` without context");
957 }
958}
959
960impl<'a, 'tcx> TyEncoder<'tcx> for CacheEncoder<'a, 'tcx> {
961 const CLEAR_CROSS_CRATE: bool = false;
962
963 #[inline]
964 fn position(&self) -> usize {
965 self.encoder.position()
966 }
967 #[inline]
968 fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
969 &mut self.type_shorthands
970 }
971 #[inline]
972 fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
973 &mut self.predicate_shorthands
974 }
975 #[inline]
976 fn encode_alloc_id(&mut self, alloc_id: &interpret::AllocId) {
977 let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
978
979 index.encode(self);
980 }
981}
982
983macro_rules! encoder_methods {
984 ($($name:ident($ty:ty);)*) => {
985 #[inline]
986 $(fn $name(&mut self, value: $ty) {
987 self.encoder.$name(value)
988 })*
989 }
990}
991
992impl<'a, 'tcx> Encoder for CacheEncoder<'a, 'tcx> {
993 self
value
self.encoder.emit_raw_bytes(value);encoder_methods! {
994 emit_usize(usize);
995 emit_u128(u128);
996 emit_u64(u64);
997 emit_u32(u32);
998 emit_u16(u16);
999 emit_u8(u8);
1000
1001 emit_isize(isize);
1002 emit_i128(i128);
1003 emit_i64(i64);
1004 emit_i32(i32);
1005 emit_i16(i16);
1006
1007 emit_raw_bytes(&[u8]);
1008 }
1009}
1010
1011impl<'a, 'tcx> Encodable<CacheEncoder<'a, 'tcx>> for [u8] {
1016 fn encode(&self, e: &mut CacheEncoder<'a, 'tcx>) {
1017 self.encode(&mut e.encoder);
1018 }
1019}