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, forward_all_decoder_methods_to};
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) -> Self {
        let _: ::core::clone::AssertParamIsClone<u32>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for SourceFileIndex { }
#[automatically_derived]
impl ::core::cmp::PartialEq for SourceFileIndex {
    #[inline]
    fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for SourceFileIndex {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<u32>;
    }
}Eq, #[automatically_derived]
impl ::core::hash::Hash for SourceFileIndex {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash, #[automatically_derived]
impl ::core::fmt::Debug for SourceFileIndex {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f,
            "SourceFileIndex", &&self.0)
    }
}Debug, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for SourceFileIndex {
            fn encode(&self, __encoder: &mut __E) {
                let SourceFileIndex(ref __binding_0) = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for SourceFileIndex {
            fn decode(__decoder: &mut __D) -> Self {
                SourceFileIndex(::rustc_serialize::Decodable::decode(__decoder))
            }
        }
    };Decodable)]
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) -> Self {
        let _: ::core::clone::AssertParamIsClone<u64>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for AbsoluteBytePos {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f,
            "AbsoluteBytePos", &&self.0)
    }
}Debug, #[automatically_derived]
impl ::core::hash::Hash for AbsoluteBytePos {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash, #[automatically_derived]
impl ::core::cmp::Eq for AbsoluteBytePos {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<u64>;
    }
}Eq, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for AbsoluteBytePos { }
#[automatically_derived]
impl ::core::cmp::PartialEq for AbsoluteBytePos {
    #[inline]
    fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}PartialEq, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for AbsoluteBytePos {
            fn encode(&self, __encoder: &mut __E) {
                let AbsoluteBytePos(ref __binding_0) = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for AbsoluteBytePos {
            fn decode(__decoder: &mut __D) -> Self {
                AbsoluteBytePos(::rustc_serialize::Decodable::decode(__decoder))
            }
        }
    };Decodable)]
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) -> Self {
        Self {
            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
532impl<'a, 'tcx> Decoder for CacheDecoder<'a, 'tcx> {
533    #[inline]
fn read_usize(&mut self) -> usize { self.opaque.read_usize() }
#[inline]
fn read_u128(&mut self) -> u128 { self.opaque.read_u128() }
#[inline]
fn read_u64(&mut self) -> u64 { self.opaque.read_u64() }
#[inline]
fn read_u32(&mut self) -> u32 { self.opaque.read_u32() }
#[inline]
fn read_u16(&mut self) -> u16 { self.opaque.read_u16() }
#[inline]
fn read_u8(&mut self) -> u8 { self.opaque.read_u8() }
#[inline]
fn read_isize(&mut self) -> isize { self.opaque.read_isize() }
#[inline]
fn read_i128(&mut self) -> i128 { self.opaque.read_i128() }
#[inline]
fn read_i64(&mut self) -> i64 { self.opaque.read_i64() }
#[inline]
fn read_i32(&mut self) -> i32 { self.opaque.read_i32() }
#[inline]
fn read_i16(&mut self) -> i16 { self.opaque.read_i16() }
#[inline]
fn read_raw_bytes(&mut self, len: usize) -> &[u8] {
    self.opaque.read_raw_bytes(len)
}
#[inline]
fn peek_byte(&self) -> u8 { self.opaque.peek_byte() }
#[inline]
fn position(&self) -> usize { self.opaque.position() }forward_all_decoder_methods_to!(|self| self.opaque);
534}
535
536// This ensures that the `Decodable<opaque::Decoder>::decode` specialization for `Vec<u8>` is used
537// when a `CacheDecoder` is passed to `Decodable::decode`. Unfortunately, we have to manually opt
538// into specializations this way, given how `CacheDecoder` and the decoding traits currently work.
539impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for Vec<u8> {
540    fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
541        Decodable::decode(&mut d.opaque)
542    }
543}
544
545impl<'a, 'tcx> SpanDecoder for CacheDecoder<'a, 'tcx> {
546    fn decode_syntax_context(&mut self) -> SyntaxContext {
547        let syntax_contexts = self.syntax_contexts;
548        rustc_span::hygiene::decode_syntax_context(self, self.hygiene_context, |this, id| {
549            // This closure is invoked if we haven't already decoded the data for the `SyntaxContext` we are deserializing.
550            // We look up the position of the associated `SyntaxData` and decode it.
551            let pos = syntax_contexts.get(&id).unwrap();
552            this.with_position(pos.to_usize(), |decoder| {
553                let data: SyntaxContextKey = decode_tagged(decoder, TAG_SYNTAX_CONTEXT);
554                data
555            })
556        })
557    }
558
559    fn decode_expn_id(&mut self) -> ExpnId {
560        let hash = ExpnHash::decode(self);
561        if hash.is_root() {
562            return ExpnId::root();
563        }
564
565        if let Some(expn_id) = ExpnId::from_hash(hash) {
566            return expn_id;
567        }
568
569        let krate = self.tcx.stable_crate_id_to_crate_num(hash.stable_crate_id());
570
571        let expn_id = if krate == LOCAL_CRATE {
572            // We look up the position of the associated `ExpnData` and decode it.
573            let pos = self
574                .expn_data
575                .get(&hash)
576                .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));
577
578            let data: ExpnData =
579                self.with_position(pos.to_usize(), |decoder| decode_tagged(decoder, TAG_EXPN_DATA));
580            let expn_id = rustc_span::hygiene::register_local_expn_id(data, hash);
581
582            #[cfg(debug_assertions)]
583            {
584                use rustc_data_structures::stable_hash::{StableHash, StableHasher};
585                let local_hash = self.tcx.with_stable_hashing_context(|mut hcx| {
586                    let mut hasher = StableHasher::new();
587                    expn_id.expn_data().stable_hash(&mut hcx, &mut hasher);
588                    hasher.finish()
589                });
590                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);
591            }
592
593            expn_id
594        } else {
595            let index_guess = self.foreign_expn_data[&hash];
596            self.tcx.expn_hash_to_expn_id(krate, index_guess, hash)
597        };
598
599        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);
600        expn_id
601    }
602
603    fn decode_span(&mut self) -> Span {
604        let ctxt = SyntaxContext::decode(self);
605        let parent = Option::<LocalDefId>::decode(self);
606        let tag: u8 = Decodable::decode(self);
607
608        let (lo, hi) = match tag {
609            TAG_PARTIAL_SPAN => (BytePos(0), BytePos(0)),
610            TAG_RELATIVE_SPAN => {
611                let dlo = u32::decode(self);
612                let dto = u32::decode(self);
613
614                let enclosing = self.tcx.source_span_untracked(parent.unwrap()).data_untracked();
615                (
616                    BytePos(enclosing.lo.0.wrapping_add(dlo)),
617                    BytePos(enclosing.lo.0.wrapping_add(dto)),
618                )
619            }
620            TAG_FULL_SPAN => {
621                let file_lo_index = SourceFileIndex::decode(self);
622                let line_lo = usize::decode(self);
623                let col_lo = RelativeBytePos::decode(self);
624                let len = BytePos::decode(self);
625
626                let file_lo = self.file_index_to_file(file_lo_index);
627                let lo = file_lo.lines()[line_lo - 1] + col_lo;
628                let lo = file_lo.absolute_position(lo);
629                let hi = lo + len;
630                (lo, hi)
631            }
632            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
633        };
634
635        Span::new(lo, hi, ctxt, parent)
636    }
637
638    fn decode_crate_num(&mut self) -> CrateNum {
639        let stable_id = StableCrateId::decode(self);
640        let cnum = self.tcx.stable_crate_id_to_crate_num(stable_id);
641        cnum
642    }
643
644    // Both the `CrateNum` and the `DefIndex` of a `DefId` can change in between two
645    // compilation sessions. We use the `DefPathHash`, which is stable across
646    // sessions, to map the old `DefId` to the new one.
647    fn decode_def_id(&mut self) -> DefId {
648        // Load the `DefPathHash` which is was we encoded the `DefId` as.
649        let def_path_hash = DefPathHash::decode(self);
650
651        // Using the `DefPathHash`, we can lookup the new `DefId`.
652        // Subtle: We only encode a `DefId` as part of a query result.
653        // If we get to this point, then all of the query inputs were green,
654        // which means that the definition with this hash is guaranteed to
655        // still exist in the current compilation session.
656        match self.tcx.def_path_hash_to_def_id(def_path_hash) {
657            Some(r) => r,
658            None => {
    ::core::panicking::panic_fmt(format_args!("Failed to convert DefPathHash {0:?}",
            def_path_hash));
}panic!("Failed to convert DefPathHash {def_path_hash:?}"),
659        }
660    }
661
662    fn decode_attr_id(&mut self) -> rustc_span::AttrId {
663        {
    ::core::panicking::panic_fmt(format_args!("cannot decode `AttrId` with `CacheDecoder`"));
};panic!("cannot decode `AttrId` with `CacheDecoder`");
664    }
665}
666
667impl<'a, 'tcx> BlobDecoder for CacheDecoder<'a, 'tcx> {
668    fn decode_symbol(&mut self) -> Symbol {
669        self.decode_symbol_or_byte_symbol(
670            Symbol::new,
671            |this| Symbol::intern(this.read_str()),
672            |opaque| Symbol::intern(opaque.read_str()),
673        )
674    }
675
676    fn decode_byte_symbol(&mut self) -> ByteSymbol {
677        self.decode_symbol_or_byte_symbol(
678            ByteSymbol::new,
679            |this| ByteSymbol::intern(this.read_byte_str()),
680            |opaque| ByteSymbol::intern(opaque.read_byte_str()),
681        )
682    }
683
684    // This impl makes sure that we get a runtime error when we try decode a
685    // `DefIndex` that is not contained in a `DefId`. Such a case would be problematic
686    // because we would not know how to transform the `DefIndex` to the current
687    // context.
688    fn decode_def_index(&mut self) -> DefIndex {
689        {
    ::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`")
690    }
691}
692
693/// Implements [`Decodable`] for `&'tcx T`, where [`T: RefDecodable`](RefDecodable).
694///
695/// Due to orphan-rule restrictions, these foreign impls cannot use a blanket
696/// [`D: TyDecoder`](TyDecoder), and must instead specify a specific decoder.
697///
698/// For impls on types defined in `rustc_middle`, see
699/// `impl_decodable_via_ref_decodable_for_local_type!` instead.
700macro_rules! impl_decodable_via_ref_decodable_for_foreign_types {
701    (
702        $(
703            &'tcx $T:ty,
704        )*
705    ) => {
706        $(
707            impl<'tcx> Decodable<CacheDecoder<'_, 'tcx>> for &'tcx $T {
708                fn decode(decoder: &mut CacheDecoder<'_, 'tcx>) -> Self {
709                    RefDecodable::decode(decoder)
710                }
711            }
712        )*
713    }
714}
715
716impl<'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! {
717    // tidy-alphabetical-start
718    &'tcx IndexVec<mir::Promoted, mir::Body<'tcx>>,
719    &'tcx UnordMap<DefId, ty::EarlyBinder<'tcx, Ty<'tcx>>>,
720    &'tcx UnordSet<LocalDefId>,
721    &'tcx [(
722        rustc_middle::middle::exported_symbols::ExportedSymbol<'tcx>,
723        rustc_middle::middle::exported_symbols::SymbolExportInfo,
724    )],
725    &'tcx [(ty::Clause<'tcx>, Span)],
726    &'tcx [DefId],
727    &'tcx [Spanned<MonoItem<'tcx>>],
728    &'tcx [ty::Variance],
729    &'tcx rustc_ast::tokenstream::TokenStream,
730    // tidy-alphabetical-end
731}
732
733//- ENCODING -------------------------------------------------------------------
734
735/// An encoder that can write to the incremental compilation cache.
736pub struct CacheEncoder<'tcx> {
737    tcx: TyCtxt<'tcx>,
738    encoder: FileEncoder<'static>,
739    type_shorthands: FxHashMap<Ty<'tcx>, usize>,
740    predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
741    interpret_allocs: FxIndexSet<interpret::AllocId>,
742    caching_source_map_view: CachingSourceMapView<'tcx>,
743    file_to_file_index: FxHashMap<*const SourceFile, SourceFileIndex>,
744    hygiene_context: Rc<RefCell<HygieneEncodeContext>>,
745    // Used for both `Symbol`s and `ByteSymbol`s.
746    symbol_index_table: FxHashMap<u32, usize>,
747
748    query_values_index: Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>,
749    side_effects_index: Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>,
750}
751
752impl<'tcx> fmt::Debug for CacheEncoder<'tcx> {
753    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
754        // Add more details here if/when necessary.
755        f.write_str("CacheEncoder")
756    }
757}
758
759impl<'tcx> CacheEncoder<'tcx> {
760    #[inline]
761    fn source_file_index(&mut self, source_file: Arc<SourceFile>) -> SourceFileIndex {
762        self.file_to_file_index[&(&raw const *source_file)]
763    }
764
765    /// Encode something with additional information that allows to do some
766    /// sanity checks when decoding the data again. This method will first
767    /// encode the specified tag, then the given value, then the number of
768    /// bytes taken up by tag and value. On decoding, we can then verify that
769    /// we get the expected tag and read the expected number of bytes.
770    fn encode_tagged<T: Encodable<Self>, V: Encodable<Self>>(&mut self, tag: T, value: &V) {
771        let start_pos = self.position();
772
773        tag.encode(self);
774        value.encode(self);
775
776        let end_pos = self.position();
777        ((end_pos - start_pos) as u64).encode(self);
778    }
779
780    pub fn encode_query_value<V: Encodable<Self>>(&mut self, index: DepNodeIndex, value: &V) {
781        let index = SerializedDepNodeIndex::from_curr_for_serialization(index);
782
783        self.query_values_index.push((index, AbsoluteBytePos::new(self.position())));
784        self.encode_tagged(index, value);
785    }
786
787    fn encode_side_effect(&mut self, index: DepNodeIndex, side_effect: &QuerySideEffect) {
788        let index = SerializedDepNodeIndex::from_curr_for_serialization(index);
789
790        self.side_effects_index.push((index, AbsoluteBytePos::new(self.position())));
791        self.encode_tagged(index, side_effect);
792    }
793
794    // copy&paste impl from rustc_metadata
795    fn encode_symbol_or_byte_symbol(
796        &mut self,
797        index: u32,
798        emit_str_or_byte_str: impl Fn(&mut Self),
799    ) {
800        // if symbol/byte symbol is predefined, emit tag and symbol index
801        if Symbol::is_predefined(index) {
802            self.encoder.emit_u8(SYMBOL_PREDEFINED);
803            self.encoder.emit_u32(index);
804        } else {
805            // otherwise write it as string or as offset to it
806            match self.symbol_index_table.entry(index) {
807                Entry::Vacant(o) => {
808                    self.encoder.emit_u8(SYMBOL_STR);
809                    let pos = self.encoder.position();
810                    o.insert(pos);
811                    emit_str_or_byte_str(self);
812                }
813                Entry::Occupied(o) => {
814                    let x = *o.get();
815                    self.emit_u8(SYMBOL_OFFSET);
816                    self.emit_usize(x);
817                }
818            }
819        }
820    }
821
822    #[inline]
823    fn finish(mut self) -> FileEncodeResult {
824        self.encoder.finish()
825    }
826}
827
828impl<'tcx> SpanEncoder for CacheEncoder<'tcx> {
829    fn encode_syntax_context(&mut self, syntax_context: SyntaxContext) {
830        let idx = self.hygiene_context.borrow_mut().get_syntax_ctxt_encoding_index(syntax_context);
831        idx.encode(self);
832    }
833
834    fn encode_expn_id(&mut self, expn_id: ExpnId) {
835        self.hygiene_context.borrow_mut().schedule_expn_data_for_encoding(expn_id);
836        expn_id.expn_hash().encode(self);
837    }
838
839    fn encode_span(&mut self, span: Span) {
840        let span_data = span.data_untracked();
841        span_data.ctxt.encode(self);
842        span_data.parent.encode(self);
843
844        if span_data.is_dummy() {
845            return TAG_PARTIAL_SPAN.encode(self);
846        }
847
848        let parent =
849            span_data.parent.map(|parent| self.tcx.source_span_untracked(parent).data_untracked());
850        if let Some(parent) = parent
851            && parent.contains(span_data)
852        {
853            TAG_RELATIVE_SPAN.encode(self);
854            (span_data.lo.0.wrapping_sub(parent.lo.0)).encode(self);
855            (span_data.hi.0.wrapping_sub(parent.lo.0)).encode(self);
856            return;
857        }
858
859        let Some((file_lo, line_lo, col_lo)) =
860            self.caching_source_map_view.byte_pos_to_line_and_col(span_data.lo)
861        else {
862            return TAG_PARTIAL_SPAN.encode(self);
863        };
864
865        if let Some(parent) = parent
866            && file_lo.contains(parent.lo)
867        {
868            TAG_RELATIVE_SPAN.encode(self);
869            (span_data.lo.0.wrapping_sub(parent.lo.0)).encode(self);
870            (span_data.hi.0.wrapping_sub(parent.lo.0)).encode(self);
871            return;
872        }
873
874        let len = span_data.hi - span_data.lo;
875        let source_file_index = self.source_file_index(file_lo);
876
877        TAG_FULL_SPAN.encode(self);
878        source_file_index.encode(self);
879        line_lo.encode(self);
880        col_lo.encode(self);
881        len.encode(self);
882    }
883
884    fn encode_symbol(&mut self, sym: Symbol) {
885        self.encode_symbol_or_byte_symbol(sym.as_u32(), |this| this.emit_str(sym.as_str()));
886    }
887
888    fn encode_byte_symbol(&mut self, byte_sym: ByteSymbol) {
889        self.encode_symbol_or_byte_symbol(byte_sym.as_u32(), |this| {
890            this.emit_byte_str(byte_sym.as_byte_str())
891        });
892    }
893
894    fn encode_crate_num(&mut self, crate_num: CrateNum) {
895        self.tcx.stable_crate_id(crate_num).encode(self);
896    }
897
898    fn encode_def_id(&mut self, def_id: DefId) {
899        self.tcx.def_path_hash(def_id).encode(self);
900    }
901
902    fn encode_def_index(&mut self, _def_index: DefIndex) {
903        ::rustc_span::macros::bug_impl(None,
    format_args!("encoding `DefIndex` without context"), Location::caller());bug!("encoding `DefIndex` without context");
904    }
905}
906
907impl<'tcx> TyEncoder<'tcx> for CacheEncoder<'tcx> {
908    const CLEAR_CROSS_CRATE: bool = false;
909
910    #[inline]
911    fn position(&self) -> usize {
912        self.encoder.position()
913    }
914    #[inline]
915    fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
916        &mut self.type_shorthands
917    }
918    #[inline]
919    fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
920        &mut self.predicate_shorthands
921    }
922    #[inline]
923    fn encode_alloc_id(&mut self, alloc_id: &interpret::AllocId) {
924        let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
925
926        index.encode(self);
927    }
928}
929
930macro_rules! encoder_methods {
931    ($($name:ident($ty:ty);)*) => {
932        #[inline]
933        $(fn $name(&mut self, value: $ty) {
934            self.encoder.$name(value)
935        })*
936    }
937}
938
939impl<'tcx> Encoder for CacheEncoder<'tcx> {
940    #[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! {
941        emit_usize(usize);
942        emit_u128(u128);
943        emit_u64(u64);
944        emit_u32(u32);
945        emit_u16(u16);
946        emit_u8(u8);
947
948        emit_isize(isize);
949        emit_i128(i128);
950        emit_i64(i64);
951        emit_i32(i32);
952        emit_i16(i16);
953
954        emit_raw_bytes(&[u8]);
955    }
956}
957
958// This ensures that the `Encodable<opaque::FileEncoder>::encode` specialization for byte slices
959// is used when a `CacheEncoder` having an `opaque::FileEncoder` is passed to `Encodable::encode`.
960// Unfortunately, we have to manually opt into specializations this way, given how `CacheEncoder`
961// and the encoding traits currently work.
962impl<'tcx> Encodable<CacheEncoder<'tcx>> for [u8] {
963    fn encode(&self, e: &mut CacheEncoder<'tcx>) {
964        self.encode(&mut e.encoder);
965    }
966}