1use std::cmp::{Ord, PartialOrd};
2use std::fmt;
3
4use derive_generic_visitor::{ControlFlow, Drive, DriveMut};
5use index_vec::Idx;
6use itertools::Itertools;
7use serde::{Deserialize, Serialize};
8use serde_state::{DeserializeState, SerializeState};
9
10use crate::ast::*;
11use crate::common::serialize_map_to_array::SeqHashMapToArray;
12use crate::formatter::{FmtCtx, IntoFormatter};
13use crate::ids::{IndexMap, IndexVec};
14use crate::pretty::FmtWithCtx;
15use macros::{EnumAsGetters, EnumIsA, VariantIndexArity, VariantName};
16
17generate_index_type!(FunDeclId, "Fun");
18generate_index_type!(TypeDeclId, "Adt");
19generate_index_type!(GlobalDeclId, "Global");
20generate_index_type!(TraitDeclId, "TraitDecl");
21generate_index_type!(TraitImplId, "TraitImpl");
22
23#[derive(
25 Copy,
26 Clone,
27 Debug,
28 PartialOrd,
29 Ord,
30 PartialEq,
31 Eq,
32 Hash,
33 EnumIsA,
34 EnumAsGetters,
35 VariantName,
36 VariantIndexArity,
37 Serialize,
38 Deserialize,
39 SerializeState,
40 DeserializeState,
41 Drive,
42 DriveMut,
43)]
44#[charon::variants_prefix("Id")]
45#[serde_state(stateless)]
46pub enum ItemId {
47 Type(TypeDeclId),
48 TraitDecl(TraitDeclId),
49 TraitImpl(TraitImplId),
50 Fun(FunDeclId),
51 Global(GlobalDeclId),
52}
53
54macro_rules! wrap_unwrap_enum {
56 ($enum:ident::$variant:ident($variant_ty:ident)) => {
57 impl TryFrom<$enum> for $variant_ty {
58 type Error = ();
59 fn try_from(x: $enum) -> Result<Self, Self::Error> {
60 match x {
61 $enum::$variant(x) => Ok(x),
62 _ => Err(()),
63 }
64 }
65 }
66
67 impl From<$variant_ty> for $enum {
68 fn from(x: $variant_ty) -> Self {
69 $enum::$variant(x)
70 }
71 }
72 };
73}
74
75wrap_unwrap_enum!(ItemId::Fun(FunDeclId));
76wrap_unwrap_enum!(ItemId::Global(GlobalDeclId));
77wrap_unwrap_enum!(ItemId::Type(TypeDeclId));
78wrap_unwrap_enum!(ItemId::TraitDecl(TraitDeclId));
79wrap_unwrap_enum!(ItemId::TraitImpl(TraitImplId));
80impl TryFrom<ItemId> for TypeId {
81 type Error = ();
82 fn try_from(x: ItemId) -> Result<Self, Self::Error> {
83 Ok(TypeId::Adt(x.try_into()?))
84 }
85}
86impl TryFrom<ItemId> for FunId {
87 type Error = ();
88 fn try_from(x: ItemId) -> Result<Self, Self::Error> {
89 Ok(FunId::Regular(x.try_into()?))
90 }
91}
92
93#[derive(
95 Debug, PartialEq, Eq, EnumIsA, EnumAsGetters, VariantName, VariantIndexArity, Drive, DriveMut,
96)]
97pub enum ItemByVal {
98 Type(TypeDecl),
99 Fun(FunDecl),
100 Global(GlobalDecl),
101 TraitDecl(TraitDecl),
102 TraitImpl(TraitImpl),
103}
104
105#[derive(
107 Debug, Clone, Copy, EnumIsA, EnumAsGetters, VariantName, VariantIndexArity, Drive, DriveMut,
108)]
109pub enum ItemRef<'ctx> {
110 Type(&'ctx TypeDecl),
111 Fun(&'ctx FunDecl),
112 Global(&'ctx GlobalDecl),
113 TraitDecl(&'ctx TraitDecl),
114 TraitImpl(&'ctx TraitImpl),
115}
116
117#[derive(
119 Debug, PartialEq, Eq, EnumIsA, EnumAsGetters, VariantName, VariantIndexArity, Drive, DriveMut,
120)]
121pub enum ItemRefMut<'ctx> {
122 Type(&'ctx mut TypeDecl),
123 Fun(&'ctx mut FunDecl),
124 Global(&'ctx mut GlobalDecl),
125 TraitDecl(&'ctx mut TraitDecl),
126 TraitImpl(&'ctx mut TraitImpl),
127}
128
129#[derive(
132 Debug, Clone, VariantIndexArity, VariantName, EnumAsGetters, EnumIsA, Serialize, Deserialize,
133)]
134#[charon::variants_suffix("Group")]
135pub enum GDeclarationGroup<Id> {
136 NonRec(Id),
138 Rec(Vec<Id>),
140}
141
142#[derive(
144 Debug, Clone, VariantIndexArity, VariantName, EnumAsGetters, EnumIsA, Serialize, Deserialize,
145)]
146#[charon::variants_suffix("Group")]
147pub enum DeclarationGroup {
148 Type(GDeclarationGroup<TypeDeclId>),
150 Fun(GDeclarationGroup<FunDeclId>),
152 Global(GDeclarationGroup<GlobalDeclId>),
154 TraitDecl(GDeclarationGroup<TraitDeclId>),
155 TraitImpl(GDeclarationGroup<TraitImplId>),
156 Mixed(GDeclarationGroup<ItemId>),
158}
159
160pub type DeclarationsGroups = Vec<DeclarationGroup>;
161
162pub type TargetTriple = String;
164
165#[derive(Clone, Drive, DriveMut, SerializeState, DeserializeState)]
166#[serde_state(stateless)]
167pub struct TargetInfo {
168 pub target_pointer_size: types::ByteCount,
170 pub is_little_endian: bool,
172}
173
174#[derive(Default, Clone, Drive, DriveMut, SerializeState, DeserializeState)]
176#[serde_state(state_implements = HashConsSerializerState)]
177pub struct TranslatedCrate {
178 #[drive(skip)]
180 pub crate_name: String,
181
182 #[drive(skip)]
186 #[serde_state(stateless)]
187 pub options: crate::options::CliOpts,
188
189 #[drive(skip)]
192 #[serde(with = "SeqHashMapToArray::<TargetTriple, TargetInfo>")]
193 pub target_information: SeqHashMap<TargetTriple, TargetInfo>,
194
195 #[serde_state(stateless)]
198 pub files: IndexVec<FileId, File>,
199
200 #[serde(with = "SeqHashMapToArray::<ItemId, Name>")]
205 pub item_names: SeqHashMap<ItemId, Name>,
206 #[serde(with = "SeqHashMapToArray::<ItemId, Name>")]
208 pub short_names: SeqHashMap<ItemId, Name>,
209
210 pub type_decls: IndexMap<TypeDeclId, TypeDecl>,
212 pub fun_decls: IndexMap<FunDeclId, FunDecl>,
214 pub global_decls: IndexMap<GlobalDeclId, GlobalDecl>,
216 pub trait_decls: IndexMap<TraitDeclId, TraitDecl>,
218 pub trait_impls: IndexMap<TraitImplId, TraitImpl>,
220 #[drive(skip)]
222 #[serde_state(stateless)]
223 pub ordered_decls: Option<DeclarationsGroups>,
224}
225
226impl TranslatedCrate {
227 pub fn item_name(&self, id: impl Into<ItemId>) -> Option<&Name> {
228 self.item_names.get(&id.into())
229 }
230
231 pub fn item_short_name(&self, id: impl Into<ItemId>) -> Option<&Name> {
232 let id = id.into();
233 self.short_names.get(&id).or_else(|| self.item_name(id))
234 }
235
236 pub fn get_item(&self, trans_id: impl Into<ItemId>) -> Option<ItemRef<'_>> {
237 match trans_id.into() {
238 ItemId::Type(id) => self.type_decls.get(id).map(ItemRef::Type),
239 ItemId::Fun(id) => self.fun_decls.get(id).map(ItemRef::Fun),
240 ItemId::Global(id) => self.global_decls.get(id).map(ItemRef::Global),
241 ItemId::TraitDecl(id) => self.trait_decls.get(id).map(ItemRef::TraitDecl),
242 ItemId::TraitImpl(id) => self.trait_impls.get(id).map(ItemRef::TraitImpl),
243 }
244 }
245 pub fn get_item_mut(&mut self, trans_id: ItemId) -> Option<ItemRefMut<'_>> {
246 match trans_id {
247 ItemId::Type(id) => self.type_decls.get_mut(id).map(ItemRefMut::Type),
248 ItemId::Fun(id) => self.fun_decls.get_mut(id).map(ItemRefMut::Fun),
249 ItemId::Global(id) => self.global_decls.get_mut(id).map(ItemRefMut::Global),
250 ItemId::TraitDecl(id) => self.trait_decls.get_mut(id).map(ItemRefMut::TraitDecl),
251 ItemId::TraitImpl(id) => self.trait_impls.get_mut(id).map(ItemRefMut::TraitImpl),
252 }
253 }
254 pub fn remove_item(&mut self, trans_id: ItemId) -> Option<ItemByVal> {
255 self.short_names.swap_remove(&trans_id);
256 self.item_names.swap_remove(&trans_id);
257 self.remove_item_temporarily(trans_id)
258 }
259 pub fn remove_item_temporarily(&mut self, trans_id: ItemId) -> Option<ItemByVal> {
261 match trans_id {
262 ItemId::Type(id) => self.type_decls.remove(id).map(ItemByVal::Type),
263 ItemId::Fun(id) => self.fun_decls.remove(id).map(ItemByVal::Fun),
264 ItemId::Global(id) => self.global_decls.remove(id).map(ItemByVal::Global),
265 ItemId::TraitDecl(id) => self.trait_decls.remove(id).map(ItemByVal::TraitDecl),
266 ItemId::TraitImpl(id) => self.trait_impls.remove(id).map(ItemByVal::TraitImpl),
267 }
268 }
269 pub fn set_new_item_slot(&mut self, id: ItemId, item: impl Into<ItemByVal>) {
271 let item = item.into();
272 self.item_names
273 .insert(id, item.as_ref().item_meta().name.clone());
274 self.set_item_slot(id, item);
275 }
276 pub fn set_item_slot(&mut self, id: ItemId, item: impl Into<ItemByVal>) {
278 match item.into() {
279 ItemByVal::Type(decl) => self.type_decls.set_slot(*id.as_type().unwrap(), decl),
280 ItemByVal::Fun(decl) => self.fun_decls.set_slot(*id.as_fun().unwrap(), decl),
281 ItemByVal::Global(decl) => self.global_decls.set_slot(*id.as_global().unwrap(), decl),
282 ItemByVal::TraitDecl(decl) => self
283 .trait_decls
284 .set_slot(*id.as_trait_decl().unwrap(), decl),
285 ItemByVal::TraitImpl(decl) => self
286 .trait_impls
287 .set_slot(*id.as_trait_impl().unwrap(), decl),
288 }
289 }
290
291 pub fn all_ids(&self) -> impl Iterator<Item = ItemId> + use<> {
292 self.type_decls
293 .all_indices()
294 .map(ItemId::Type)
295 .chain(self.trait_decls.all_indices().map(ItemId::TraitDecl))
296 .chain(self.trait_impls.all_indices().map(ItemId::TraitImpl))
297 .chain(self.global_decls.all_indices().map(ItemId::Global))
298 .chain(self.fun_decls.all_indices().map(ItemId::Fun))
299 }
300 pub fn all_items(&self) -> impl Iterator<Item = ItemRef<'_>> {
301 self.type_decls
302 .iter()
303 .map(ItemRef::Type)
304 .chain(self.trait_decls.iter().map(ItemRef::TraitDecl))
305 .chain(self.trait_impls.iter().map(ItemRef::TraitImpl))
306 .chain(self.global_decls.iter().map(ItemRef::Global))
307 .chain(self.fun_decls.iter().map(ItemRef::Fun))
308 }
309 pub fn all_items_mut(&mut self) -> impl Iterator<Item = ItemRefMut<'_>> {
310 self.type_decls
311 .iter_mut()
312 .map(ItemRefMut::Type)
313 .chain(self.trait_impls.iter_mut().map(ItemRefMut::TraitImpl))
314 .chain(self.trait_decls.iter_mut().map(ItemRefMut::TraitDecl))
315 .chain(self.fun_decls.iter_mut().map(ItemRefMut::Fun))
316 .chain(self.global_decls.iter_mut().map(ItemRefMut::Global))
317 }
318 pub fn all_items_with_ids(&self) -> impl Iterator<Item = (ItemId, ItemRef<'_>)> {
319 self.all_items().map(|item| (item.id(), item))
320 }
321
322 pub fn the_target_information(&self) -> &TargetInfo {
325 self.target_information
326 .values()
327 .exactly_one()
328 .ok()
329 .expect("called `the_target_information` on a multi-target crate")
330 }
331}
332
333impl ItemByVal {
334 pub fn as_ref(&self) -> ItemRef<'_> {
335 match self {
336 Self::Type(d) => ItemRef::Type(d),
337 Self::Fun(d) => ItemRef::Fun(d),
338 Self::Global(d) => ItemRef::Global(d),
339 Self::TraitDecl(d) => ItemRef::TraitDecl(d),
340 Self::TraitImpl(d) => ItemRef::TraitImpl(d),
341 }
342 }
343 pub fn as_mut(&mut self) -> ItemRefMut<'_> {
344 match self {
345 Self::Type(d) => ItemRefMut::Type(d),
346 Self::Fun(d) => ItemRefMut::Fun(d),
347 Self::Global(d) => ItemRefMut::Global(d),
348 Self::TraitDecl(d) => ItemRefMut::TraitDecl(d),
349 Self::TraitImpl(d) => ItemRefMut::TraitImpl(d),
350 }
351 }
352}
353
354impl<'ctx> ItemRef<'ctx> {
355 pub fn id(&self) -> ItemId {
356 match self {
357 ItemRef::Type(d) => d.def_id.into(),
358 ItemRef::Fun(d) => d.def_id.into(),
359 ItemRef::Global(d) => d.def_id.into(),
360 ItemRef::TraitDecl(d) => d.def_id.into(),
361 ItemRef::TraitImpl(d) => d.def_id.into(),
362 }
363 }
364
365 pub fn to_owned(&self) -> ItemByVal {
366 match *self {
367 Self::Type(d) => ItemByVal::Type(d.clone()),
368 Self::Fun(d) => ItemByVal::Fun(d.clone()),
369 Self::Global(d) => ItemByVal::Global(d.clone()),
370 Self::TraitDecl(d) => ItemByVal::TraitDecl(d.clone()),
371 Self::TraitImpl(d) => ItemByVal::TraitImpl(d.clone()),
372 }
373 }
374
375 pub fn item_meta(&self) -> &'ctx ItemMeta {
376 match self {
377 Self::Type(d) => &d.item_meta,
378 Self::Fun(d) => &d.item_meta,
379 Self::Global(d) => &d.item_meta,
380 Self::TraitDecl(d) => &d.item_meta,
381 Self::TraitImpl(d) => &d.item_meta,
382 }
383 }
384 pub fn generic_params(&self) -> &'ctx GenericParams {
386 match self {
387 ItemRef::Type(d) => &d.generics,
388 ItemRef::Fun(d) => &d.generics,
389 ItemRef::Global(d) => &d.generics,
390 ItemRef::TraitDecl(d) => &d.generics,
391 ItemRef::TraitImpl(d) => &d.generics,
392 }
393 }
394
395 pub fn parent_info(&self) -> &'ctx ItemSource {
397 match self {
398 ItemRef::Fun(d) => &d.src,
399 ItemRef::Global(d) => &d.src,
400 ItemRef::Type(_) | ItemRef::TraitDecl(_) | ItemRef::TraitImpl(_) => {
401 &ItemSource::TopLevel
402 }
403 }
404 }
405
406 pub fn identity_args(&self) -> GenericArgs {
408 self.generic_params().identity_args()
409 }
410
411 pub fn drive<V: VisitAst>(&self, visitor: &mut V) -> ControlFlow<V::Break> {
414 match *self {
415 ItemRef::Type(d) => visitor.visit(d),
416 ItemRef::Fun(d) => visitor.visit(d),
417 ItemRef::Global(d) => visitor.visit(d),
418 ItemRef::TraitDecl(d) => visitor.visit(d),
419 ItemRef::TraitImpl(d) => visitor.visit(d),
420 }
421 }
422
423 pub fn dyn_visit<T: AstVisitable>(&self, f: impl FnMut(&T)) {
425 match *self {
426 ItemRef::Type(d) => d.dyn_visit(f),
427 ItemRef::Fun(d) => d.dyn_visit(f),
428 ItemRef::Global(d) => d.dyn_visit(f),
429 ItemRef::TraitDecl(d) => d.dyn_visit(f),
430 ItemRef::TraitImpl(d) => d.dyn_visit(f),
431 }
432 }
433}
434
435impl<'ctx> ItemRefMut<'ctx> {
436 pub fn as_ref(&self) -> ItemRef<'_> {
437 match self {
438 ItemRefMut::Type(d) => ItemRef::Type(d),
439 ItemRefMut::Fun(d) => ItemRef::Fun(d),
440 ItemRefMut::Global(d) => ItemRef::Global(d),
441 ItemRefMut::TraitDecl(d) => ItemRef::TraitDecl(d),
442 ItemRefMut::TraitImpl(d) => ItemRef::TraitImpl(d),
443 }
444 }
445 pub fn reborrow(&mut self) -> ItemRefMut<'_> {
446 match self {
447 ItemRefMut::Type(d) => ItemRefMut::Type(d),
448 ItemRefMut::Fun(d) => ItemRefMut::Fun(d),
449 ItemRefMut::Global(d) => ItemRefMut::Global(d),
450 ItemRefMut::TraitDecl(d) => ItemRefMut::TraitDecl(d),
451 ItemRefMut::TraitImpl(d) => ItemRefMut::TraitImpl(d),
452 }
453 }
454
455 pub fn set_id(&mut self, id: ItemId) {
456 match (self, id) {
457 (Self::Type(d), ItemId::Type(id)) => d.def_id = id,
458 (Self::Fun(d), ItemId::Fun(id)) => d.def_id = id,
459 (Self::Global(d), ItemId::Global(id)) => d.def_id = id,
460 (Self::TraitDecl(d), ItemId::TraitDecl(id)) => d.def_id = id,
461 (Self::TraitImpl(d), ItemId::TraitImpl(id)) => d.def_id = id,
462 _ => unreachable!(),
463 }
464 }
465
466 pub fn item_meta(&mut self) -> &mut ItemMeta {
467 match self {
468 Self::Type(d) => &mut d.item_meta,
469 Self::Fun(d) => &mut d.item_meta,
470 Self::Global(d) => &mut d.item_meta,
471 Self::TraitDecl(d) => &mut d.item_meta,
472 Self::TraitImpl(d) => &mut d.item_meta,
473 }
474 }
475 pub fn generic_params(&mut self) -> &mut GenericParams {
477 match self {
478 ItemRefMut::Type(d) => &mut d.generics,
479 ItemRefMut::Fun(d) => &mut d.generics,
480 ItemRefMut::Global(d) => &mut d.generics,
481 ItemRefMut::TraitDecl(d) => &mut d.generics,
482 ItemRefMut::TraitImpl(d) => &mut d.generics,
483 }
484 }
485
486 pub fn drive_mut<V: VisitAstMut>(&mut self, visitor: &mut V) -> ControlFlow<V::Break> {
489 match self {
490 ItemRefMut::Type(d) => visitor.visit(*d),
491 ItemRefMut::Fun(d) => visitor.visit(*d),
492 ItemRefMut::Global(d) => visitor.visit(*d),
493 ItemRefMut::TraitDecl(d) => visitor.visit(*d),
494 ItemRefMut::TraitImpl(d) => visitor.visit(*d),
495 }
496 }
497
498 pub fn dyn_visit_mut<T: AstVisitable>(&mut self, f: impl FnMut(&mut T)) {
500 match self {
501 ItemRefMut::Type(d) => d.dyn_visit_mut(f),
502 ItemRefMut::Fun(d) => d.dyn_visit_mut(f),
503 ItemRefMut::Global(d) => d.dyn_visit_mut(f),
504 ItemRefMut::TraitDecl(d) => d.dyn_visit_mut(f),
505 ItemRefMut::TraitImpl(d) => d.dyn_visit_mut(f),
506 }
507 }
508}
509
510impl fmt::Display for TranslatedCrate {
511 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
512 let fmt: &FmtCtx = &self.into_fmt();
513 match &self.ordered_decls {
514 None => {
515 for d in &self.type_decls {
517 writeln!(f, "{}\n", d.with_ctx(fmt))?
518 }
519 for d in &self.global_decls {
520 writeln!(f, "{}\n", d.with_ctx(fmt))?
521 }
522 for d in &self.trait_decls {
523 writeln!(f, "{}\n", d.with_ctx(fmt))?
524 }
525 for d in &self.trait_impls {
526 writeln!(f, "{}\n", d.with_ctx(fmt))?
527 }
528 for d in &self.fun_decls {
529 writeln!(f, "{}\n", d.with_ctx(fmt))?
530 }
531 }
532 Some(ordered_decls) => {
533 for gr in ordered_decls {
534 for id in gr.get_ids() {
535 writeln!(f, "{}\n", fmt.format_decl_id(id))?
536 }
537 }
538 }
539 }
540 fmt::Result::Ok(())
541 }
542}
543
544impl<'a> IntoFormatter for &'a TranslatedCrate {
545 type C = FmtCtx<'a>;
546
547 fn into_fmt(self) -> Self::C {
548 FmtCtx {
549 translated: Some(self),
550 ..Default::default()
551 }
552 }
553}
554
555pub trait HasIdxMapOf<Id: Idx>: std::ops::Index<Id, Output: Sized> {
556 fn get_idx_map(&self) -> &IndexMap<Id, Self::Output>;
557 fn get_idx_map_mut(&mut self) -> &mut IndexMap<Id, Self::Output>;
558}
559
560macro_rules! mk_index_impls {
562 ($ty:ident.$field:ident[$idx:ty]: $output:ty) => {
563 impl std::ops::Index<$idx> for $ty {
564 type Output = $output;
565 fn index(&self, index: $idx) -> &Self::Output {
566 &self.$field[index]
567 }
568 }
569 impl std::ops::IndexMut<$idx> for $ty {
570 fn index_mut(&mut self, index: $idx) -> &mut Self::Output {
571 &mut self.$field[index]
572 }
573 }
574 impl HasIdxMapOf<$idx> for $ty {
575 fn get_idx_map(&self) -> &IndexMap<$idx, Self::Output> {
576 &self.$field
577 }
578 fn get_idx_map_mut(&mut self) -> &mut IndexMap<$idx, Self::Output> {
579 &mut self.$field
580 }
581 }
582 };
583}
584mk_index_impls!(TranslatedCrate.type_decls[TypeDeclId]: TypeDecl);
585mk_index_impls!(TranslatedCrate.fun_decls[FunDeclId]: FunDecl);
586mk_index_impls!(TranslatedCrate.global_decls[GlobalDeclId]: GlobalDecl);
587mk_index_impls!(TranslatedCrate.trait_decls[TraitDeclId]: TraitDecl);
588mk_index_impls!(TranslatedCrate.trait_impls[TraitImplId]: TraitImpl);