Skip to main content

rustc_middle/query/
on_disk_cache.rs

1use std::collections::hash_map::Entry;
2use std::sync::Arc;
3use std::{fmt, mem};
4
5use rustc_data_structures::fx::{FxHashMap, 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::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::{self, interpret};
28use crate::mono::MonoItem;
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
34// A normal span encoded with both location information and a `SyntaxContext`
35const TAG_FULL_SPAN: u8 = 0;
36// A partial span with no location information, encoded only with a `SyntaxContext`
37const 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
43// Tags for encoding Symbols and ByteSymbols
44const SYMBOL_STR: u8 = 0;
45const SYMBOL_OFFSET: u8 = 1;
46const SYMBOL_PREDEFINED: u8 = 2;
47
48/// Provides an interface to incremental compilation data cached from the
49/// previous compilation session. This data will eventually include the results
50/// of a few selected queries (like `typeck` and `mir_optimized`) and
51/// any side effects that have been emitted during a query.
52pub struct OnDiskCache {
53    // The complete cache data in serialized form.
54    serialized_data: RwLock<Option<Mmap>>,
55
56    file_index_to_stable_id: FxHashMap<SourceFileIndex, EncodedSourceFileId>,
57
58    // Caches that are populated lazily during decoding.
59    file_index_to_file: Lock<FxHashMap<SourceFileIndex, Arc<SourceFile>>>,
60
61    /// For query dep nodes that have a disk-cached return value, maps the node
62    /// index to the position of its serialized value in `serialized_data`.
63    query_values_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
64
65    /// For `DepKind::SideEffect` dep nodes, maps the node index to the position
66    /// of its serialized [`QuerySideEffect`] in `serialized_data`.
67    side_effects_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
68
69    alloc_decoding_state: AllocDecodingState,
70
71    // A map from syntax context ids to the position of their associated
72    // `SyntaxContextData`. We use a `u32` instead of a `SyntaxContext`
73    // to represent the fact that we are storing *encoded* ids. When we decode
74    // a `SyntaxContext`, a new id will be allocated from the global `HygieneData`,
75    // which will almost certainly be different than the serialized id.
76    syntax_contexts: FxHashMap<u32, AbsoluteBytePos>,
77    // A map from the `DefPathHash` of an `ExpnId` to the position
78    // of their associated `ExpnData`. Ideally, we would store a `DefId`,
79    // but we need to decode this before we've constructed a `TyCtxt` (which
80    // makes it difficult to decode a `DefId`).
81
82    // Note that these `DefPathHashes` correspond to both local and foreign
83    // `ExpnData` (e.g `ExpnData.krate` may not be `LOCAL_CRATE`). Alternatively,
84    // we could look up the `ExpnData` from the metadata of foreign crates,
85    // but it seemed easier to have `OnDiskCache` be independent of the `CStore`.
86    expn_data: UnhashMap<ExpnHash, AbsoluteBytePos>,
87    // Additional information used when decoding hygiene data.
88    hygiene_context: HygieneDecodeContext,
89    // Maps `ExpnHash`es to their raw value from the *previous*
90    // compilation session. This is used as an initial 'guess' when
91    // we try to map an `ExpnHash` to its value in the current
92    // compilation session.
93    foreign_expn_data: UnhashMap<ExpnHash, u32>,
94}
95
96// This type is used only for serialization and deserialization.
97#[derive(const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for Footer {
            fn encode(&self, __encoder: &mut __E) {
                let Footer {
                        file_index_to_stable_id: ref __binding_0,
                        query_values_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 } = *self;
                ::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_values_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)]
98struct Footer {
99    file_index_to_stable_id: FxHashMap<SourceFileIndex, EncodedSourceFileId>,
100    query_values_index: Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>,
101    side_effects_index: Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>,
102    // The location of all allocations.
103    // Most uses only need values up to u32::MAX, but benchmarking indicates that we can use a u64
104    // without measurable overhead. This permits larger const allocations without ICEing.
105    interpret_alloc_index: Vec<u64>,
106    // See `OnDiskCache.syntax_contexts`
107    syntax_contexts: FxHashMap<u32, AbsoluteBytePos>,
108    // See `OnDiskCache.expn_data`
109    expn_data: UnhashMap<ExpnHash, AbsoluteBytePos>,
110    foreign_expn_data: UnhashMap<ExpnHash, u32>,
111}
112
113#[derive(#[automatically_derived]
impl ::core::marker::Copy for SourceFileIndex { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for SourceFileIndex { }
#[automatically_derived]
impl ::core::clone::Clone for SourceFileIndex {
    #[inline]
    fn clone(&self) -> SourceFileIndex {
        let _: ::core::clone::AssertParamIsClone<u32>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for SourceFileIndex { }
#[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) {
                let SourceFileIndex(ref __binding_0) = *self;
                ::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)]
114struct SourceFileIndex(u32);
115
116#[derive(#[automatically_derived]
impl ::core::marker::Copy for AbsoluteBytePos { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for AbsoluteBytePos { }
#[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::marker::StructuralPartialEq for AbsoluteBytePos { }
#[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) {
                let AbsoluteBytePos(ref __binding_0) = *self;
                ::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)]
117struct AbsoluteBytePos(u64);
118
119impl AbsoluteBytePos {
120    #[inline]
121    fn new(pos: usize) -> AbsoluteBytePos {
122        AbsoluteBytePos(pos.try_into().expect("Incremental cache file size overflowed u64."))
123    }
124
125    #[inline]
126    fn to_usize(self) -> usize {
127        self.0 as usize
128    }
129}
130
131#[derive(const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for EncodedSourceFileId {
            fn encode(&self, __encoder: &mut __E) {
                let EncodedSourceFileId {
                        stable_source_file_id: ref __binding_0,
                        stable_crate_id: ref __binding_1 } = *self;
                ::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)]
132struct EncodedSourceFileId {
133    stable_source_file_id: StableSourceFileId,
134    stable_crate_id: StableCrateId,
135}
136
137impl EncodedSourceFileId {
138    #[inline]
139    fn new(tcx: TyCtxt<'_>, file: &SourceFile) -> EncodedSourceFileId {
140        EncodedSourceFileId {
141            stable_source_file_id: file.stable_id,
142            stable_crate_id: tcx.stable_crate_id(file.cnum),
143        }
144    }
145}
146
147impl OnDiskCache {
148    /// Creates a new `OnDiskCache` instance from the serialized data in `data`.
149    ///
150    /// The serialized cache has some basic integrity checks, if those checks indicate that the
151    /// on-disk data is corrupt, an error is returned.
152    pub fn new(sess: &Session, data: Mmap, start_pos: usize) -> Result<Self, ()> {
153        if !sess.opts.incremental.is_some() {
    ::core::panicking::panic("assertion failed: sess.opts.incremental.is_some()")
};assert!(sess.opts.incremental.is_some());
154
155        let mut decoder = MemDecoder::new(&data, start_pos)?;
156
157        // Decode the *position* of the footer, which can be found in the
158        // last 8 bytes of the file.
159        let footer_pos = decoder
160            .with_position(decoder.len() - IntEncodedWithFixedSize::ENCODED_SIZE, |decoder| {
161                IntEncodedWithFixedSize::decode(decoder).0 as usize
162            });
163        // Decode the file footer, which contains all the lookup tables, etc.
164        let footer: Footer =
165            decoder.with_position(footer_pos, |decoder| decode_tagged(decoder, TAG_FILE_FOOTER));
166
167        Ok(Self {
168            serialized_data: RwLock::new(Some(data)),
169            file_index_to_stable_id: footer.file_index_to_stable_id,
170            file_index_to_file: Default::default(),
171            query_values_index: footer.query_values_index.into_iter().collect(),
172            side_effects_index: footer.side_effects_index.into_iter().collect(),
173            alloc_decoding_state: AllocDecodingState::new(footer.interpret_alloc_index),
174            syntax_contexts: footer.syntax_contexts,
175            expn_data: footer.expn_data,
176            foreign_expn_data: footer.foreign_expn_data,
177            hygiene_context: Default::default(),
178        })
179    }
180
181    pub fn new_empty() -> Self {
182        Self {
183            serialized_data: RwLock::new(None),
184            file_index_to_stable_id: Default::default(),
185            file_index_to_file: Default::default(),
186            query_values_index: Default::default(),
187            side_effects_index: Default::default(),
188            alloc_decoding_state: AllocDecodingState::new(Vec::new()),
189            syntax_contexts: FxHashMap::default(),
190            expn_data: UnhashMap::default(),
191            foreign_expn_data: UnhashMap::default(),
192            hygiene_context: Default::default(),
193        }
194    }
195
196    /// Release the serialized backing `Mmap`.
197    pub fn close_serialized_data_mmap(&self) {
198        // Obtain a write lock, and replace the mmap with None to drop it.
199        *self.serialized_data.write() = None;
200    }
201
202    /// Serialize the current-session data that will be loaded by [`OnDiskCache`]
203    /// in a subsequent incremental compilation session.
204    pub fn serialize(tcx: TyCtxt<'_>, encoder: FileEncoder<'static>) -> FileEncodeResult {
205        // Serializing the `DepGraph` should not modify it.
206        tcx.dep_graph.with_ignore(|| {
207            // Allocate `SourceFileIndex`es.
208            let (file_to_file_index, file_index_to_stable_id) = {
209                let files = tcx.sess.source_map().files();
210                let mut file_to_file_index =
211                    FxHashMap::with_capacity_and_hasher(files.len(), Default::default());
212                let mut file_index_to_stable_id =
213                    FxHashMap::with_capacity_and_hasher(files.len(), Default::default());
214
215                for (index, file) in files.iter().enumerate() {
216                    let index = SourceFileIndex(index as u32);
217                    let file_ptr: *const SourceFile = &raw const **file;
218                    file_to_file_index.insert(file_ptr, index);
219                    let source_file_id = EncodedSourceFileId::new(tcx, file);
220                    file_index_to_stable_id.insert(index, source_file_id);
221                }
222
223                (file_to_file_index, file_index_to_stable_id)
224            };
225
226            let hygiene_encode_context = HygieneEncodeContext::default();
227
228            let mut encoder = CacheEncoder {
229                tcx,
230                encoder,
231                type_shorthands: Default::default(),
232                predicate_shorthands: Default::default(),
233                interpret_allocs: Default::default(),
234                caching_source_map_view: CachingSourceMapView::new(tcx.sess.source_map()),
235                file_to_file_index,
236                hygiene_context: &hygiene_encode_context,
237                symbol_index_table: Default::default(),
238                query_values_index: Default::default(),
239                side_effects_index: Default::default(),
240            };
241
242            // Encode query return values.
243            tcx.sess.time("encode_query_values", || {
244                tcx.encode_query_values(&mut encoder);
245            });
246
247            // Encode side effects.
248            for (&dep_node_index, side_effect) in tcx.query_system.side_effects.borrow().iter() {
249                encoder.encode_side_effect(dep_node_index, side_effect);
250            }
251
252            let interpret_alloc_index = {
253                let mut interpret_alloc_index = Vec::new();
254                let mut n = 0;
255                loop {
256                    let new_n = encoder.interpret_allocs.len();
257                    // If we have found new IDs, serialize those too.
258                    if n == new_n {
259                        // Otherwise, abort.
260                        break;
261                    }
262                    interpret_alloc_index.reserve(new_n - n);
263                    for idx in n..new_n {
264                        let id = encoder.interpret_allocs[idx];
265                        let pos: u64 = encoder.position().try_into().unwrap();
266                        interpret_alloc_index.push(pos);
267                        interpret::specialized_encode_alloc_id(&mut encoder, tcx, id);
268                    }
269                    n = new_n;
270                }
271                interpret_alloc_index
272            };
273
274            let mut syntax_contexts = FxHashMap::default();
275            let mut expn_data = UnhashMap::default();
276            let mut foreign_expn_data = UnhashMap::default();
277
278            // Encode all hygiene data (`SyntaxContextData` and `ExpnData`) from the current
279            // session.
280
281            hygiene_encode_context.encode(
282                &mut encoder,
283                |encoder, index, ctxt_data| {
284                    let pos = AbsoluteBytePos::new(encoder.position());
285                    encoder.encode_tagged(TAG_SYNTAX_CONTEXT, ctxt_data);
286                    syntax_contexts.insert(index, pos);
287                },
288                |encoder, expn_id, data, hash| {
289                    if expn_id.krate == LOCAL_CRATE {
290                        let pos = AbsoluteBytePos::new(encoder.position());
291                        encoder.encode_tagged(TAG_EXPN_DATA, data);
292                        expn_data.insert(hash, pos);
293                    } else {
294                        foreign_expn_data.insert(hash, expn_id.local_id.as_u32());
295                    }
296                },
297            );
298
299            // Encode the file footer.
300            let footer_pos = encoder.position() as u64;
301            let query_values_index = mem::take(&mut encoder.query_values_index);
302            let side_effects_index = mem::take(&mut encoder.side_effects_index);
303            encoder.encode_tagged(
304                TAG_FILE_FOOTER,
305                &Footer {
306                    file_index_to_stable_id,
307                    query_values_index,
308                    side_effects_index,
309                    interpret_alloc_index,
310                    syntax_contexts,
311                    expn_data,
312                    foreign_expn_data,
313                },
314            );
315
316            // Encode the position of the footer as the last 8 bytes of the
317            // file so we know where to look for it.
318            IntEncodedWithFixedSize(footer_pos).encode(&mut encoder.encoder);
319
320            // DO NOT WRITE ANYTHING TO THE ENCODER AFTER THIS POINT! The address
321            // of the footer must be the last thing in the data stream.
322
323            encoder.finish()
324        })
325    }
326
327    /// Loads a `QuerySideEffect` created during the previous compilation session.
328    pub(crate) fn load_side_effect(
329        &self,
330        tcx: TyCtxt<'_>,
331        dep_node_index: SerializedDepNodeIndex,
332    ) -> Option<QuerySideEffect> {
333        let side_effect: Option<QuerySideEffect> =
334            self.load_indexed(tcx, dep_node_index, &self.side_effects_index);
335        side_effect
336    }
337
338    /// Returns the disk-cached query return value for the given node, if there is one.
339    pub fn try_load_query_value<'tcx, T>(
340        &self,
341        tcx: TyCtxt<'tcx>,
342        dep_node_index: SerializedDepNodeIndex,
343    ) -> Option<T>
344    where
345        T: for<'a> Decodable<CacheDecoder<'a, 'tcx>>,
346    {
347        self.load_indexed(tcx, dep_node_index, &self.query_values_index)
348    }
349
350    fn load_indexed<'tcx, T>(
351        &self,
352        tcx: TyCtxt<'tcx>,
353        dep_node_index: SerializedDepNodeIndex,
354        index: &FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
355    ) -> Option<T>
356    where
357        T: for<'a> Decodable<CacheDecoder<'a, 'tcx>>,
358    {
359        let pos = index.get(&dep_node_index).cloned()?;
360        let value = self.with_decoder(tcx, pos, |decoder| decode_tagged(decoder, dep_node_index));
361        Some(value)
362    }
363
364    fn with_decoder<'a, 'tcx, T, F: for<'s> FnOnce(&mut CacheDecoder<'s, 'tcx>) -> T>(
365        &self,
366        tcx: TyCtxt<'tcx>,
367        pos: AbsoluteBytePos,
368        f: F,
369    ) -> T
370    where
371        T: Decodable<CacheDecoder<'a, 'tcx>>,
372    {
373        let serialized_data = self.serialized_data.read();
374        let mut decoder = CacheDecoder {
375            tcx,
376            opaque: MemDecoder::new(serialized_data.as_deref().unwrap_or(&[]), pos.to_usize())
377                .unwrap(),
378            file_index_to_file: &self.file_index_to_file,
379            file_index_to_stable_id: &self.file_index_to_stable_id,
380            alloc_decoding_session: self.alloc_decoding_state.new_decoding_session(),
381            syntax_contexts: &self.syntax_contexts,
382            expn_data: &self.expn_data,
383            foreign_expn_data: &self.foreign_expn_data,
384            hygiene_context: &self.hygiene_context,
385        };
386        f(&mut decoder)
387    }
388}
389
390//- DECODING -------------------------------------------------------------------
391
392/// A decoder that can read from the incremental compilation cache. It is similar to the one
393/// we use for crate metadata decoding in that it can rebase spans and eventually
394/// will also handle things that contain `Ty` instances.
395pub struct CacheDecoder<'a, 'tcx> {
396    tcx: TyCtxt<'tcx>,
397    opaque: MemDecoder<'a>,
398    file_index_to_file: &'a Lock<FxHashMap<SourceFileIndex, Arc<SourceFile>>>,
399    file_index_to_stable_id: &'a FxHashMap<SourceFileIndex, EncodedSourceFileId>,
400    alloc_decoding_session: AllocDecodingSession<'a>,
401    syntax_contexts: &'a FxHashMap<u32, AbsoluteBytePos>,
402    expn_data: &'a UnhashMap<ExpnHash, AbsoluteBytePos>,
403    foreign_expn_data: &'a UnhashMap<ExpnHash, u32>,
404    hygiene_context: &'a HygieneDecodeContext,
405}
406
407impl<'a, 'tcx> CacheDecoder<'a, 'tcx> {
408    #[inline]
409    fn file_index_to_file(&self, index: SourceFileIndex) -> Arc<SourceFile> {
410        let CacheDecoder { tcx, file_index_to_file, file_index_to_stable_id, .. } = *self;
411
412        Arc::clone(file_index_to_file.borrow_mut().entry(index).or_insert_with(|| {
413            let source_file_id = &file_index_to_stable_id[&index];
414            let source_file_cnum = tcx.stable_crate_id_to_crate_num(source_file_id.stable_crate_id);
415
416            // If this `SourceFile` is from a foreign crate, then make sure
417            // that we've imported all of the source files from that crate.
418            // This has usually already been done during macro invocation.
419            // However, when encoding query results like `TypeckResults`,
420            // we might encode an `AdtDef` for a foreign type (because it
421            // was referenced in the body of the function). There is no guarantee
422            // that we will load the source files from that crate during macro
423            // expansion, so we use `import_source_files` to ensure that the foreign
424            // source files are actually imported before we call `source_file_by_stable_id`.
425            if source_file_cnum != LOCAL_CRATE {
426                self.tcx.import_source_files(source_file_cnum);
427            }
428
429            tcx.sess
430                .source_map()
431                .source_file_by_stable_id(source_file_id.stable_source_file_id)
432                .expect("failed to lookup `SourceFile` in new context")
433        }))
434    }
435
436    // copy&paste impl from rustc_metadata
437    #[inline]
438    fn decode_symbol_or_byte_symbol<S>(
439        &mut self,
440        new_from_index: impl Fn(u32) -> S,
441        read_and_intern_str_or_byte_str_this: impl Fn(&mut Self) -> S,
442        read_and_intern_str_or_byte_str_opaque: impl Fn(&mut MemDecoder<'a>) -> S,
443    ) -> S {
444        let tag = self.read_u8();
445
446        match tag {
447            SYMBOL_STR => read_and_intern_str_or_byte_str_this(self),
448            SYMBOL_OFFSET => {
449                // read str offset
450                let pos = self.read_usize();
451
452                // move to str offset and read
453                self.opaque.with_position(pos, |d| read_and_intern_str_or_byte_str_opaque(d))
454            }
455            SYMBOL_PREDEFINED => new_from_index(self.read_u32()),
456            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
457        }
458    }
459}
460
461// Decodes something that was encoded with `encode_tagged()` and verify that the
462// tag matches and the correct amount of bytes was read.
463fn decode_tagged<D, T, V>(decoder: &mut D, expected_tag: T) -> V
464where
465    T: Decodable<D> + Eq + fmt::Debug,
466    V: Decodable<D>,
467    D: Decoder,
468{
469    let start_pos = decoder.position();
470
471    let actual_tag = T::decode(decoder);
472    {
    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);
473    let value = V::decode(decoder);
474    let end_pos = decoder.position();
475
476    let expected_len: u64 = Decodable::decode(decoder);
477    {
    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);
478
479    value
480}
481
482impl<'a, 'tcx> TyDecoder<'tcx> for CacheDecoder<'a, 'tcx> {
483    const CLEAR_CROSS_CRATE: bool = false;
484
485    fn cached_ty_for_shorthand<F>(&mut self, shorthand: usize, or_insert_with: F) -> Ty<'tcx>
486    where
487        F: FnOnce(&mut Self) -> Ty<'tcx>,
488    {
489        let tcx = self.tcx;
490
491        let cache_key = ty::CReaderCacheKey { cnum: None, pos: shorthand };
492
493        if let Some(&ty) = tcx.caches.ty_rcache.borrow().get(&cache_key) {
494            return ty;
495        }
496
497        let ty = or_insert_with(self);
498        // This may overwrite the entry, but it should overwrite with the same value.
499        tcx.caches.ty_rcache.borrow_mut().insert_same(cache_key, ty);
500        ty
501    }
502
503    fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
504    where
505        F: FnOnce(&mut Self) -> R,
506    {
507        if true {
    if !(pos < self.opaque.len()) {
        ::core::panicking::panic("assertion failed: pos < self.opaque.len()")
    };
};debug_assert!(pos < self.opaque.len());
508
509        let new_opaque = self.opaque.split_at(pos);
510        let old_opaque = mem::replace(&mut self.opaque, new_opaque);
511        let r = f(self);
512        self.opaque = old_opaque;
513        r
514    }
515
516    fn decode_alloc_id(&mut self) -> interpret::AllocId {
517        let alloc_decoding_session = self.alloc_decoding_session;
518        alloc_decoding_session.decode_alloc_id(self)
519    }
520}
521
522impl<'a, 'tcx> rustc_type_ir::InternerDecoder for CacheDecoder<'a, 'tcx> {
523    type Interner = TyCtxt<'tcx>;
524
525    #[inline]
526    fn interner(&self) -> Self::Interner {
527        self.tcx
528    }
529}
530
531mod __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>);
532
533// This ensures that the `Decodable<opaque::Decoder>::decode` specialization for `Vec<u8>` is used
534// when a `CacheDecoder` is passed to `Decodable::decode`. Unfortunately, we have to manually opt
535// into specializations this way, given how `CacheDecoder` and the decoding traits currently work.
536impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for Vec<u8> {
537    fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
538        Decodable::decode(&mut d.opaque)
539    }
540}
541
542impl<'a, 'tcx> SpanDecoder for CacheDecoder<'a, 'tcx> {
543    fn decode_syntax_context(&mut self) -> SyntaxContext {
544        let syntax_contexts = self.syntax_contexts;
545        rustc_span::hygiene::decode_syntax_context(self, self.hygiene_context, |this, id| {
546            // This closure is invoked if we haven't already decoded the data for the `SyntaxContext` we are deserializing.
547            // We look up the position of the associated `SyntaxData` and decode it.
548            let pos = syntax_contexts.get(&id).unwrap();
549            this.with_position(pos.to_usize(), |decoder| {
550                let data: SyntaxContextKey = decode_tagged(decoder, TAG_SYNTAX_CONTEXT);
551                data
552            })
553        })
554    }
555
556    fn decode_expn_id(&mut self) -> ExpnId {
557        let hash = ExpnHash::decode(self);
558        if hash.is_root() {
559            return ExpnId::root();
560        }
561
562        if let Some(expn_id) = ExpnId::from_hash(hash) {
563            return expn_id;
564        }
565
566        let krate = self.tcx.stable_crate_id_to_crate_num(hash.stable_crate_id());
567
568        let expn_id = if krate == LOCAL_CRATE {
569            // We look up the position of the associated `ExpnData` and decode it.
570            let pos = self
571                .expn_data
572                .get(&hash)
573                .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));
574
575            let data: ExpnData =
576                self.with_position(pos.to_usize(), |decoder| decode_tagged(decoder, TAG_EXPN_DATA));
577            let expn_id = rustc_span::hygiene::register_local_expn_id(data, hash);
578
579            #[cfg(debug_assertions)]
580            {
581                use rustc_data_structures::stable_hash::{StableHash, StableHasher};
582                let local_hash = self.tcx.with_stable_hashing_context(|mut hcx| {
583                    let mut hasher = StableHasher::new();
584                    expn_id.expn_data().stable_hash(&mut hcx, &mut hasher);
585                    hasher.finish()
586                });
587                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);
588            }
589
590            expn_id
591        } else {
592            let index_guess = self.foreign_expn_data[&hash];
593            self.tcx.expn_hash_to_expn_id(krate, index_guess, hash)
594        };
595
596        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);
597        expn_id
598    }
599
600    fn decode_span(&mut self) -> Span {
601        let ctxt = SyntaxContext::decode(self);
602        let parent = Option::<LocalDefId>::decode(self);
603        let tag: u8 = Decodable::decode(self);
604
605        let (lo, hi) = match tag {
606            TAG_PARTIAL_SPAN => (BytePos(0), BytePos(0)),
607            TAG_RELATIVE_SPAN => {
608                let dlo = u32::decode(self);
609                let dto = u32::decode(self);
610
611                let enclosing = self.tcx.source_span_untracked(parent.unwrap()).data_untracked();
612                (
613                    BytePos(enclosing.lo.0.wrapping_add(dlo)),
614                    BytePos(enclosing.lo.0.wrapping_add(dto)),
615                )
616            }
617            TAG_FULL_SPAN => {
618                let file_lo_index = SourceFileIndex::decode(self);
619                let line_lo = usize::decode(self);
620                let col_lo = RelativeBytePos::decode(self);
621                let len = BytePos::decode(self);
622
623                let file_lo = self.file_index_to_file(file_lo_index);
624                let lo = file_lo.lines()[line_lo - 1] + col_lo;
625                let lo = file_lo.absolute_position(lo);
626                let hi = lo + len;
627                (lo, hi)
628            }
629            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
630        };
631
632        Span::new(lo, hi, ctxt, parent)
633    }
634
635    fn decode_crate_num(&mut self) -> CrateNum {
636        let stable_id = StableCrateId::decode(self);
637        let cnum = self.tcx.stable_crate_id_to_crate_num(stable_id);
638        cnum
639    }
640
641    // Both the `CrateNum` and the `DefIndex` of a `DefId` can change in between two
642    // compilation sessions. We use the `DefPathHash`, which is stable across
643    // sessions, to map the old `DefId` to the new one.
644    fn decode_def_id(&mut self) -> DefId {
645        // Load the `DefPathHash` which is was we encoded the `DefId` as.
646        let def_path_hash = DefPathHash::decode(self);
647
648        // Using the `DefPathHash`, we can lookup the new `DefId`.
649        // Subtle: We only encode a `DefId` as part of a query result.
650        // If we get to this point, then all of the query inputs were green,
651        // which means that the definition with this hash is guaranteed to
652        // still exist in the current compilation session.
653        match self.tcx.def_path_hash_to_def_id(def_path_hash) {
654            Some(r) => r,
655            None => {
    ::core::panicking::panic_fmt(format_args!("Failed to convert DefPathHash {0:?}",
            def_path_hash));
}panic!("Failed to convert DefPathHash {def_path_hash:?}"),
656        }
657    }
658
659    fn decode_attr_id(&mut self) -> rustc_span::AttrId {
660        {
    ::core::panicking::panic_fmt(format_args!("cannot decode `AttrId` with `CacheDecoder`"));
};panic!("cannot decode `AttrId` with `CacheDecoder`");
661    }
662}
663
664impl<'a, 'tcx> BlobDecoder for CacheDecoder<'a, 'tcx> {
665    fn decode_symbol(&mut self) -> Symbol {
666        self.decode_symbol_or_byte_symbol(
667            Symbol::new,
668            |this| Symbol::intern(this.read_str()),
669            |opaque| Symbol::intern(opaque.read_str()),
670        )
671    }
672
673    fn decode_byte_symbol(&mut self) -> ByteSymbol {
674        self.decode_symbol_or_byte_symbol(
675            ByteSymbol::new,
676            |this| ByteSymbol::intern(this.read_byte_str()),
677            |opaque| ByteSymbol::intern(opaque.read_byte_str()),
678        )
679    }
680
681    // This impl makes sure that we get a runtime error when we try decode a
682    // `DefIndex` that is not contained in a `DefId`. Such a case would be problematic
683    // because we would not know how to transform the `DefIndex` to the current
684    // context.
685    fn decode_def_index(&mut self) -> DefIndex {
686        {
    ::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`")
687    }
688}
689
690impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx UnordSet<LocalDefId> {
691    #[inline]
692    fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
693        RefDecodable::decode(d)
694    }
695}
696
697impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>>
698    for &'tcx UnordMap<DefId, ty::EarlyBinder<'tcx, Ty<'tcx>>>
699{
700    #[inline]
701    fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
702        RefDecodable::decode(d)
703    }
704}
705
706impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>>
707    for &'tcx IndexVec<mir::Promoted, mir::Body<'tcx>>
708{
709    #[inline]
710    fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
711        RefDecodable::decode(d)
712    }
713}
714
715impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [(ty::Clause<'tcx>, Span)] {
716    #[inline]
717    fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
718        RefDecodable::decode(d)
719    }
720}
721
722impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [rustc_ast::InlineAsmTemplatePiece] {
723    #[inline]
724    fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
725        RefDecodable::decode(d)
726    }
727}
728
729impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [Spanned<MonoItem<'tcx>>] {
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 crate::traits::specialization_graph::Graph
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 rustc_ast::tokenstream::TokenStream {
746    #[inline]
747    fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
748        RefDecodable::decode(d)
749    }
750}
751
752macro_rules! impl_ref_decoder {
753    (<$tcx:tt> $($ty:ty,)*) => {
754        $(impl<'a, $tcx> Decodable<CacheDecoder<'a, $tcx>> for &$tcx [$ty] {
755            #[inline]
756            fn decode(d: &mut CacheDecoder<'a, $tcx>) -> Self {
757                RefDecodable::decode(d)
758            }
759        })*
760    };
761}
762
763impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [Span] {
    #[inline]
    fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
        RefDecodable::decode(d)
    }
}
impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for
    &'tcx [rustc_hir::Attribute] {
    #[inline]
    fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
        RefDecodable::decode(d)
    }
}
impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [rustc_span::Ident]
    {
    #[inline]
    fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
        RefDecodable::decode(d)
    }
}
impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [ty::Variance] {
    #[inline]
    fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
        RefDecodable::decode(d)
    }
}
impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for
    &'tcx [rustc_span::def_id::DefId] {
    #[inline]
    fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
        RefDecodable::decode(d)
    }
}
impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for
    &'tcx [rustc_span::def_id::LocalDefId] {
    #[inline]
    fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
        RefDecodable::decode(d)
    }
}
impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for
    &'tcx [(rustc_middle::middle::exported_symbols::ExportedSymbol<'tcx>,
    rustc_middle::middle::exported_symbols::SymbolExportInfo)] {
    #[inline]
    fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
        RefDecodable::decode(d)
    }
}
impl<'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>
764    Span,
765    rustc_hir::Attribute,
766    rustc_span::Ident,
767    ty::Variance,
768    rustc_span::def_id::DefId,
769    rustc_span::def_id::LocalDefId,
770    (rustc_middle::middle::exported_symbols::ExportedSymbol<'tcx>, rustc_middle::middle::exported_symbols::SymbolExportInfo),
771    rustc_middle::middle::deduced_param_attrs::DeducedParamAttrs,
772}
773
774//- ENCODING -------------------------------------------------------------------
775
776/// An encoder that can write to the incremental compilation cache.
777pub struct CacheEncoder<'a, 'tcx> {
778    tcx: TyCtxt<'tcx>,
779    encoder: FileEncoder<'static>,
780    type_shorthands: FxHashMap<Ty<'tcx>, usize>,
781    predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
782    interpret_allocs: FxIndexSet<interpret::AllocId>,
783    caching_source_map_view: CachingSourceMapView<'tcx>,
784    file_to_file_index: FxHashMap<*const SourceFile, SourceFileIndex>,
785    hygiene_context: &'a HygieneEncodeContext,
786    // Used for both `Symbol`s and `ByteSymbol`s.
787    symbol_index_table: FxHashMap<u32, usize>,
788
789    query_values_index: Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>,
790    side_effects_index: Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>,
791}
792
793impl<'a, 'tcx> fmt::Debug for CacheEncoder<'a, 'tcx> {
794    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
795        // Add more details here if/when necessary.
796        f.write_str("CacheEncoder")
797    }
798}
799
800impl<'a, 'tcx> CacheEncoder<'a, 'tcx> {
801    #[inline]
802    fn source_file_index(&mut self, source_file: Arc<SourceFile>) -> SourceFileIndex {
803        self.file_to_file_index[&(&raw const *source_file)]
804    }
805
806    /// Encode something with additional information that allows to do some
807    /// sanity checks when decoding the data again. This method will first
808    /// encode the specified tag, then the given value, then the number of
809    /// bytes taken up by tag and value. On decoding, we can then verify that
810    /// we get the expected tag and read the expected number of bytes.
811    fn encode_tagged<T: Encodable<Self>, V: Encodable<Self>>(&mut self, tag: T, value: &V) {
812        let start_pos = self.position();
813
814        tag.encode(self);
815        value.encode(self);
816
817        let end_pos = self.position();
818        ((end_pos - start_pos) as u64).encode(self);
819    }
820
821    pub fn encode_query_value<V: Encodable<Self>>(&mut self, index: DepNodeIndex, value: &V) {
822        let index = SerializedDepNodeIndex::from_curr_for_serialization(index);
823
824        self.query_values_index.push((index, AbsoluteBytePos::new(self.position())));
825        self.encode_tagged(index, value);
826    }
827
828    fn encode_side_effect(&mut self, index: DepNodeIndex, side_effect: &QuerySideEffect) {
829        let index = SerializedDepNodeIndex::from_curr_for_serialization(index);
830
831        self.side_effects_index.push((index, AbsoluteBytePos::new(self.position())));
832        self.encode_tagged(index, side_effect);
833    }
834
835    // copy&paste impl from rustc_metadata
836    fn encode_symbol_or_byte_symbol(
837        &mut self,
838        index: u32,
839        emit_str_or_byte_str: impl Fn(&mut Self),
840    ) {
841        // if symbol/byte symbol is predefined, emit tag and symbol index
842        if Symbol::is_predefined(index) {
843            self.encoder.emit_u8(SYMBOL_PREDEFINED);
844            self.encoder.emit_u32(index);
845        } else {
846            // otherwise write it as string or as offset to it
847            match self.symbol_index_table.entry(index) {
848                Entry::Vacant(o) => {
849                    self.encoder.emit_u8(SYMBOL_STR);
850                    let pos = self.encoder.position();
851                    o.insert(pos);
852                    emit_str_or_byte_str(self);
853                }
854                Entry::Occupied(o) => {
855                    let x = *o.get();
856                    self.emit_u8(SYMBOL_OFFSET);
857                    self.emit_usize(x);
858                }
859            }
860        }
861    }
862
863    #[inline]
864    fn finish(mut self) -> FileEncodeResult {
865        self.encoder.finish()
866    }
867}
868
869impl<'a, 'tcx> SpanEncoder for CacheEncoder<'a, 'tcx> {
870    fn encode_syntax_context(&mut self, syntax_context: SyntaxContext) {
871        rustc_span::hygiene::raw_encode_syntax_context(syntax_context, self.hygiene_context, self);
872    }
873
874    fn encode_expn_id(&mut self, expn_id: ExpnId) {
875        self.hygiene_context.schedule_expn_data_for_encoding(expn_id);
876        expn_id.expn_hash().encode(self);
877    }
878
879    fn encode_span(&mut self, span: Span) {
880        let span_data = span.data_untracked();
881        span_data.ctxt.encode(self);
882        span_data.parent.encode(self);
883
884        if span_data.is_dummy() {
885            return TAG_PARTIAL_SPAN.encode(self);
886        }
887
888        let parent =
889            span_data.parent.map(|parent| self.tcx.source_span_untracked(parent).data_untracked());
890        if let Some(parent) = parent
891            && parent.contains(span_data)
892        {
893            TAG_RELATIVE_SPAN.encode(self);
894            (span_data.lo.0.wrapping_sub(parent.lo.0)).encode(self);
895            (span_data.hi.0.wrapping_sub(parent.lo.0)).encode(self);
896            return;
897        }
898
899        let Some((file_lo, line_lo, col_lo)) =
900            self.caching_source_map_view.byte_pos_to_line_and_col(span_data.lo)
901        else {
902            return TAG_PARTIAL_SPAN.encode(self);
903        };
904
905        if let Some(parent) = parent
906            && file_lo.contains(parent.lo)
907        {
908            TAG_RELATIVE_SPAN.encode(self);
909            (span_data.lo.0.wrapping_sub(parent.lo.0)).encode(self);
910            (span_data.hi.0.wrapping_sub(parent.lo.0)).encode(self);
911            return;
912        }
913
914        let len = span_data.hi - span_data.lo;
915        let source_file_index = self.source_file_index(file_lo);
916
917        TAG_FULL_SPAN.encode(self);
918        source_file_index.encode(self);
919        line_lo.encode(self);
920        col_lo.encode(self);
921        len.encode(self);
922    }
923
924    fn encode_symbol(&mut self, sym: Symbol) {
925        self.encode_symbol_or_byte_symbol(sym.as_u32(), |this| this.emit_str(sym.as_str()));
926    }
927
928    fn encode_byte_symbol(&mut self, byte_sym: ByteSymbol) {
929        self.encode_symbol_or_byte_symbol(byte_sym.as_u32(), |this| {
930            this.emit_byte_str(byte_sym.as_byte_str())
931        });
932    }
933
934    fn encode_crate_num(&mut self, crate_num: CrateNum) {
935        self.tcx.stable_crate_id(crate_num).encode(self);
936    }
937
938    fn encode_def_id(&mut self, def_id: DefId) {
939        self.tcx.def_path_hash(def_id).encode(self);
940    }
941
942    fn encode_def_index(&mut self, _def_index: DefIndex) {
943        crate::util::bug::bug_fmt(format_args!("encoding `DefIndex` without context"));bug!("encoding `DefIndex` without context");
944    }
945}
946
947impl<'a, 'tcx> TyEncoder<'tcx> for CacheEncoder<'a, 'tcx> {
948    const CLEAR_CROSS_CRATE: bool = false;
949
950    #[inline]
951    fn position(&self) -> usize {
952        self.encoder.position()
953    }
954    #[inline]
955    fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
956        &mut self.type_shorthands
957    }
958    #[inline]
959    fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
960        &mut self.predicate_shorthands
961    }
962    #[inline]
963    fn encode_alloc_id(&mut self, alloc_id: &interpret::AllocId) {
964        let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
965
966        index.encode(self);
967    }
968}
969
970macro_rules! encoder_methods {
971    ($($name:ident($ty:ty);)*) => {
972        #[inline]
973        $(fn $name(&mut self, value: $ty) {
974            self.encoder.$name(value)
975        })*
976    }
977}
978
979impl<'a, 'tcx> Encoder for CacheEncoder<'a, 'tcx> {
980    #[inline]
fn emit_usize(&mut self, value: usize) { self.encoder.emit_usize(value) }
fn emit_u128(&mut self, value: u128) { self.encoder.emit_u128(value) }
fn emit_u64(&mut self, value: u64) { self.encoder.emit_u64(value) }
fn emit_u32(&mut self, value: u32) { self.encoder.emit_u32(value) }
fn emit_u16(&mut self, value: u16) { self.encoder.emit_u16(value) }
fn emit_u8(&mut self, value: u8) { self.encoder.emit_u8(value) }
fn emit_isize(&mut self, value: isize) { self.encoder.emit_isize(value) }
fn emit_i128(&mut self, value: i128) { self.encoder.emit_i128(value) }
fn emit_i64(&mut self, value: i64) { self.encoder.emit_i64(value) }
fn emit_i32(&mut self, value: i32) { self.encoder.emit_i32(value) }
fn emit_i16(&mut self, value: i16) { self.encoder.emit_i16(value) }
fn emit_raw_bytes(&mut self, value: &[u8]) {
    self.encoder.emit_raw_bytes(value)
}encoder_methods! {
981        emit_usize(usize);
982        emit_u128(u128);
983        emit_u64(u64);
984        emit_u32(u32);
985        emit_u16(u16);
986        emit_u8(u8);
987
988        emit_isize(isize);
989        emit_i128(i128);
990        emit_i64(i64);
991        emit_i32(i32);
992        emit_i16(i16);
993
994        emit_raw_bytes(&[u8]);
995    }
996}
997
998// This ensures that the `Encodable<opaque::FileEncoder>::encode` specialization for byte slices
999// is used when a `CacheEncoder` having an `opaque::FileEncoder` is passed to `Encodable::encode`.
1000// Unfortunately, we have to manually opt into specializations this way, given how `CacheEncoder`
1001// and the encoding traits currently work.
1002impl<'a, 'tcx> Encodable<CacheEncoder<'a, 'tcx>> for [u8] {
1003    fn encode(&self, e: &mut CacheEncoder<'a, 'tcx>) {
1004        self.encode(&mut e.encoder);
1005    }
1006}