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