1use super::translate_crate::RustcItem;
3pub use super::translate_crate::TransItemSource;
4use super::translate_generics::{BindingLevel, LifetimeMutabilityComputer};
5use crate::frontend as front;
6use crate::frontend::SInto;
7use charon_lib::ast::*;
8use charon_lib::formatter::{FmtCtx, IntoFormatter};
9use charon_lib::ids::IndexVec;
10use charon_lib::options::TranslateOptions;
11use petgraph::graphmap::DiGraphMap;
12use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
13use rustc_middle::ty::TyCtxt;
14use rustc_span::def_id::DefId as RDefId;
15use std::borrow::Cow;
16use std::cell::RefCell;
17use std::collections::VecDeque;
18use std::fmt::Debug;
19use std::ops::{Deref, DerefMut};
20use std::path::PathBuf;
21use std::sync::Arc;
22use std::{fmt, mem};
23
24pub(crate) use charon_lib::errors::{
26 DepSource, ErrorCtx, Level, error_assert, raise_error, register_error,
27};
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30pub enum ItemOrModuleId {
31 Item(ItemId),
32 Module(RDefId),
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
37pub enum ItemOrModuleKind {
38 Item(ItemKind),
39 Module,
41}
42
43impl ItemOrModuleKind {
44 pub fn from_def_kind(kind: &front::DefKind) -> Option<Self> {
45 use front::DefKind::*;
46 Some(match kind {
47 Enum | Struct | Union | TyAlias | ForeignTy | AssocTy | Closure | OpaqueTy => {
48 Self::Item(ItemKind::Type)
49 }
50 Fn | AssocFn | Ctor(_, front::CtorKind::Fn) => Self::Item(ItemKind::Fun),
51 Const | Static { .. } | AssocConst | AnonConst | PromotedConst => {
52 Self::Item(ItemKind::Global)
53 }
54 Trait | TraitAlias => Self::Item(ItemKind::TraitDecl),
55 Impl { of_trait: true } => Self::Item(ItemKind::TraitImpl),
56 Impl { of_trait: false } | Mod | ForeignMod => Self::Module,
57 _ => return None,
58 })
59 }
60
61 pub fn is_fun_decl(&self) -> bool {
62 matches!(self, Self::Item(ItemKind::Fun))
63 }
64
65 pub fn is_trait_impl(&self) -> bool {
66 matches!(self, Self::Item(ItemKind::TraitImpl))
67 }
68}
69
70impl Ord for ItemOrModuleId {
73 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
74 use std::cmp::Ordering;
75 match (self, other) {
76 (Self::Item(a), Self::Item(b)) => a.cmp(b),
77 (Self::Module(a), Self::Module(b)) => {
78 (a.krate.as_u32(), a.index.as_u32()).cmp(&(b.krate.as_u32(), b.index.as_u32()))
79 }
80 (Self::Item(_), Self::Module(_)) => Ordering::Less,
81 (Self::Module(_), Self::Item(_)) => Ordering::Greater,
82 }
83 }
84}
85
86impl PartialOrd for ItemOrModuleId {
87 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
88 Some(self.cmp(other))
89 }
90}
91
92impl ItemOrModuleId {
93 pub fn as_item(&self) -> Option<ItemId> {
94 match self {
95 Self::Item(id) => Some(*id),
96 Self::Module(_) => None,
97 }
98 }
99
100 pub fn expect_item<T: TryFrom<ItemId>>(&self) -> T {
101 self.as_item()
102 .expect("expected a translated item")
103 .try_into()
104 .ok()
105 .expect("unexpected item kind")
106 }
107}
108
109#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
111pub enum ContainmentNode {
112 Start,
113 WholeCrate,
114 Item(ItemOrModuleId),
115 TraitMethod(TraitDeclId, TraitMethodId),
116}
117
118impl From<ItemOrModuleId> for ContainmentNode {
119 fn from(id: ItemOrModuleId) -> Self {
120 Self::Item(id)
121 }
122}
123
124impl From<ItemId> for ContainmentNode {
125 fn from(id: ItemId) -> Self {
126 Self::Item(ItemOrModuleId::Item(id))
127 }
128}
129
130pub struct TranslateCtx<'tcx> {
132 pub tcx: TyCtxt<'tcx>,
134 pub sysroot: PathBuf,
136 pub frontend_state: front::StateWithBase<'tcx>,
138
139 pub options: TranslateOptions,
141 pub translated: TranslatedCrate,
143
144 pub method_status: IndexMap<TraitDeclId, IndexVec<TraitMethodId, MethodStatus>>,
153
154 pub id_map: HashMap<TransItemSource<'tcx>, ItemId>,
156 pub reverse_id_map: HashMap<ItemId, TransItemSource<'tcx>>,
158 pub assoc_item_id_map: HashMap<front::DefId, AssocItemId>,
160 pub file_to_id: HashMap<FileName, FileId>,
162
163 pub errors: RefCell<ErrorCtx>,
165 pub items_to_translate: VecDeque<TransItemSource<'tcx>>,
167 pub processed: HashSet<TransItemSource<'tcx>>,
169 pub containment_graph: DiGraphMap<ContainmentNode, (), rustc_hash::FxBuildHasher>,
173 pub translate_stack: Vec<ItemOrModuleId>,
175 pub cached_spans: HashMap<rustc_span::Span, Span>,
177 pub cached_span_datas: HashMap<rustc_span::Span, meta::SpanData>,
179 pub cached_file_ids: HashMap<rustc_span::StableSourceFileId, FileId>,
181 pub cached_names: HashMap<TransItemSource<'tcx>, Name>,
183 pub exported_fns: Option<HashMap<String, ExportedFns<'tcx>>>,
186 pub exported_foreign_items: HashMap<rustc_span::def_id::CrateNum, HashSet<RDefId>>,
189 pub lt_mutability_computer: LifetimeMutabilityComputer,
191 pub monomorphic_layouts: SeqHashMap<TypeDeclRef, Layout>,
193 pub intrinsic_def_ids: HashMap<rustc_span::Symbol, RDefId>,
195}
196
197#[derive(Debug, Default, Clone)]
199pub enum ExportedFns<'tcx> {
200 #[default]
201 None,
202 Strong(rustc_middle::ty::Instance<'tcx>),
203 Weak(Vec<rustc_middle::ty::Instance<'tcx>>),
204 AllocatorShim(rustc_middle::ty::Instance<'tcx>),
205 Many,
208}
209
210impl<'tcx> ExportedFns<'tcx> {
211 pub(crate) fn merge(&mut self, other: ExportedFns<'tcx>) {
212 use ExportedFns::*;
213 *self = match (std::mem::take(self), other) {
214 (Many, _) | (_, Many) | (Strong(_), Strong(_)) => Many,
216 (strong @ Strong(_), _) | (_, strong @ Strong(_)) => strong,
218 (Weak(mut weak), Weak(other)) => {
220 weak.extend(other);
221 Weak(weak)
222 }
223 (weak @ Weak(_), None) | (None, weak @ Weak(_)) => weak,
224 (None, None) => None,
225 (AllocatorShim(_), _) | (_, AllocatorShim(_)) => {
227 panic!("allocator shims are added after merging exported functions")
228 }
229 };
230 }
231}
232
233#[derive(Debug)]
235pub enum MethodStatus {
236 Unused {
237 implementors: HashSet<FunDeclId>,
241 },
242 Used,
243}
244
245impl Default for MethodStatus {
246 fn default() -> Self {
247 Self::Unused {
248 implementors: Default::default(),
249 }
250 }
251}
252
253pub(crate) struct ItemTransCtx<'tcx, 'ctx> {
256 pub item_src: TransItemSource<'tcx>,
258 pub item_id: ItemOrModuleId,
260 pub t_ctx: &'ctx mut TranslateCtx<'tcx>,
262 pub frontend_state: front::StateWithOwner<'tcx>,
264 pub error_on_trait_proof_error: bool,
267
268 pub binding_levels: BindingStack<BindingLevel<'tcx>>,
272 pub lifetime_freshener: Option<IndexMap<RegionId, ()>>,
274 pub recording_mono_layouts: bool,
279}
280
281pub fn catch_sinto<S, T, U>(
283 s: &S,
284 err: &mut ErrorCtx,
285 krate: &TranslatedCrate,
286 span: Span,
287 x: &T,
288) -> Result<U, Error>
289where
290 T: Debug + SInto<S, U>,
291{
292 let unwind_safe_s = std::panic::AssertUnwindSafe(s);
293 let unwind_safe_x = std::panic::AssertUnwindSafe(x);
294 std::panic::catch_unwind(move || unwind_safe_x.sinto(*unwind_safe_s)).or_else(|_| {
295 raise_error!(
296 err,
297 crate(krate),
298 span,
299 "The frontend panicked when translating `{x:?}`."
300 )
301 })
302}
303
304impl<'tcx> TranslateCtx<'tcx> {
305 pub fn span_err(&self, span: Span, msg: &str, level: Level) -> Error {
307 self.errors
308 .borrow_mut()
309 .span_err(&self.translated, span, msg, level)
310 }
311
312 pub fn get_target_triple(&self) -> TargetTriple {
313 self.tcx.sess.opts.target_triple.tuple().to_owned()
314 }
315
316 pub fn catch_sinto<S, T, U>(&mut self, s: &S, span: Span, x: &T) -> Result<U, Error>
318 where
319 T: Debug + SInto<S, U>,
320 {
321 catch_sinto(s, &mut self.errors.borrow_mut(), &self.translated, span, x)
322 }
323
324 pub fn poly_frontend_def(
329 &mut self,
330 def_id: &front::DefId,
331 ) -> Result<Arc<front::FullDef<'tcx>>, Error> {
332 self.frontend_def_for_item(&TransItemSource::polymorphic(def_id))
333 }
334
335 pub fn frontend_def_for_item(
338 &mut self,
339 item: &TransItemSource<'tcx>,
340 ) -> Result<Arc<front::FullDef<'tcx>>, Error> {
341 item.full_def(&self.frontend_state).or_else(|_| {
342 let def_id = item.def_id();
343 let span = self.def_span(def_id);
344 raise_error!(
345 self,
346 span,
347 "The frontend panicked when translating `{def_id:?}`."
348 )
349 })
350 }
351
352 pub(crate) fn with_def_id<F, T>(
353 &mut self,
354 def_id: &front::DefId,
355 item_id: &ItemOrModuleId,
356 f: F,
357 ) -> T
358 where
359 F: FnOnce(&mut Self) -> T,
360 {
361 let mut errors = self.errors.borrow_mut();
362 let current_def_id = mem::replace(&mut errors.def_id, item_id.as_item());
363 let current_def_id_is_local = mem::replace(&mut errors.def_id_is_local, def_id.is_local());
364 drop(errors); let ret = f(self);
366 let mut errors = self.errors.borrow_mut();
367 errors.def_id = current_def_id;
368 errors.def_id_is_local = current_def_id_is_local;
369 ret
370 }
371}
372
373impl<'tcx, 'ctx> ItemTransCtx<'tcx, 'ctx> {
374 pub(crate) fn new(
376 item_src: TransItemSource<'tcx>,
377 item_id: ItemOrModuleId,
378 t_ctx: &'ctx mut TranslateCtx<'tcx>,
379 ) -> Self {
380 use crate::frontend::BaseState;
381 let frontend_state_with_id = t_ctx
382 .frontend_state
383 .clone()
384 .with_frontend_owner(item_src.def_id());
385 ItemTransCtx {
386 item_src,
387 item_id,
388 t_ctx,
389 frontend_state: frontend_state_with_id,
390 error_on_trait_proof_error: true,
391 binding_levels: Default::default(),
392 lifetime_freshener: None,
393 recording_mono_layouts: false,
394 }
395 }
396
397 pub fn monomorphize(&self) -> bool {
399 matches!(
400 self.item_src.item,
401 RustcItem::Mono(..) | RustcItem::MonoTrait(..)
402 )
403 }
404
405 pub fn should_monomorphize_item(&self, item: &front::ItemRef) -> bool {
407 self.options.monomorphize_with_frontend
410 && (TransItemSource::is_for_trait(&item.def_id) || !item.mentions_non_lt_param)
411 }
412
413 pub fn span_err(&self, span: Span, msg: &str, level: Level) -> Error {
414 self.t_ctx.span_err(span, msg, level)
415 }
416
417 pub fn frontend_state(&self) -> &front::StateWithBase<'tcx> {
418 &self.t_ctx.frontend_state
419 }
420
421 pub fn frontend_state_with_id(&self) -> &front::StateWithOwner<'tcx> {
422 &self.frontend_state
423 }
424
425 pub fn catch_sinto<T, U>(&mut self, span: Span, x: &T) -> Result<U, Error>
426 where
427 T: Debug + SInto<front::StateWithOwner<'tcx>, U>,
428 {
429 self.t_ctx.catch_sinto(&self.frontend_state, span, x)
430 }
431
432 pub fn frontend_def(
435 &mut self,
436 item: &front::ItemRef<'tcx>,
437 ) -> Result<Arc<front::FullDef<'tcx>>, Error> {
438 let item = if self.monomorphize() && !TransItemSource::is_for_trait(self.item_src.def_id())
439 {
440 TransItemSource::monomorphic(item)
441 } else {
442 TransItemSource::polymorphic(&item.def_id)
443 };
444 self.frontend_def_for_item(&item)
445 }
446}
447
448impl<'tcx> Deref for ItemTransCtx<'tcx, '_> {
449 type Target = TranslateCtx<'tcx>;
450 fn deref(&self) -> &Self::Target {
451 self.t_ctx
452 }
453}
454impl<'tcx> DerefMut for ItemTransCtx<'tcx, '_> {
455 fn deref_mut(&mut self) -> &mut Self::Target {
456 self.t_ctx
457 }
458}
459
460impl<'a> IntoFormatter for &'a TranslateCtx<'_> {
461 type C = FmtCtx<'a>;
462 fn into_fmt(self) -> Self::C {
463 self.translated.into_fmt()
464 }
465}
466
467impl<'a> IntoFormatter for &'a ItemTransCtx<'_, '_> {
468 type C = FmtCtx<'a>;
469 fn into_fmt(self) -> Self::C {
470 FmtCtx {
471 generics: self.binding_levels.map_ref(|bl| Cow::Borrowed(&bl.params)),
472 ..self.t_ctx.into_fmt()
473 }
474 }
475}
476
477impl<'tcx> fmt::Display for TranslateCtx<'tcx> {
478 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
479 self.translated.fmt(f)
480 }
481}