charon_lib/ast/expressions.rs
1//! Implements expressions: paths, operands, rvalues, lvalues
2
3use crate::ast::*;
4use derive_generic_visitor::{Drive, DriveMut};
5use macros::{EnumAsGetters, EnumIsA, EnumToGetters, VariantIndexArity, VariantName};
6use serde::{Deserialize, Serialize};
7use serde_state::{DeserializeState, SerializeState};
8use std::vec::Vec;
9
10#[derive(Debug, PartialEq, Eq, Clone, SerializeState, DeserializeState, Drive, DriveMut)]
11#[serde_state(state_implements = HashConsSerializerState)] // Avoid corecursive impls due to perfect derive
12pub struct Place {
13 pub kind: PlaceKind,
14 pub ty: Ty,
15}
16
17#[derive(
18 Debug,
19 PartialEq,
20 Eq,
21 Clone,
22 EnumIsA,
23 EnumAsGetters,
24 EnumToGetters,
25 SerializeState,
26 DeserializeState,
27 Drive,
28 DriveMut,
29)]
30#[charon::variants_prefix("Place")]
31pub enum PlaceKind {
32 /// A local variable in a function body.
33 Local(LocalId),
34 /// A subplace of a place.
35 Projection(Box<Place>, ProjectionElem),
36 /// A global (const or static).
37 /// Not present in MIR; introduced in [simplify_constants.rs].
38 Global(GlobalDeclRef),
39}
40
41/// Note that we don't have the equivalent of "downcasts".
42/// Downcasts are actually necessary, for instance when initializing enumeration
43/// values: the value is initially `Bottom`, and we need a way of knowing the
44/// variant.
45/// For example:
46/// `((_0 as Right).0: T2) = move _1;`
47/// In MIR, downcasts always happen before field projections: in our internal
48/// language, we thus merge downcasts and field projections.
49#[derive(
50 Debug,
51 PartialEq,
52 Eq,
53 Clone,
54 EnumIsA,
55 EnumAsGetters,
56 EnumToGetters,
57 VariantName,
58 SerializeState,
59 DeserializeState,
60 Drive,
61 DriveMut,
62)]
63pub enum ProjectionElem {
64 /// Dereference a shared/mutable reference, a box, or a raw pointer.
65 Deref,
66 /// Projection from ADTs (variants, structures).
67 /// We allow projections to be used as left-values and right-values.
68 /// We should never have projections to fields of symbolic variants (they
69 /// should have been expanded before through a match).
70 Field(FieldProjKind, FieldId),
71 /// A built-in pointer (a reference, raw pointer, or `Box`) in Rust is always a fat pointer: it
72 /// contains an address and metadata for the pointed-to place. This metadata is empty for sized
73 /// types, it's the length for slices, and the vtable for `dyn Trait`.
74 ///
75 /// We consider such pointers to be like a struct with two fields; this represent access to the
76 /// metadata "field".
77 PtrMetadata,
78 /// MIR imposes that the argument to an index projection be a local variable, meaning
79 /// that even constant indices into arrays are let-bound as separate variables.
80 /// We **eliminate** this variant in a micro-pass for LLBC.
81 #[charon::rename("ProjIndex")]
82 Index {
83 offset: Box<Operand>,
84 #[drive(skip)]
85 from_end: bool,
86 },
87 /// Take a subslice of a slice or array. If `from_end` is `true` this is
88 /// `slice[from..slice.len() - to]`, otherwise this is `slice[from..to]`.
89 /// We **eliminate** this variant in a micro-pass for LLBC.
90 Subslice {
91 from: Box<Operand>,
92 to: Box<Operand>,
93 #[drive(skip)]
94 from_end: bool,
95 },
96}
97
98#[derive(
99 Debug,
100 PartialEq,
101 Eq,
102 Copy,
103 Clone,
104 EnumIsA,
105 EnumAsGetters,
106 SerializeState,
107 DeserializeState,
108 Drive,
109 DriveMut,
110)]
111#[charon::variants_prefix("Proj")]
112pub enum FieldProjKind {
113 Adt(TypeDeclId, Option<VariantId>),
114 /// If we project from a tuple, the projection kind gives the arity of the tuple.
115 #[drive(skip)]
116 Tuple(usize),
117}
118
119#[derive(
120 Debug,
121 PartialEq,
122 Eq,
123 Copy,
124 Clone,
125 EnumIsA,
126 EnumAsGetters,
127 Serialize,
128 Deserialize,
129 Drive,
130 DriveMut,
131)]
132#[charon::variants_prefix("B")]
133pub enum BorrowKind {
134 Shared,
135 Mut,
136 /// See <https://doc.rust-lang.org/beta/nightly-rustc/rustc_middle/mir/enum.MutBorrowKind.html#variant.TwoPhaseBorrow>
137 /// and <https://rustc-dev-guide.rust-lang.org/borrow_check/two_phase_borrows.html>
138 TwoPhaseMut,
139 /// Those are typically introduced when using guards in matches, to make sure guards don't
140 /// change the variant of an enum value while me match over it.
141 ///
142 /// See <https://doc.rust-lang.org/beta/nightly-rustc/rustc_middle/mir/enum.FakeBorrowKind.html#variant.Shallow>.
143 Shallow,
144 /// Data must be immutable but not aliasable. In other words you can't mutate the data but you
145 /// can mutate *through it*, e.g. if it points to a `&mut T`. This is only used in closure
146 /// captures, e.g.
147 /// ```rust,ignore
148 /// let mut z = 3;
149 /// let x: &mut isize = &mut z;
150 /// let y = || *x += 5;
151 /// ```
152 /// Here the captured variable can't be `&mut &mut x` since the `x` binding is not mutable, yet
153 /// we must be able to mutate what it points to.
154 ///
155 /// See <https://doc.rust-lang.org/beta/nightly-rustc/rustc_middle/mir/enum.MutBorrowKind.html#variant.ClosureCapture>.
156 UniqueImmutable,
157}
158
159/// Unary operation
160#[derive(
161 Debug,
162 PartialEq,
163 Eq,
164 Clone,
165 EnumIsA,
166 VariantName,
167 SerializeState,
168 DeserializeState,
169 Drive,
170 DriveMut,
171)]
172#[charon::rename("Unop")]
173pub enum UnOp {
174 Not,
175 /// This can overflow, for `-i::MIN`.
176 #[drive(skip)]
177 #[serde_state(stateless)]
178 Neg(OverflowMode),
179 /// Casts are rvalues in MIR, but we treat them as unops.
180 Cast(CastKind),
181}
182
183/// Nullary operation
184#[derive(
185 Debug,
186 PartialEq,
187 Eq,
188 Clone,
189 EnumIsA,
190 VariantName,
191 SerializeState,
192 DeserializeState,
193 Drive,
194 DriveMut,
195)]
196#[charon::rename("Nullop")]
197pub enum NullOp {
198 SizeOf,
199 AlignOf,
200 OffsetOf(TypeDeclRef, Option<VariantId>, FieldId),
201 UbChecks,
202 OverflowChecks,
203 ContractChecks,
204}
205
206/// For all the variants: the first type gives the source type, the second one gives
207/// the destination type.
208#[derive(
209 Debug,
210 PartialEq,
211 Eq,
212 Clone,
213 EnumIsA,
214 VariantName,
215 SerializeState,
216 DeserializeState,
217 Drive,
218 DriveMut,
219)]
220#[charon::variants_prefix("Cast")]
221pub enum CastKind {
222 /// Conversion between types in `{Integer, Bool}`
223 /// Remark: for now we don't support conversions with Char.
224 Scalar(LiteralTy, LiteralTy),
225 RawPtr(Ty, Ty),
226 FnPtr(Ty, Ty),
227 /// [Unsize coercion](https://doc.rust-lang.org/std/ops/trait.CoerceUnsized.html). This is
228 /// either `[T; N]` -> `[T]` or `T: Trait` -> `dyn Trait` coercions, behind a pointer
229 /// (reference, `Box`, or other type that implements `CoerceUnsized`).
230 ///
231 /// The special case of `&[T; N]` -> `&[T]` coercion is caught by `UnOp::ArrayToSlice`.
232 Unsize(Ty, Ty, UnsizingMetadata),
233 /// Reinterprets the bits of a value of one type as another type, i.e. exactly what
234 /// [`std::mem::transmute`] does.
235 Transmute(Ty, Ty),
236 /// Converts a receiver type with `dyn Trait<...>` to a concrete type `T`, used in vtable method shims.
237 /// Valid conversions are references, raw pointers, and (optionally) boxes:
238 /// - `&[mut] dyn Trait<...>` -> `&[mut] T`
239 /// - `*[mut] dyn Trait<...>` -> `*[mut] T`
240 /// - `Box<dyn Trait<...>>` -> `Box<T>` when no `--raw-boxes`
241 ///
242 /// For possible receivers, see: <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>.
243 /// Other receivers, e.g., `Rc` should be unpacked before the cast and re-boxed after.
244 /// FIXME(ssyram): but this is not implemented yet, namely, there may still be
245 /// something like `Rc<dyn Trait<...>> -> Rc<T>` in the types.
246 Concretize(Ty, Ty),
247}
248
249#[derive(
250 Debug,
251 PartialEq,
252 Eq,
253 Clone,
254 EnumIsA,
255 VariantName,
256 SerializeState,
257 DeserializeState,
258 Drive,
259 DriveMut,
260)]
261#[charon::variants_prefix("Meta")]
262pub enum UnsizingMetadata {
263 /// Cast from `[T; N]` to `[T]`.
264 Length(ConstGeneric),
265 /// Cast from a sized value to a `dyn Trait` value. The `TraitRef` gives the trait for which
266 /// we're getting a vtable (this is the _principal_ trait of the `dyn Trait` target). The second
267 /// field is the vtable instance, if we could resolve it.
268 VTable(TraitRef, Option<GlobalDeclRef>),
269 /// Cast from `dyn Trait` to `dyn OtherTrait`. The fields indicate how to retreive the vtable:
270 /// it's always either the same we already had, or the vtable for a (possibly nested) supertrait.
271 ///
272 /// Note that we cheat in one case: when upcasting to a marker trait (e.g. `dyn Trait -> dyn
273 /// Sized`), we keep the current vtable.
274 VTableUpcast(Vec<FieldId>),
275 Unknown,
276}
277
278#[derive(Debug, PartialEq, Eq, Copy, Clone, Serialize, Deserialize)]
279#[charon::variants_prefix("O")]
280pub enum OverflowMode {
281 /// If this operation overflows, it panics. Only exists in debug mode, for instance in
282 /// `a + b`, and only if `--reconstruct-fallible-operations` is passed to Charon. Otherwise the
283 /// bound check will be explicit.
284 Panic,
285 /// If this operation overflows, it is UB; for instance in `core::num::unchecked_add`. This can
286 /// exists in safe code, but will always be preceded by a bounds check.
287 UB,
288 /// If this operation overflows, it wraps around for instance in `core::num::wrapping_add`,
289 /// or `a + b` in release mode.
290 Wrap,
291}
292
293/// Binary operations.
294#[derive(
295 Debug,
296 PartialEq,
297 Eq,
298 Copy,
299 Clone,
300 EnumIsA,
301 VariantName,
302 SerializeState,
303 DeserializeState,
304 Drive,
305 DriveMut,
306)]
307#[charon::rename("Binop")]
308#[serde_state(stateless)]
309pub enum BinOp {
310 BitXor,
311 BitAnd,
312 BitOr,
313 Eq,
314 Lt,
315 Le,
316 Ne,
317 Ge,
318 Gt,
319 #[drive(skip)]
320 Add(OverflowMode),
321 #[drive(skip)]
322 Sub(OverflowMode),
323 #[drive(skip)]
324 Mul(OverflowMode),
325 #[drive(skip)]
326 Div(OverflowMode),
327 #[drive(skip)]
328 Rem(OverflowMode),
329 /// Returns `(result, did_overflow)`, where `result` is the result of the operation with
330 /// wrapping semantics, and `did_overflow` is a boolean that indicates whether the operation
331 /// overflowed. This operation does not fail.
332 AddChecked,
333 /// Like `AddChecked`.
334 SubChecked,
335 /// Like `AddChecked`.
336 MulChecked,
337 /// Fails if the shift is bigger than the bit-size of the type.
338 #[drive(skip)]
339 Shl(OverflowMode),
340 /// Fails if the shift is bigger than the bit-size of the type.
341 #[drive(skip)]
342 Shr(OverflowMode),
343 /// `BinOp(Offset, ptr, n)` for `ptr` a pointer to type `T` offsets `ptr` by `n * size_of::<T>()`.
344 Offset,
345 /// `BinOp(Cmp, a, b)` returns `-1u8` if `a < b`, `0u8` if `a == b`, and `1u8` if `a > b`.
346 Cmp,
347}
348
349#[derive(
350 Debug,
351 PartialEq,
352 Eq,
353 Clone,
354 EnumIsA,
355 EnumToGetters,
356 EnumAsGetters,
357 VariantName,
358 SerializeState,
359 DeserializeState,
360 Drive,
361 DriveMut,
362)]
363#[serde_state(state_implements = HashConsSerializerState)] // Avoid corecursive impls due to perfect derive
364pub enum Operand {
365 Copy(Place),
366 Move(Place),
367 /// Constant value (including constant and static variables)
368 #[charon::rename("Constant")]
369 Const(Box<ConstantExpr>),
370}
371
372/// A function identifier. See [crate::ullbc_ast::Terminator]
373#[derive(
374 Debug,
375 Clone,
376 PartialEq,
377 Eq,
378 Hash,
379 EnumIsA,
380 EnumAsGetters,
381 VariantName,
382 SerializeState,
383 DeserializeState,
384 Drive,
385 DriveMut,
386)]
387#[charon::variants_prefix("F")]
388#[serde_state(stateless)]
389pub enum FunId {
390 /// A "regular" function (function local to the crate, external function
391 /// not treated as a primitive one).
392 Regular(FunDeclId),
393 /// A primitive function, coming from a standard library (for instance:
394 /// `alloc::boxed::Box::new`).
395 /// TODO: rename to "Primitive"
396 #[charon::rename("FBuiltin")]
397 Builtin(BuiltinFunId),
398}
399
400impl From<FunDeclId> for FunId {
401 fn from(id: FunDeclId) -> Self {
402 Self::Regular(id)
403 }
404}
405impl From<BuiltinFunId> for FunId {
406 fn from(id: BuiltinFunId) -> Self {
407 Self::Builtin(id)
408 }
409}
410
411/// An built-in function identifier, identifying a function coming from a
412/// standard library.
413#[derive(
414 Debug,
415 Clone,
416 Copy,
417 PartialEq,
418 Eq,
419 Hash,
420 EnumIsA,
421 EnumAsGetters,
422 VariantName,
423 Serialize,
424 Deserialize,
425 Drive,
426 DriveMut,
427)]
428pub enum BuiltinFunId {
429 /// Used instead of `alloc::boxed::Box::new` when `--treat-box-as-builtin` is set.
430 BoxNew,
431 /// Cast `&[T; N]` to `&[T]`.
432 ///
433 /// This is used instead of unsizing coercions when `--ops-to-function-calls` is set.
434 ArrayToSliceShared,
435 /// Cast `&mut [T; N]` to `&mut [T]`.
436 ///
437 /// This is used instead of unsizing coercions when `--ops-to-function-calls` is set.
438 ArrayToSliceMut,
439 /// `repeat(n, x)` returns an array where `x` has been replicated `n` times.
440 ///
441 /// This is used instead of `Rvalue::ArrayRepeat` when `--ops-to-function-calls` is set.
442 ArrayRepeat,
443 /// A built-in funciton introduced instead of array/slice place indexing when
444 /// `--index-to-function-calls` is set. The signature depends on the parameters. It could look
445 /// like:
446 /// - `fn ArrayIndexShared<T,N>(&[T;N], usize) -> &T`
447 /// - `fn SliceIndexShared<T>(&[T], usize) -> &T`
448 /// - `fn ArraySubSliceShared<T,N>(&[T;N], usize, usize) -> &[T]`
449 /// - `fn SliceSubSliceMut<T>(&mut [T], usize, usize) -> &mut [T]`
450 /// - etc
451 Index(BuiltinIndexOp),
452 /// Build a raw pointer, from a data pointer and metadata. The metadata can be unit, if
453 /// building a thin pointer.
454 ///
455 /// This is used instead of `AggregateKind::RawPtr` when `--ops-to-function-calls` is set.
456 PtrFromParts(RefKind),
457}
458
459/// One of 8 built-in indexing operations.
460#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Drive, DriveMut)]
461pub struct BuiltinIndexOp {
462 /// Whether this is a slice or array.
463 #[drive(skip)]
464 pub is_array: bool,
465 /// Whether we're indexing mutably or not. Determines the type ofreference of the input and
466 /// output.
467 pub mutability: RefKind,
468 /// Whether we're indexing a single element or a subrange. If `true`, the function takes
469 /// two indices and the output is a slice; otherwise, the function take one index and the
470 /// output is a reference to a single element.
471 #[drive(skip)]
472 pub is_range: bool,
473}
474
475/// Reference to a function declaration or builtin function.
476#[derive(Debug, Clone, SerializeState, DeserializeState, PartialEq, Eq, Hash, Drive, DriveMut)]
477pub struct MaybeBuiltinFunDeclRef {
478 pub id: FunId,
479 pub generics: BoxedArgs,
480 pub trait_ref: Option<TraitRef>,
481}
482
483/// Reference to a trait method.
484#[derive(Debug, Clone, SerializeState, DeserializeState, PartialEq, Eq, Hash, Drive, DriveMut)]
485pub struct TraitMethodRef {
486 pub trait_ref: TraitRef,
487 pub name: TraitItemName,
488 pub generics: BoxedArgs,
489 /// Reference to the method declaration; can be derived from the trait_ref, provided here for
490 /// convenience. The generic args are for the method, not for this function.
491 pub method_decl_id: FunDeclId,
492}
493
494#[derive(
495 Debug,
496 Clone,
497 PartialEq,
498 Eq,
499 EnumAsGetters,
500 SerializeState,
501 DeserializeState,
502 Drive,
503 DriveMut,
504 Hash,
505)]
506pub enum FnPtrKind {
507 #[charon::rename("FunId")]
508 Fun(FunId),
509 /// If a trait: the reference to the trait and the id of the trait method.
510 /// The fun decl id is not really necessary - we put it here for convenience
511 /// purposes.
512 #[charon::rename("TraitMethod")]
513 Trait(TraitRef, TraitItemName, FunDeclId),
514}
515
516impl From<FunId> for FnPtrKind {
517 fn from(id: FunId) -> Self {
518 Self::Fun(id)
519 }
520}
521impl From<FunDeclId> for FnPtrKind {
522 fn from(id: FunDeclId) -> Self {
523 Self::Fun(id.into())
524 }
525}
526
527#[derive(Debug, PartialEq, Eq, Clone, SerializeState, DeserializeState, Drive, DriveMut, Hash)]
528pub struct FnPtr {
529 pub kind: Box<FnPtrKind>,
530 pub generics: BoxedArgs,
531}
532
533impl From<FunDeclRef> for FnPtr {
534 fn from(fn_ref: FunDeclRef) -> Self {
535 FnPtr::new(fn_ref.id.into(), fn_ref.generics)
536 }
537}
538
539#[derive(Debug, PartialEq, Eq, Clone, SerializeState, DeserializeState, Drive, DriveMut, Hash)]
540pub enum Provenance {
541 Global(GlobalDeclRef),
542 Function(FunDeclRef),
543 Unknown,
544}
545
546/// A byte, in the MiniRust sense: it can either be uninitialized, a concrete u8 value,
547/// or part of a pointer with provenance (e.g. to a global or a function)
548#[derive(Debug, PartialEq, Eq, Clone, SerializeState, DeserializeState, Drive, DriveMut, Hash)]
549pub enum Byte {
550 /// An uninitialized byte
551 Uninit,
552 /// A concrete byte value
553 Value(u8),
554 /// A byte that is part of a pointer with provenance. The u8 is the offset within the
555 /// pointer. Note that we do not have an actual value for this pointer byte, unlike
556 /// MiniRust, as that is non-deterministic.
557 Provenance(Provenance, u8),
558}
559
560/// A constant expression.
561///
562/// Only the [`ConstantExprKind::Literal`] and [`ConstantExprKind::Var`]
563/// cases are left in the final LLBC.
564///
565/// The other cases come from a straight translation from the MIR:
566///
567/// [`ConstantExprKind::Adt`] case:
568/// It is a bit annoying, but rustc treats some ADT and tuple instances as
569/// constants when generating MIR:
570/// - an enumeration with one variant and no fields is a constant.
571/// - a structure with no field is a constant.
572/// - sometimes, Rust stores the initialization of an ADT as a constant
573/// (if all the fields are constant) rather than as an aggregated value
574/// We later desugar those to regular ADTs, see [regularize_constant_adts.rs].
575///
576/// [`ConstantExprKind::Global`] case: access to a global variable. We later desugar it to
577/// a copy of a place global.
578///
579/// [`ConstantExprKind::Ref`] case: reference to a constant value. We later desugar it to a separate
580/// statement.
581///
582/// [`ConstantExprKind::FnPtr`] case: a function pointer (to a top-level function).
583///
584/// Remark:
585/// MIR seems to forbid more complex expressions like paths. For instance,
586/// reading the constant `a.b` is translated to `{ _1 = const a; _2 = (_1.0) }`.
587#[derive(
588 Debug,
589 Hash,
590 PartialEq,
591 Eq,
592 Clone,
593 VariantName,
594 EnumIsA,
595 EnumAsGetters,
596 SerializeState,
597 DeserializeState,
598 Drive,
599 DriveMut,
600)]
601#[charon::variants_prefix("C")]
602pub enum ConstantExprKind {
603 #[serde_state(stateless)]
604 Literal(Literal),
605 /// In most situations:
606 /// Enumeration with one variant with no fields, structure with
607 /// no fields, unit (encoded as a 0-tuple).
608 ///
609 /// Less frequently: arbitrary ADT values.
610 ///
611 /// We eliminate this case in a micro-pass.
612 Adt(Option<VariantId>, Vec<ConstantExpr>),
613 Array(Vec<ConstantExpr>),
614 Slice(Vec<ConstantExpr>),
615 /// The value is a top-level constant/static.
616 ///
617 /// We eliminate this case in a micro-pass.
618 ///
619 /// Remark: constants can actually have generic parameters.
620 /// ```text
621 /// struct V<const N: usize, T> {
622 /// x: [T; N],
623 /// }
624 ///
625 /// impl<const N: usize, T> V<N, T> {
626 /// const LEN: usize = N; // This has generics <N, T>
627 /// }
628 ///
629 /// fn use_v<const N: usize, T>(v: V<N, T>) {
630 /// let l = V::<N, T>::LEN; // We need to provided a substitution here
631 /// }
632 /// ```
633 Global(GlobalDeclRef),
634 ///
635 /// A trait constant.
636 ///
637 /// Ex.:
638 /// ```text
639 /// impl Foo for Bar {
640 /// const C : usize = 32; // <-
641 /// }
642 /// ```
643 ///
644 /// Remark: trait constants can not be used in types, they are necessarily
645 /// values.
646 TraitConst(TraitRef, TraitItemName),
647 /// A shared reference to a constant value.
648 ///
649 /// We eliminate this case in a micro-pass.
650 Ref(Box<ConstantExpr>),
651 /// A pointer to a mutable static.
652 ///
653 /// We eliminate this case in a micro-pass.
654 Ptr(RefKind, Box<ConstantExpr>),
655 /// A const generic var
656 Var(ConstGenericDbVar),
657 /// Function definition -- this is a ZST constant
658 FnDef(FnPtr),
659 /// A function pointer to a function item; this is an actual pointer to that function item.
660 ///
661 /// We eliminate this case in a micro-pass.
662 FnPtr(FnPtr),
663 /// A pointer with no provenance (e.g. 0 for the null pointer)
664 ///
665 /// We eliminate this case in a micro-pass.
666 #[drive(skip)]
667 PtrNoProvenance(u128),
668 /// Raw memory value obtained from constant evaluation. Used when a more structured
669 /// representation isn't possible (e.g. for unions) or just isn't implemented yet.
670 #[drive(skip)]
671 RawMemory(Vec<Byte>),
672 /// A constant expression that Charon still doesn't handle, along with the reason why.
673 #[drive(skip)]
674 Opaque(String),
675}
676
677#[derive(Debug, Hash, PartialEq, Eq, Clone, SerializeState, DeserializeState, Drive, DriveMut)]
678#[serde_state(state_implements = HashConsSerializerState)] // Avoid corecursive impls due to perfect derive
679pub struct ConstantExpr {
680 pub kind: ConstantExprKind,
681 pub ty: Ty,
682}
683
684/// TODO: we could factor out [Rvalue] and function calls (for LLBC, not ULLBC).
685/// We can also factor out the unops, binops with the function calls.
686/// TODO: move the aggregate kind to operands
687/// TODO: we should prefix the type variants with "R" or "Rv", this would avoid collisions
688#[derive(
689 Debug,
690 Clone,
691 EnumToGetters,
692 EnumAsGetters,
693 EnumIsA,
694 SerializeState,
695 DeserializeState,
696 Drive,
697 DriveMut,
698)]
699pub enum Rvalue {
700 /// Lifts an operand as an rvalue.
701 Use(Operand),
702 /// Takes a reference to the given place.
703 /// The `Operand` refers to the init value of the metadata, it is `()` if no metadata
704 #[charon::rename("RvRef")]
705 Ref {
706 place: Place,
707 #[serde_state(stateless)]
708 kind: BorrowKind,
709 ptr_metadata: Operand,
710 },
711 /// Takes a raw pointer with the given mutability to the given place. This is generated by
712 /// pointer casts like `&v as *const _` or raw borrow expressions like `&raw const v.`
713 /// Like `Ref`, the `Operand` refers to the init value of the metadata, it is `()` if no metadata.
714 RawPtr {
715 place: Place,
716 kind: RefKind,
717 ptr_metadata: Operand,
718 },
719 /// Binary operations (note that we merge "checked" and "unchecked" binops)
720 BinaryOp(BinOp, Operand, Operand),
721 /// Unary operation (e.g. not, neg)
722 UnaryOp(UnOp, Operand),
723 /// Nullary operation (e.g. `size_of`)
724 NullaryOp(NullOp, Ty),
725 /// Discriminant read. Reads the discriminant value of an enum. The place must have the type of
726 /// an enum. The discriminant in question is the one in the `discriminant` field of the
727 /// corresponding `Variant`. This can be different than the value stored in memory (called
728 /// `tag`). That one is described by [`DiscriminantLayout`] and [`TagEncoding`].
729 Discriminant(Place),
730 /// Creates an aggregate value, like a tuple, a struct or an enum:
731 /// ```text
732 /// l = List::Cons { value:x, tail:tl };
733 /// ```
734 /// Note that in some MIR passes (like optimized MIR), aggregate values are
735 /// decomposed, like below:
736 /// ```text
737 /// (l as List::Cons).value = x;
738 /// (l as List::Cons).tail = tl;
739 /// ```
740 /// Because we may want to plug our translation mechanism at various
741 /// places, we need to take both into accounts in the translation and in
742 /// our semantics. Aggregate value initialization is easy, you might want
743 /// to have a look at expansion of `Bottom` values for explanations about the
744 /// other case.
745 ///
746 /// Remark: in case of closures, the aggregated value groups the closure id
747 /// together with its state.
748 Aggregate(AggregateKind, Vec<Operand>),
749 /// Length of a place of type `[T]` or `[T; N]`. This applies to the place itself, not to a
750 /// pointer value. This is inserted by rustc in a single case: slice patterns.
751 /// ```text
752 /// fn slice_pattern_4(x: &[()]) {
753 /// match x {
754 /// [_named] => (),
755 /// _ => (),
756 /// }
757 /// }
758 /// ```
759 Len(Place, Ty, Option<ConstGeneric>),
760 /// `Repeat(x, n)` creates an array where `x` is copied `n` times.
761 ///
762 /// We translate this to a function call for LLBC.
763 Repeat(Operand, Ty, ConstGeneric),
764 /// Transmutes a `*mut u8` (obtained from `malloc`) into shallow-initialized `Box<T>`. This
765 /// only appears as part of lowering `Box::new()` in some cases. We reconstruct the original
766 /// `Box::new()` call, but sometimes may fail to do so, leaking the expression.
767 ShallowInitBox(Operand, Ty),
768}
769
770/// An aggregated ADT.
771///
772/// Note that ADTs are desaggregated at some point in MIR. For instance, if
773/// we have in Rust:
774/// ```ignore
775/// let ls = Cons(hd, tl);
776/// ```
777///
778/// In MIR we have (yes, the discriminant update happens *at the end* for some
779/// reason):
780/// ```text
781/// (ls as Cons).0 = move hd;
782/// (ls as Cons).1 = move tl;
783/// discriminant(ls) = 0; // assuming `Cons` is the variant of index 0
784/// ```
785///
786/// Rem.: in the Aeneas semantics, both cases are handled (in case of desaggregated
787/// initialization, `ls` is initialized to `⊥`, then this `⊥` is expanded to
788/// `Cons (⊥, ⊥)` upon the first assignment, at which point we can initialize
789/// the field 0, etc.).
790#[derive(Debug, Clone, VariantIndexArity, SerializeState, DeserializeState, Drive, DriveMut)]
791#[charon::variants_prefix("Aggregated")]
792pub enum AggregateKind {
793 /// A struct, enum or union aggregate. The `VariantId`, if present, indicates this is an enum
794 /// and the aggregate uses that variant. The `FieldId`, if present, indicates this is a union
795 /// and the aggregate writes into that field. Otherwise this is a struct.
796 Adt(TypeDeclRef, Option<VariantId>, Option<FieldId>),
797 /// We don't put this with the ADT cas because this is the only built-in type
798 /// with aggregates, and it is a primitive type. In particular, it makes
799 /// sense to treat it differently because it has a variable number of fields.
800 Array(Ty, ConstGeneric),
801 /// Construct a raw pointer from a pointer value, and its metadata (can be unit, if building
802 /// a thin pointer). The type is the type of the pointee.
803 /// We lower this to a builtin function call for LLBC in [crate::transform::simplify_output::ops_to_function_calls].
804 RawPtr(Ty, RefKind),
805}