Skip to main content

rustc_middle/query/
on_disk_cache.rs

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