charon_lib/ast/
expressions_utils.rs1use 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 pub fn is_local(&self) -> bool {
25 self.as_local().is_some()
26 }
27
28 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 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_unit() -> Self {
94 ConstantExpr {
95 kind: ConstantExprKind::Adt(None, Vec::new()),
96 ty: Ty::mk_unit(),
97 }
98 }
99
100 pub fn mk_usize(scalar: ScalarValue) -> Self {
101 ConstantExpr {
102 kind: ConstantExprKind::Literal(Literal::Scalar(scalar)),
103 ty: Ty::mk_usize(),
104 }
105 }
106}
107
108impl Operand {
109 pub fn mk_const_unit() -> Self {
110 Operand::Const(Box::new(ConstantExpr::mk_unit()))
111 }
112
113 pub fn ty(&self) -> &Ty {
114 match self {
115 Operand::Copy(place) | Operand::Move(place) => place.ty(),
116 Operand::Const(constant_expr) => &constant_expr.ty,
117 }
118 }
119}
120
121impl Rvalue {
122 pub fn unit_value() -> Self {
123 Rvalue::Aggregate(
124 AggregateKind::Adt(
125 TypeDeclRef {
126 id: TypeId::Tuple,
127 generics: Box::new(GenericArgs::empty()),
128 },
129 None,
130 None,
131 ),
132 Vec::new(),
133 )
134 }
135}
136
137impl BorrowKind {
138 pub fn mutable(x: bool) -> Self {
139 if x { Self::Mut } else { Self::Shared }
140 }
141}
142
143impl From<BorrowKind> for RefKind {
144 fn from(value: BorrowKind) -> Self {
145 match value {
146 BorrowKind::Shared | BorrowKind::Shallow => RefKind::Shared,
147 BorrowKind::Mut | BorrowKind::TwoPhaseMut | BorrowKind::UniqueImmutable => RefKind::Mut,
148 }
149 }
150}
151
152impl From<RefKind> for BorrowKind {
153 fn from(value: RefKind) -> Self {
154 match value {
155 RefKind::Shared => BorrowKind::Shared,
156 RefKind::Mut => BorrowKind::Mut,
157 }
158 }
159}
160
161impl ProjectionElem {
162 pub fn project_type(&self, krate: &TranslatedCrate, ty: &Ty) -> Option<Ty> {
164 use ProjectionElem::*;
165 Some(match self {
166 Deref => {
167 use TyKind::*;
168 match ty.kind() {
169 Ref(_, ty, _) | RawPtr(ty, _) => ty.clone(),
170 Adt(tref) if matches!(tref.id, TypeId::Builtin(BuiltinTy::Box)) => {
171 tref.generics.types[0].clone()
172 }
173 Adt(..) | TypeVar(_) | Literal(_) | Never | TraitType(..) | DynTrait(..)
174 | Array(..) | Slice(..) | FnPtr(..) | FnDef(..) | PtrMetadata(..)
175 | Error(..) => {
176 return None;
178 }
179 }
180 }
181 Field(pkind, field_id) => {
182 use FieldProjKind::*;
184 match pkind {
185 Adt(type_decl_id, variant_id) => {
186 let type_decl = krate.type_decls.get(*type_decl_id)?;
188 let tref = ty.as_adt()?;
189 assert!(TypeId::Adt(*type_decl_id) == tref.id);
190 use TypeDeclKind::*;
191 match &type_decl.kind {
192 Struct(fields) | Union(fields) => {
193 if variant_id.is_some() {
194 return None;
195 };
196 fields.get(*field_id)?.ty.clone().substitute(&tref.generics)
197 }
198 Enum(variants) => {
199 let variant_id = (*variant_id)?;
200 let variant = variants.get(variant_id)?;
201 variant
202 .fields
203 .get(*field_id)?
204 .ty
205 .clone()
206 .substitute(&tref.generics)
207 }
208 Opaque | Alias(_) | Error(_) => return None,
209 }
210 }
211 Tuple(_) => ty
212 .as_tuple()?
213 .get(TypeVarId::from(usize::from(*field_id)))?
214 .clone(),
215 }
216 }
217 PtrMetadata => ty.get_ptr_metadata(krate).into_type(),
218 Index { .. } | Subslice { .. } => ty.as_array_or_slice()?.clone(),
219 })
220 }
221}
222
223impl BinOp {
224 pub fn with_overflow(&self, overflow: OverflowMode) -> Self {
225 match self {
226 BinOp::Add(_) | BinOp::AddChecked => BinOp::Add(overflow),
227 BinOp::Sub(_) | BinOp::SubChecked => BinOp::Sub(overflow),
228 BinOp::Mul(_) | BinOp::MulChecked => BinOp::Mul(overflow),
229 BinOp::Div(_) => BinOp::Div(overflow),
230 BinOp::Rem(_) => BinOp::Rem(overflow),
231 BinOp::Shl(_) => BinOp::Shl(overflow),
232 BinOp::Shr(_) => BinOp::Shr(overflow),
233 _ => {
234 panic!(
235 "Cannot set overflow mode for this binary operator: {:?}",
236 self
237 );
238 }
239 }
240 }
241}
242
243impl UnOp {
244 pub fn with_overflow(&self, overflow: OverflowMode) -> Self {
245 match self {
246 UnOp::Neg(_) => UnOp::Neg(overflow),
247 _ => {
248 panic!(
249 "Cannot set overflow mode for this unary operator: {:?}",
250 self
251 );
252 }
253 }
254 }
255}
256
257impl FnPtr {
258 pub fn new(kind: FnPtrKind, generics: impl Into<BoxedArgs>) -> Self {
259 Self {
260 kind: Box::new(kind),
261 generics: generics.into(),
262 }
263 }
264
265 pub fn pre_mono_generics<'a>(&'a self, krate: &'a TranslatedCrate) -> &'a GenericArgs {
267 match *self.kind {
268 FnPtrKind::Fun(FunId::Regular(fun_id)) => krate
269 .item_name(fun_id)
270 .unwrap()
271 .mono_args()
272 .unwrap_or(&self.generics),
273 FnPtrKind::Fun(FunId::Builtin(..)) => &self.generics,
275 FnPtrKind::Trait(..) => &self.generics,
277 }
278 }
279}