1use std::{cell::RefCell, collections::hash_map::Entry, sync::Arc};
2
3use flux_common::bug;
4use flux_middle::global_env::GlobalEnv;
5use rustc_data_structures::fx::FxHashMap;
6use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
7use rustc_middle::ty::{self, TyCtxt, codec::TyEncoder};
8use rustc_serialize::{Encodable, Encoder, opaque, opaque::IntEncodedWithFixedSize};
9use rustc_span::{
10 ByteSymbol, ExpnId, SourceFile, Span, SpanEncoder, Symbol, SyntaxContext,
11 def_id::{CrateNum, DefIndex},
12 hygiene::{ExpnIndex, HygieneEncodeContext},
13};
14use rustc_structures::CrateType;
15
16use crate::{
17 AbsoluteBytePos, CrateMetadata, EncodedSourceFileId, ExpnKey, Footer, METADATA_HEADER,
18 SYMBOL_OFFSET, SYMBOL_PREDEFINED, SYMBOL_STR, SourceFileIndex, TAG_FULL_SPAN, TAG_PARTIAL_SPAN,
19};
20
21struct EncodeContext<'a, 'tcx> {
22 tcx: TyCtxt<'tcx>,
23 opaque: opaque::FileEncoder<'a>,
24 type_shorthands: FxHashMap<ty::Ty<'tcx>, usize>,
25 predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
26 file_to_file_index: FxHashMap<*const SourceFile, SourceFileIndex>,
27 is_proc_macro: bool,
28 hygiene_ctxt: &'a RefCell<HygieneEncodeContext>,
29 symbol_index_table: FxHashMap<u32, usize>,
30}
31
32impl EncodeContext<'_, '_> {
33 fn source_file_index(&mut self, source_file: Arc<SourceFile>) -> SourceFileIndex {
34 self.file_to_file_index[&(&*source_file as *const SourceFile)]
35 }
36
37 fn encode_symbol_or_byte_symbol(
38 &mut self,
39 index: u32,
40 emit_str_or_byte_str: impl Fn(&mut Self),
41 ) {
42 if Symbol::is_predefined(index) {
45 self.opaque.emit_u8(SYMBOL_PREDEFINED);
46 self.opaque.emit_u32(index);
47 } else {
48 match self.symbol_index_table.entry(index) {
50 Entry::Vacant(o) => {
51 self.opaque.emit_u8(SYMBOL_STR);
52 let pos = self.opaque.position();
53 o.insert(pos);
54 emit_str_or_byte_str(self);
55 }
56 Entry::Occupied(o) => {
57 let x = *o.get();
58 self.emit_u8(SYMBOL_OFFSET);
59 self.emit_usize(x);
60 }
61 }
62 }
63 }
64}
65
66fn file_indices(
67 tcx: TyCtxt,
68) -> (FxHashMap<*const SourceFile, SourceFileIndex>, FxHashMap<SourceFileIndex, EncodedSourceFileId>)
69{
70 let files = tcx.sess.source_map().files();
71 let mut file_to_file_index =
72 FxHashMap::with_capacity_and_hasher(files.len(), Default::default());
73 let mut file_index_to_stable_id =
74 FxHashMap::with_capacity_and_hasher(files.len(), Default::default());
75 use rustc_span::def_id::LOCAL_CRATE;
76 let local_crate_stable_id = tcx.stable_crate_id(LOCAL_CRATE);
77
78 for (index, file) in files.iter().enumerate() {
83 let index = SourceFileIndex(index as u32);
84 let file_ptr: *const SourceFile = &**file as *const _;
85 file_to_file_index.insert(file_ptr, index);
86
87 let mut adapted_source_file = (**file).clone();
88 if adapted_source_file.cnum == LOCAL_CRATE {
89 use rustc_span::FileName;
90 match file.name {
91 FileName::Real(ref original_file_name) => {
92 let mut adapted_file_name = original_file_name.clone();
93 adapted_file_name.update_for_crate_metadata();
94
95 adapted_source_file.name = FileName::Real(adapted_file_name);
96 }
97 _ => {
98 }
100 };
101 use rustc_span::StableSourceFileId;
102 adapted_source_file.stable_id = StableSourceFileId::from_filename_for_export(
103 &adapted_source_file.name,
104 local_crate_stable_id,
105 );
106 }
107
108 let source_file_id = EncodedSourceFileId::new(tcx, &adapted_source_file);
109 file_index_to_stable_id.insert(index, source_file_id);
110 }
111
112 (file_to_file_index, file_index_to_stable_id)
113}
114
115pub fn encode_metadata(genv: GlobalEnv, path: &std::path::Path) {
116 let (file_to_file_index, file_index_to_stable_id) = file_indices(genv.tcx());
117
118 let mut encoder = opaque::FileEncoder::new(path).unwrap_or_else(|err| {
119 genv.tcx()
120 .sess
121 .dcx()
122 .fatal(format!("failed to create file encoder: {err}"))
123 });
124
125 encoder.emit_raw_bytes(METADATA_HEADER);
126
127 let crate_root = CrateMetadata::new(genv);
128
129 let hygiene_ctxt = RefCell::new(HygieneEncodeContext::default());
130 let tcx = genv.tcx();
131 let mut ecx = EncodeContext {
132 tcx,
133 opaque: encoder,
134 type_shorthands: Default::default(),
135 predicate_shorthands: Default::default(),
136 file_to_file_index,
137 is_proc_macro: genv.tcx().crate_types().contains(&CrateType::ProcMacro),
138 hygiene_ctxt: &hygiene_ctxt,
139 symbol_index_table: Default::default(),
140 };
141
142 crate_root.encode(&mut ecx);
143
144 let mut syntax_contexts = FxHashMap::default();
146 let mut expn_data = FxHashMap::default();
147
148 HygieneEncodeContext::encode(
150 &hygiene_ctxt,
151 &mut ecx,
152 |encoder, ctxt, ctxt_data| {
153 let pos = AbsoluteBytePos::new(encoder.position());
154 ctxt_data.encode(encoder);
155 syntax_contexts.insert(ctxt.as_u32(), pos);
156 },
157 |encoder, expn_id, data, hash| {
158 let pos = AbsoluteBytePos::new(encoder.position());
159 data.expect("local expn").encode(encoder);
160 hash.encode(encoder);
161 expn_data.insert(
162 ExpnKey(tcx.stable_crate_id(expn_id.krate), expn_id.local_id.as_u32()),
163 pos,
164 );
165 },
166 );
167
168 let footer_pos = ecx.position() as u64;
170 let footer = Footer { file_index_to_stable_id, syntax_contexts, expn_data };
171 footer.encode(&mut ecx);
172
173 IntEncodedWithFixedSize(footer_pos).encode(&mut ecx.opaque);
176
177 ecx.opaque.finish().unwrap();
182}
183
184impl SpanEncoder for EncodeContext<'_, '_> {
185 fn encode_crate_num(&mut self, crate_num: CrateNum) {
186 if crate_num != LOCAL_CRATE && self.is_proc_macro {
187 bug!("Attempted to encode non-local CrateNum {crate_num:?} for proc-macro crate");
188 }
189 self.tcx.stable_crate_id(crate_num).encode(self);
190 }
191
192 fn encode_def_index(&mut self, def_index: DefIndex) {
193 self.emit_u32(def_index.as_u32());
194 }
195
196 fn encode_def_id(&mut self, def_id: DefId) {
197 def_id.krate.encode(self);
198 def_id.index.encode(self);
199 }
200
201 fn encode_local_def_id(&mut self, def_id: LocalDefId) {
204 bug!("attempted to encode `LocalDefId` {def_id:?} in flux metadata");
205 }
206
207 fn encode_syntax_context(&mut self, syntax_context: SyntaxContext) {
208 self.hygiene_ctxt
209 .borrow_mut()
210 .enqueue_syntax_context_for_encoding(syntax_context);
211 self.emit_u32(syntax_context.as_u32());
212 }
213
214 fn encode_expn_id(&mut self, expn_id: ExpnId) {
215 if expn_id.krate == LOCAL_CRATE {
216 self.hygiene_ctxt
221 .borrow_mut()
222 .schedule_expn_data_for_encoding(expn_id);
223 }
224 expn_id.krate.encode(self);
225 expn_id.local_id.encode(self);
226 }
227
228 fn encode_span(&mut self, span: Span) {
230 let span = span.data();
231 span.ctxt.encode(self);
232
233 if span.is_dummy() {
234 return TAG_PARTIAL_SPAN.encode(self);
235 }
236
237 let source_file = self.tcx.sess.source_map().lookup_source_file(span.lo);
238 if !source_file.contains(span.hi) {
239 return TAG_PARTIAL_SPAN.encode(self);
242 }
243
244 let lo = span.lo - source_file.start_pos;
245 let len = span.hi - span.lo;
246 let source_file_index = self.source_file_index(source_file);
247
248 TAG_FULL_SPAN.encode(self);
249 source_file_index.encode(self);
250 lo.encode(self);
251 len.encode(self);
252 }
253
254 fn encode_symbol(&mut self, sym: Symbol) {
255 self.encode_symbol_or_byte_symbol(sym.as_u32(), |this| this.emit_str(sym.as_str()));
256 }
257
258 fn encode_byte_symbol(&mut self, byte_sym: ByteSymbol) {
259 self.encode_symbol_or_byte_symbol(byte_sym.as_u32(), |this| {
260 this.emit_byte_str(byte_sym.as_byte_str());
261 });
262 }
263}
264
265impl<'tcx> TyEncoder<'tcx> for EncodeContext<'_, 'tcx> {
266 const CLEAR_CROSS_CRATE: bool = true;
267
268 fn position(&self) -> usize {
269 self.opaque.position()
270 }
271
272 fn type_shorthands(&mut self) -> &mut FxHashMap<ty::Ty<'tcx>, usize> {
273 &mut self.type_shorthands
274 }
275
276 fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
277 &mut self.predicate_shorthands
278 }
279
280 fn encode_alloc_id(&mut self, _alloc_id: &rustc_middle::mir::interpret::AllocId) {
281 bug!("Encoding `interpret::AllocId` is not supported");
282 }
285}
286
287impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnIndex {
288 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
289 s.emit_u32(self.as_u32());
290 }
291}
292
293macro_rules! encoder_methods {
294 ($($name:ident($ty:ty);)*) => {
295 $(fn $name(&mut self, value: $ty) {
296 self.opaque.$name(value)
297 })*
298 }
299}
300
301impl Encoder for EncodeContext<'_, '_> {
302 encoder_methods! {
303 emit_usize(usize);
304 emit_u128(u128);
305 emit_u64(u64);
306 emit_u32(u32);
307 emit_u16(u16);
308 emit_u8(u8);
309
310 emit_isize(isize);
311 emit_i128(i128);
312 emit_i64(i64);
313 emit_i32(i32);
314 emit_i16(i16);
315 emit_i8(i8);
316
317 emit_bool(bool);
318 emit_char(char);
319 emit_str(&str);
320 emit_raw_bytes(&[u8]);
321 }
322}