Skip to main content

rustc_middle/query/
on_disk_cache.rs

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