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