Skip to main content

flux_metadata/
decoder.rs

1use std::{
2    fs,
3    io::{self, Read},
4    mem, panic,
5    path::Path,
6    sync::Arc,
7};
8
9use flux_common::bug;
10use flux_errors::FluxSession;
11use rustc_data_structures::{fx::FxHashMap, sync::HashMapExt};
12use rustc_hir::def_id::{DefId, LocalDefId};
13use rustc_middle::ty::{
14    self, TyCtxt,
15    codec::{TyDecoder, forward_all_decoder_methods_to},
16};
17use rustc_serialize::{
18    Decodable, Decoder,
19    opaque::{IntEncodedWithFixedSize, MemDecoder},
20};
21use rustc_session::StableCrateId;
22use rustc_span::{
23    BlobDecoder, BytePos, ByteSymbol, DUMMY_SP, SourceFile, Span, SpanDecoder, Symbol,
24    SyntaxContext,
25    def_id::{CrateNum, DefIndex},
26    hygiene::{HygieneDecodeContext, SyntaxContextKey},
27};
28
29use crate::{
30    AbsoluteBytePos, CrateMetadata, EncodedSourceFileId, ExpnKey, Footer, METADATA_HEADER,
31    SYMBOL_OFFSET, SYMBOL_PREDEFINED, SYMBOL_STR, SourceFileIndex, TAG_FULL_SPAN, TAG_PARTIAL_SPAN,
32};
33
34struct DecodeContext<'a, 'tcx> {
35    tcx: TyCtxt<'tcx>,
36    opaque: MemDecoder<'a>,
37    file_index_to_file: FxHashMap<SourceFileIndex, Arc<SourceFile>>,
38    file_index_to_stable_id: FxHashMap<SourceFileIndex, EncodedSourceFileId>,
39    syntax_contexts: &'a FxHashMap<u32, AbsoluteBytePos>,
40    expn_data: FxHashMap<ExpnKey, AbsoluteBytePos>,
41    hygiene_context: &'a HygieneDecodeContext,
42}
43
44impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
45    fn file_index_to_file(&mut self, index: SourceFileIndex) -> Arc<SourceFile> {
46        self.file_index_to_file
47            .entry(index)
48            .or_insert_with(|| {
49                let source_file_id = &self.file_index_to_stable_id[&index];
50                let source_file_cnum = self
51                    .tcx
52                    .stable_crate_id_to_crate_num(source_file_id.stable_crate_id);
53
54                self.tcx.import_source_files(source_file_cnum);
55                self.tcx
56                    .sess
57                    .source_map()
58                    .source_file_by_stable_id(source_file_id.stable_source_file_id)
59                    .expect("failed to lookup `SourceFile` in new context")
60            })
61            .clone()
62    }
63}
64
65pub(super) fn decode_crate_metadata<'tcx>(
66    tcx: TyCtxt<'tcx>,
67    sess: &FluxSession,
68    path: &Path,
69) -> Option<CrateMetadata<'tcx>> {
70    let mut file = match fs::File::open(path) {
71        Ok(file) => file,
72        Err(err) if let io::ErrorKind::NotFound = err.kind() => return None,
73        Err(err) => sess.emit_fatal(errors::DecodeFileError::new(path, err)),
74    };
75    let mut buf = vec![];
76    file.read_to_end(&mut buf)
77        .unwrap_or_else(|err| sess.emit_fatal(errors::DecodeFileError::new(path, err)));
78
79    // The last byte of the header is `METADATA_VERSION`. A header mismatch means the file was
80    // produced by a version of flux using a different (and thus incompatible) metadata format.
81    if !buf.starts_with(METADATA_HEADER) {
82        sess.emit_fatal(errors::IncompatibleMetadata::new(path));
83    }
84
85    let metadata = catch_decode(|| {
86        let footer = {
87            let mut decoder = MemDecoder::new(&buf, 0).unwrap();
88            let footer_pos = decoder
89                .with_position(decoder.len() - IntEncodedWithFixedSize::ENCODED_SIZE, |d| {
90                    IntEncodedWithFixedSize::decode(d).0 as usize
91                });
92            decoder.with_position(footer_pos, Footer::decode)
93        };
94
95        let mut decoder = DecodeContext {
96            tcx,
97            opaque: MemDecoder::new(&buf, METADATA_HEADER.len()).unwrap(),
98            file_index_to_stable_id: footer.file_index_to_stable_id,
99            file_index_to_file: Default::default(),
100            syntax_contexts: &footer.syntax_contexts,
101            expn_data: footer.expn_data,
102            hygiene_context: &Default::default(),
103        };
104
105        CrateMetadata::decode(&mut decoder)
106    });
107
108    match metadata {
109        Ok(metadata) => Some(metadata),
110        Err(()) => sess.emit_fatal(errors::IncompatibleMetadata::new(path)),
111    }
112}
113
114/// Runs `decode`, catching any panic raised by rustc's opaque decoder on malformed input.
115/// The panic hook is silenced so stale metadata surfaces as a clean diagnostic, not an ICE dump.
116fn catch_decode<R>(decode: impl FnOnce() -> R) -> Result<R, ()> {
117    let prev_hook = panic::take_hook();
118    panic::set_hook(Box::new(|_| {}));
119    let result = panic::catch_unwind(panic::AssertUnwindSafe(decode));
120    panic::set_hook(prev_hook);
121    result.map_err(|_| ())
122}
123
124impl Decoder for DecodeContext<'_, '_> {
125    forward_all_decoder_methods_to!(|self| self.opaque);
126}
127
128impl BlobDecoder for DecodeContext<'_, '_> {
129    fn decode_symbol(&mut self) -> Symbol {
130        let tag = self.read_u8();
131
132        match tag {
133            SYMBOL_STR => {
134                let s = self.read_str();
135                Symbol::intern(s)
136            }
137            SYMBOL_OFFSET => {
138                // read str offset
139                let pos = self.read_usize();
140
141                // move to str offset and read
142                self.opaque.with_position(pos, |d| {
143                    let s = d.read_str();
144                    Symbol::intern(s)
145                })
146            }
147            SYMBOL_PREDEFINED => {
148                let symbol_index = self.read_u32();
149                Symbol::new(symbol_index)
150            }
151            _ => unreachable!(),
152        }
153    }
154
155    fn decode_byte_symbol(&mut self) -> ByteSymbol {
156        ByteSymbol::intern(self.read_byte_str())
157    }
158
159    fn decode_def_index(&mut self) -> DefIndex {
160        DefIndex::from_u32(self.read_u32())
161    }
162
163    fn decode_local_def_id(&mut self) -> LocalDefId {
164        bug!("flux metadata never encodes a `LocalDefId`")
165    }
166}
167
168impl SpanDecoder for DecodeContext<'_, '_> {
169    fn decode_attr_id(&mut self) -> rustc_ast::AttrId {
170        self.tcx.sess.psess.attr_id_generator.mk_attr_id()
171    }
172
173    fn decode_crate_num(&mut self) -> CrateNum {
174        let stable_id = StableCrateId::decode(self);
175        self.tcx.stable_crate_id_to_crate_num(stable_id)
176    }
177
178    fn decode_def_id(&mut self) -> DefId {
179        DefId { krate: Decodable::decode(self), index: Decodable::decode(self) }
180    }
181
182    fn decode_syntax_context(&mut self) -> SyntaxContext {
183        let syntax_contexts = self.syntax_contexts;
184        rustc_span::hygiene::decode_syntax_context(self, self.hygiene_context, |this, id| {
185            // This closure is invoked if we haven't already decoded the data for the `SyntaxContext` we are deserializing.
186            // We look up the position of the associated `SyntaxData` and decode it.
187            let pos = syntax_contexts.get(&id.as_u32()).unwrap();
188            this.with_position(pos.to_usize(), SyntaxContextKey::decode)
189        })
190    }
191
192    fn decode_expn_id(&mut self) -> rustc_span::ExpnId {
193        let stable_id = StableCrateId::decode(self);
194        let cnum = self.tcx.stable_crate_id_to_crate_num(stable_id);
195        let index = u32::decode(self);
196
197        rustc_span::hygiene::decode_expn_id(cnum, index, |_| {
198            let pos = self.expn_data.get(&ExpnKey(stable_id, index)).unwrap();
199            self.with_position(pos.to_usize(), |decoder| {
200                let data = rustc_span::ExpnData::decode(decoder);
201                let hash = rustc_span::ExpnHash::decode(decoder);
202                (data, hash)
203            })
204        })
205    }
206
207    fn decode_span(&mut self) -> rustc_span::Span {
208        let ctxt = SyntaxContext::decode(self);
209        let tag: u8 = Decodable::decode(self);
210
211        if tag == TAG_PARTIAL_SPAN {
212            return DUMMY_SP.with_ctxt(ctxt);
213        }
214
215        debug_assert!(tag == TAG_FULL_SPAN);
216
217        let source_file_index = SourceFileIndex::decode(self);
218        let lo = BytePos::decode(self);
219        let len = BytePos::decode(self);
220        let file = self.file_index_to_file(source_file_index);
221        let lo = file.start_pos + lo;
222        let hi = lo + len;
223
224        Span::new(lo, hi, ctxt, None)
225    }
226}
227
228impl<'tcx> rustc_type_ir::InternerDecoder for DecodeContext<'_, 'tcx> {
229    type Interner = TyCtxt<'tcx>;
230
231    fn interner(&self) -> TyCtxt<'tcx> {
232        self.tcx
233    }
234}
235
236impl<'tcx> TyDecoder<'tcx> for DecodeContext<'_, 'tcx> {
237    const CLEAR_CROSS_CRATE: bool = true;
238
239    fn cached_ty_for_shorthand<F>(&mut self, shorthand: usize, or_insert_with: F) -> ty::Ty<'tcx>
240    where
241        F: FnOnce(&mut Self) -> ty::Ty<'tcx>,
242    {
243        let tcx = self.tcx;
244
245        let cache_key = ty::CReaderCacheKey { cnum: None, pos: shorthand };
246
247        if let Some(&ty) = tcx.caches.ty_rcache.borrow().get(&cache_key) {
248            return ty;
249        }
250
251        let ty = or_insert_with(self);
252        // This may overwrite the entry, but it should overwrite with the same value.
253        tcx.caches.ty_rcache.borrow_mut().insert_same(cache_key, ty);
254        ty
255    }
256
257    fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
258    where
259        F: FnOnce(&mut Self) -> R,
260    {
261        let new_opaque = self.opaque.split_at(pos);
262        let old_opaque = mem::replace(&mut self.opaque, new_opaque);
263        let r = f(self);
264        self.opaque = old_opaque;
265        r
266    }
267
268    fn decode_alloc_id(&mut self) -> rustc_middle::mir::interpret::AllocId {
269        bug!("Encoding `interpret::AllocId` is not supported")
270    }
271}
272
273mod errors {
274    use std::{io, path::Path};
275
276    use flux_errors::E0999;
277    use flux_macros::Diagnostic;
278
279    #[derive(Diagnostic)]
280    #[diag("error when decoding flux metadata file {$path}: {$err}", code = E0999)]
281    pub(super) struct DecodeFileError<'a> {
282        path: &'a Path,
283        err: io::Error,
284    }
285
286    impl<'a> DecodeFileError<'a> {
287        pub(super) fn new(path: &'a Path, err: io::Error) -> Self {
288            Self { path, err }
289        }
290    }
291
292    #[derive(Diagnostic)]
293    #[diag("failed to decode flux metadata file `{$path}`; this is likely because it was produced by an incompatible version of flux. Run `cargo clean` to remove stale metadata and try again", code = E0999)]
294    pub(super) struct IncompatibleMetadata<'a> {
295        path: &'a Path,
296    }
297
298    impl<'a> IncompatibleMetadata<'a> {
299        pub(super) fn new(path: &'a Path) -> Self {
300            Self { path }
301        }
302    }
303}