charon_lib/ast/
expressions_utils.rs

1//! This file groups everything which is linked to implementations about [crate::expressions]
2use crate::ast::*;
3
4impl Place {
5    pub fn new(local_id: LocalId, ty: Ty) -> Place {
6        Place {
7            kind: PlaceKind::Local(local_id),
8            ty,
9        }
10    }
11
12    pub fn new_global(global: GlobalDeclRef, ty: Ty) -> Place {
13        Place {
14            kind: PlaceKind::Global(global),
15            ty,
16        }
17    }
18
19    pub fn ty(&self) -> &Ty {
20        &self.ty
21    }
22
23    /// Whether this place corresponds to a local variable without any projections.
24    pub fn is_local(&self) -> bool {
25        self.as_local().is_some()
26    }
27
28    /// If this place corresponds to an unprojected local, return the variable id.
29    pub fn as_local(&self) -> Option<LocalId> {
30        self.kind.as_local().copied()
31    }
32
33    pub fn as_projection(&self) -> Option<(&Self, &ProjectionElem)> {
34        self.kind.as_projection().map(|(pl, pj)| (pl.as_ref(), pj))
35    }
36
37    #[deprecated(note = "use `local_id` instead")]
38    pub fn var_id(&self) -> Option<LocalId> {
39        self.local_id()
40    }
41    pub fn local_id(&self) -> Option<LocalId> {
42        match &self.kind {
43            PlaceKind::Local(var_id) => Some(*var_id),
44            PlaceKind::Projection(subplace, _) => subplace.local_id(),
45            PlaceKind::Global(_) => None,
46        }
47    }
48
49    pub fn project(self, elem: ProjectionElem, ty: Ty) -> Self {
50        Self {
51            kind: PlaceKind::Projection(Box::new(self), elem),
52            ty,
53        }
54    }
55
56    pub fn project_auto_ty(
57        self,
58        krate: &TranslatedCrate,
59        proj: ProjectionElem,
60    ) -> Result<Self, ()> {
61        Ok(Place {
62            ty: proj.project_type(krate, &self.ty)?,
63            kind: PlaceKind::Projection(Box::new(self), proj),
64        })
65    }
66
67    /// Dereferences the place. Panics if the type cannot be dereferenced.
68    pub fn deref(self) -> Place {
69        use TyKind::*;
70        let proj_ty = match self.ty.kind() {
71            Ref(_, ty, _) | RawPtr(ty, _) => ty.clone(),
72            Adt(tref) if matches!(tref.id, TypeId::Builtin(BuiltinTy::Box)) => {
73                tref.generics.types[0].clone()
74            }
75            Adt(..) | TypeVar(_) | Literal(_) | Never | TraitType(..) | DynTrait(..)
76            | FnPtr(..) | FnDef(..) | PtrMetadata(..) | Error(..) => panic!("internal type error"),
77        };
78        Place {
79            ty: proj_ty,
80            kind: PlaceKind::Projection(Box::new(self), ProjectionElem::Deref),
81        }
82    }
83
84    pub fn projections<'a>(&'a self) -> impl Iterator<Item = &'a ProjectionElem> {
85        let mut place = self;
86        std::iter::from_fn(move || {
87            let (new_place, proj) = place.as_projection()?;
88            place = new_place;
89            Some(proj)
90        })
91    }
92}
93
94impl Operand {
95    pub fn mk_const_unit() -> Self {
96        Operand::Const(Box::new(ConstantExpr {
97            kind: ConstantExprKind::Adt(None, Vec::new()),
98            ty: Ty::mk_unit(),
99        }))
100    }
101
102    pub fn ty(&self) -> &Ty {
103        match self {
104            Operand::Copy(place) | Operand::Move(place) => place.ty(),
105            Operand::Const(constant_expr) => &constant_expr.ty,
106        }
107    }
108}
109
110impl Rvalue {
111    pub fn unit_value() -> Self {
112        Rvalue::Aggregate(
113            AggregateKind::Adt(
114                TypeDeclRef {
115                    id: TypeId::Tuple,
116                    generics: Box::new(GenericArgs::empty()),
117                },
118                None,
119                None,
120            ),
121            Vec::new(),
122        )
123    }
124}
125
126impl BorrowKind {
127    pub fn mutable(x: bool) -> Self {
128        if x { Self::Mut } else { Self::Shared }
129    }
130}
131
132impl From<BorrowKind> for RefKind {
133    fn from(value: BorrowKind) -> Self {
134        match value {
135            BorrowKind::Shared | BorrowKind::Shallow => RefKind::Shared,
136            BorrowKind::Mut | BorrowKind::TwoPhaseMut | BorrowKind::UniqueImmutable => RefKind::Mut,
137        }
138    }
139}
140
141impl From<RefKind> for BorrowKind {
142    fn from(value: RefKind) -> Self {
143        match value {
144            RefKind::Shared => BorrowKind::Shared,
145            RefKind::Mut => BorrowKind::Mut,
146        }
147    }
148}
149
150impl ProjectionElem {
151    /// Compute the type obtained when applying the current projection to a place of type `ty`.
152    pub fn project_type(&self, krate: &TranslatedCrate, ty: &Ty) -> Result<Ty, ()> {
153        use ProjectionElem::*;
154        Ok(match self {
155            Deref => {
156                use TyKind::*;
157                match ty.kind() {
158                    Ref(_, ty, _) | RawPtr(ty, _) => ty.clone(),
159                    Adt(tref) if matches!(tref.id, TypeId::Builtin(BuiltinTy::Box)) => {
160                        tref.generics.types[0].clone()
161                    }
162                    Adt(..) | TypeVar(_) | Literal(_) | Never | TraitType(..) | DynTrait(..)
163                    | FnPtr(..) | FnDef(..) | PtrMetadata(..) | Error(..) => {
164                        // Type error
165                        return Err(());
166                    }
167                }
168            }
169            Field(pkind, field_id) => {
170                // Lookup the type decl
171                use FieldProjKind::*;
172                match pkind {
173                    Adt(type_decl_id, variant_id) => {
174                        // Can fail if the type declaration was not translated.
175                        let type_decl = krate.type_decls.get(*type_decl_id).ok_or(())?;
176                        let tref = ty.as_adt().ok_or(())?;
177                        assert!(TypeId::Adt(*type_decl_id) == tref.id);
178                        use TypeDeclKind::*;
179                        match &type_decl.kind {
180                            Struct(fields) | Union(fields) => {
181                                if variant_id.is_some() {
182                                    return Err(());
183                                };
184                                fields
185                                    .get(*field_id)
186                                    .ok_or(())?
187                                    .ty
188                                    .clone()
189                                    .substitute(&tref.generics)
190                            }
191                            Enum(variants) => {
192                                let variant_id = variant_id.ok_or(())?;
193                                let variant = variants.get(variant_id).ok_or(())?;
194                                variant
195                                    .fields
196                                    .get(*field_id)
197                                    .ok_or(())?
198                                    .ty
199                                    .clone()
200                                    .substitute(&tref.generics)
201                            }
202                            Opaque | Alias(_) | Error(_) => return Err(()),
203                        }
204                    }
205                    Tuple(_) => ty
206                        .as_tuple()
207                        .ok_or(())?
208                        .get(TypeVarId::from(usize::from(*field_id)))
209                        .ok_or(())?
210                        .clone(),
211                }
212            }
213            PtrMetadata => ty.get_ptr_metadata(krate).into_type(),
214            Index { .. } | Subslice { .. } => ty.as_array_or_slice().ok_or(())?.clone(),
215        })
216    }
217}
218
219impl From<ConstGeneric> for ConstantExprKind {
220    fn from(cg: ConstGeneric) -> Self {
221        match cg {
222            ConstGeneric::Global(id) => ConstantExprKind::Global(GlobalDeclRef {
223                id,
224                generics: Box::new(GenericArgs::empty()),
225            }),
226            ConstGeneric::Var(var) => ConstantExprKind::Var(var),
227            ConstGeneric::Value(lit) => ConstantExprKind::Literal(lit),
228        }
229    }
230}
231
232impl BinOp {
233    pub fn with_overflow(&self, overflow: OverflowMode) -> Self {
234        match self {
235            BinOp::Add(_) | BinOp::AddChecked => BinOp::Add(overflow),
236            BinOp::Sub(_) | BinOp::SubChecked => BinOp::Sub(overflow),
237            BinOp::Mul(_) | BinOp::MulChecked => BinOp::Mul(overflow),
238            BinOp::Div(_) => BinOp::Div(overflow),
239            BinOp::Rem(_) => BinOp::Rem(overflow),
240            BinOp::Shl(_) => BinOp::Shl(overflow),
241            BinOp::Shr(_) => BinOp::Shr(overflow),
242            _ => {
243                panic!(
244                    "Cannot set overflow mode for this binary operator: {:?}",
245                    self
246                );
247            }
248        }
249    }
250}
251
252impl UnOp {
253    pub fn with_overflow(&self, overflow: OverflowMode) -> Self {
254        match self {
255            UnOp::Neg(_) => UnOp::Neg(overflow),
256            _ => {
257                panic!(
258                    "Cannot set overflow mode for this unary operator: {:?}",
259                    self
260                );
261            }
262        }
263    }
264}
265
266impl FnPtr {
267    pub fn new(kind: FnPtrKind, generics: impl Into<BoxedArgs>) -> Self {
268        Self {
269            kind: Box::new(kind),
270            generics: generics.into(),
271        }
272    }
273
274    /// Get the generics for the pre-monomorphization item.
275    pub fn pre_mono_generics<'a>(&'a self, krate: &'a TranslatedCrate) -> &'a GenericArgs {
276        match *self.kind {
277            FnPtrKind::Fun(FunId::Regular(fun_id)) => krate
278                .item_name(fun_id)
279                .unwrap()
280                .mono_args()
281                .unwrap_or(&self.generics),
282            //  We don't mono builtins.
283            FnPtrKind::Fun(FunId::Builtin(..)) => &self.generics,
284            // Can't happen in mono mode.
285            FnPtrKind::Trait(..) => &self.generics,
286        }
287    }
288}