Skip to main content

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(self, krate: &TranslatedCrate, proj: ProjectionElem) -> Option<Self> {
57        Some(Place {
58            ty: proj.project_type(krate, &self.ty)?,
59            kind: PlaceKind::Projection(Box::new(self), proj),
60        })
61    }
62
63    /// Dereferences the place. Panics if the type cannot be dereferenced.
64    pub fn deref(self) -> Place {
65        use TyKind::*;
66        let proj_ty = match self.ty.kind() {
67            Ref(_, ty, _) | RawPtr(ty, _) => ty.clone(),
68            Adt(tref) if matches!(tref.id, TypeId::Builtin(BuiltinTy::Box)) => {
69                tref.generics.types[0].clone()
70            }
71            Adt(..) | TypeVar(_) | Literal(_) | Never | TraitType(..) | DynTrait(..)
72            | FnPtr(..) | FnDef(..) | PtrMetadata(..) | Array(..) | Slice(_) | Error(..) => {
73                panic!("internal type error")
74            }
75        };
76        Place {
77            ty: proj_ty,
78            kind: PlaceKind::Projection(Box::new(self), ProjectionElem::Deref),
79        }
80    }
81
82    pub fn projections(&self) -> impl Iterator<Item = &ProjectionElem> {
83        let mut place = self;
84        std::iter::from_fn(move || {
85            let (new_place, proj) = place.as_projection()?;
86            place = new_place;
87            Some(proj)
88        })
89    }
90}
91
92impl ConstantExpr {
93    pub fn mk_usize(scalar: ScalarValue) -> Self {
94        ConstantExpr {
95            kind: ConstantExprKind::Literal(Literal::Scalar(scalar)),
96            ty: Ty::mk_usize(),
97        }
98    }
99}
100
101impl Operand {
102    pub fn mk_const_unit() -> Self {
103        Operand::Const(Box::new(ConstantExpr {
104            kind: ConstantExprKind::Adt(None, Vec::new()),
105            ty: Ty::mk_unit(),
106        }))
107    }
108
109    pub fn ty(&self) -> &Ty {
110        match self {
111            Operand::Copy(place) | Operand::Move(place) => place.ty(),
112            Operand::Const(constant_expr) => &constant_expr.ty,
113        }
114    }
115}
116
117impl Rvalue {
118    pub fn unit_value() -> Self {
119        Rvalue::Aggregate(
120            AggregateKind::Adt(
121                TypeDeclRef {
122                    id: TypeId::Tuple,
123                    generics: Box::new(GenericArgs::empty()),
124                },
125                None,
126                None,
127            ),
128            Vec::new(),
129        )
130    }
131}
132
133impl BorrowKind {
134    pub fn mutable(x: bool) -> Self {
135        if x { Self::Mut } else { Self::Shared }
136    }
137}
138
139impl From<BorrowKind> for RefKind {
140    fn from(value: BorrowKind) -> Self {
141        match value {
142            BorrowKind::Shared | BorrowKind::Shallow => RefKind::Shared,
143            BorrowKind::Mut | BorrowKind::TwoPhaseMut | BorrowKind::UniqueImmutable => RefKind::Mut,
144        }
145    }
146}
147
148impl From<RefKind> for BorrowKind {
149    fn from(value: RefKind) -> Self {
150        match value {
151            RefKind::Shared => BorrowKind::Shared,
152            RefKind::Mut => BorrowKind::Mut,
153        }
154    }
155}
156
157impl ProjectionElem {
158    /// Compute the type obtained when applying the current projection to a place of type `ty`.
159    pub fn project_type(&self, krate: &TranslatedCrate, ty: &Ty) -> Option<Ty> {
160        use ProjectionElem::*;
161        Some(match self {
162            Deref => {
163                use TyKind::*;
164                match ty.kind() {
165                    Ref(_, ty, _) | RawPtr(ty, _) => ty.clone(),
166                    Adt(tref) if matches!(tref.id, TypeId::Builtin(BuiltinTy::Box)) => {
167                        tref.generics.types[0].clone()
168                    }
169                    Adt(..) | TypeVar(_) | Literal(_) | Never | TraitType(..) | DynTrait(..)
170                    | Array(..) | Slice(..) | FnPtr(..) | FnDef(..) | PtrMetadata(..)
171                    | Error(..) => {
172                        // Type error
173                        return None;
174                    }
175                }
176            }
177            Field(pkind, field_id) => {
178                // Lookup the type decl
179                use FieldProjKind::*;
180                match pkind {
181                    Adt(type_decl_id, variant_id) => {
182                        // Can fail if the type declaration was not translated.
183                        let type_decl = krate.type_decls.get(*type_decl_id)?;
184                        let tref = ty.as_adt()?;
185                        assert!(TypeId::Adt(*type_decl_id) == tref.id);
186                        use TypeDeclKind::*;
187                        match &type_decl.kind {
188                            Struct(fields) | Union(fields) => {
189                                if variant_id.is_some() {
190                                    return None;
191                                };
192                                fields.get(*field_id)?.ty.clone().substitute(&tref.generics)
193                            }
194                            Enum(variants) => {
195                                let variant_id = (*variant_id)?;
196                                let variant = variants.get(variant_id)?;
197                                variant
198                                    .fields
199                                    .get(*field_id)?
200                                    .ty
201                                    .clone()
202                                    .substitute(&tref.generics)
203                            }
204                            Opaque | Alias(_) | Error(_) => return None,
205                        }
206                    }
207                    Tuple(_) => ty
208                        .as_tuple()?
209                        .get(TypeVarId::from(usize::from(*field_id)))?
210                        .clone(),
211                }
212            }
213            PtrMetadata => ty.get_ptr_metadata(krate).into_type(),
214            Index { .. } | Subslice { .. } => ty.as_array_or_slice()?.clone(),
215        })
216    }
217}
218
219impl BinOp {
220    pub fn with_overflow(&self, overflow: OverflowMode) -> Self {
221        match self {
222            BinOp::Add(_) | BinOp::AddChecked => BinOp::Add(overflow),
223            BinOp::Sub(_) | BinOp::SubChecked => BinOp::Sub(overflow),
224            BinOp::Mul(_) | BinOp::MulChecked => BinOp::Mul(overflow),
225            BinOp::Div(_) => BinOp::Div(overflow),
226            BinOp::Rem(_) => BinOp::Rem(overflow),
227            BinOp::Shl(_) => BinOp::Shl(overflow),
228            BinOp::Shr(_) => BinOp::Shr(overflow),
229            _ => {
230                panic!(
231                    "Cannot set overflow mode for this binary operator: {:?}",
232                    self
233                );
234            }
235        }
236    }
237}
238
239impl UnOp {
240    pub fn with_overflow(&self, overflow: OverflowMode) -> Self {
241        match self {
242            UnOp::Neg(_) => UnOp::Neg(overflow),
243            _ => {
244                panic!(
245                    "Cannot set overflow mode for this unary operator: {:?}",
246                    self
247                );
248            }
249        }
250    }
251}
252
253impl FnPtr {
254    pub fn new(kind: FnPtrKind, generics: impl Into<BoxedArgs>) -> Self {
255        Self {
256            kind: Box::new(kind),
257            generics: generics.into(),
258        }
259    }
260
261    /// Get the generics for the pre-monomorphization item.
262    pub fn pre_mono_generics<'a>(&'a self, krate: &'a TranslatedCrate) -> &'a GenericArgs {
263        match *self.kind {
264            FnPtrKind::Fun(FunId::Regular(fun_id)) => krate
265                .item_name(fun_id)
266                .unwrap()
267                .mono_args()
268                .unwrap_or(&self.generics),
269            //  We don't mono builtins.
270            FnPtrKind::Fun(FunId::Builtin(..)) => &self.generics,
271            // Can't happen in mono mode.
272            FnPtrKind::Trait(..) => &self.generics,
273        }
274    }
275}