Skip to main content

charon_lib/ast/bodies/
expressions.rs

1//! Implements expressions: paths, operands, rvalues, lvalues
2use crate::ast::*;
3use derive_generic_visitor::{Drive, DriveMut, DriveTwo};
4use enum_as_inner::EnumAsInner;
5use serde::{Deserialize, Serialize};
6use serde_state::{DeserializeState, SerializeState};
7use std::vec::Vec;
8
9/// An expression that evaluates to a value. This is the RHS of an assignment.
10#[derive(Debug, Clone, PartialEq, Eq)]
11#[derive(EnumAsInner)]
12#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
13pub enum Rvalue {
14    /// Lifts an operand as an rvalue.
15    Use(Operand, WithRetag),
16    /// Takes a reference to the given place.
17    /// The `Operand` refers to the init value of the metadata, it is `()` if no metadata
18    #[cfg_attr(feature = "charon_on_charon", charon::rename("RvRef"))]
19    Ref {
20        place: Place,
21        #[serde_state(stateless)]
22        kind: BorrowKind,
23        ptr_metadata: Operand,
24    },
25    /// Takes a raw pointer with the given mutability to the given place. This is generated by
26    /// pointer casts like `&v as *const _` or raw borrow expressions like `&raw const v.`
27    /// Like `Ref`, the `Operand` refers to the init value of the metadata, it is `()` if no metadata.
28    RawPtr {
29        place: Place,
30        kind: RefKind,
31        ptr_metadata: Operand,
32    },
33    /// Binary operations.
34    BinaryOp(BinOp, Operand, Operand),
35    /// Unary operation (e.g. not, neg)
36    UnaryOp(UnOp, Operand),
37    /// An operation with no inputs.
38    NullaryOp(NullOp),
39    /// Discriminant read. Reads the discriminant value of an enum. The place must have the type of
40    /// an enum. The discriminant in question is the one in the `discriminant` field of the
41    /// corresponding `Variant`. This can be different than the value stored in memory (called
42    /// `tag`); that one is described by [`Discriminator`] and [`VariantLayout::tagger`].
43    Discriminant(Place),
44    /// Creates an aggregate value, like a tuple, a struct or an enum:
45    /// ```text
46    /// l = List::Cons { value:x, tail:tl };
47    /// ```
48    /// Note that in some MIR passes (like optimized MIR), aggregate values are
49    /// decomposed, like below:
50    /// ```text
51    /// (l as List::Cons).value = x;
52    /// (l as List::Cons).tail = tl;
53    /// ```
54    /// Because we may want to plug our translation mechanism at various
55    /// places, we need to take both into accounts in the translation and in
56    /// our semantics. Aggregate value initialization is easy, you might want
57    /// to have a look at expansion of `Bottom` values for explanations about the
58    /// other case.
59    ///
60    /// Remark: in case of closures, the aggregated value groups the closure id
61    /// together with its state.
62    Aggregate(AggregateKind, Vec<Operand>),
63    /// `Repeat(x, n)` creates an array containing `n` copies of `x`.
64    Repeat {
65        operand: Operand,
66        count: ConstantExpr,
67        /// Proof that the element type is `Copy`.
68        elem_is_copy: TraitRef,
69        /// Proof that the element type is `Sized`; absent with `--hide-marker-traits`.
70        elem_is_sized: Option<TraitRef>,
71    },
72}
73
74#[derive(Debug, Clone, PartialEq, Eq)]
75#[derive(EnumAsInner)]
76#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
77#[serde_state(state_implements = DedupSerializerState)] // Avoid corecursive impls due to perfect derive
78pub enum Operand {
79    /// Copy the value inside this place. The `TraitRef` proves that its type implements `Copy`.
80    Copy(Place, TraitRef),
81    /// Read the value inside this place. This is allowed for non-`Copy` values, and only used when
82    /// it is sound to do so.
83    ///
84    /// Used for MIR's `CopyForDeref`, reading the value of named constants, and reads introduced
85    /// by Charon such as pointer metadata.
86    Read(Place),
87    /// Move the value out of this place.
88    Move(Place),
89    /// Use the value of this constant.
90    #[cfg_attr(feature = "charon_on_charon", charon::rename("Constant"))]
91    Const(ConstantExpr),
92}
93
94/// Used for [`Rvalue::Use`] to indicate whether the operand should be retagged (this is used
95/// for Rust's aliasing model).
96#[derive(Debug, Clone, PartialEq, Eq, Hash)]
97#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
98#[cfg_attr(feature = "charon_on_charon", charon::variants_suffix("Retag"))]
99pub enum WithRetag {
100    No,
101    Yes,
102}
103
104#[derive(Debug, Copy, Clone, PartialEq, Eq)]
105#[derive(Serialize, Deserialize)]
106#[cfg_attr(feature = "charon_on_charon", charon::variants_prefix("O"))]
107pub enum OverflowMode {
108    /// If this operation overflows, it panics. Only exists in debug mode, for instance in
109    /// `a + b`, and only if `--reconstruct-fallible-operations` is passed to Charon. Otherwise the
110    /// bound check will be explicit.
111    Panic,
112    /// If this operation overflows, it is UB; for instance in `core::num::unchecked_add`. This can
113    /// exists in safe code, but will always be preceded by a bounds check.
114    UB,
115    /// If this operation overflows, it wraps around for instance in `core::num::wrapping_add`,
116    /// or `a + b` in release mode.
117    Wrap,
118}
119
120/// Binary operations.
121#[derive(Debug, Copy, Clone, PartialEq, Eq)]
122#[derive(EnumAsInner)]
123#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
124#[cfg_attr(feature = "charon_on_charon", charon::rename("Binop"))]
125#[serde_state(stateless)]
126pub enum BinOp {
127    BitXor,
128    BitAnd,
129    BitOr,
130    Eq,
131    Lt,
132    Le,
133    Ne,
134    Ge,
135    Gt,
136    Add(OverflowMode),
137    Sub(OverflowMode),
138    Mul(OverflowMode),
139    Div(OverflowMode),
140    Rem(OverflowMode),
141    /// Fails if the shift is bigger than the bit-size of the type.
142    Shl(OverflowMode),
143    /// Fails if the shift is bigger than the bit-size of the type.
144    Shr(OverflowMode),
145    /// `BinOp(Cmp, a, b)` returns `-1u8` if `a < b`, `0u8` if `a == b`, and `1u8` if `a > b`.
146    Cmp,
147}
148
149/// Unary operation
150#[derive(Debug, Clone, PartialEq, Eq)]
151#[derive(EnumAsInner)]
152#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
153#[cfg_attr(feature = "charon_on_charon", charon::rename("Unop"))]
154pub enum UnOp {
155    Not,
156    /// This can overflow, for `-i::MIN`.
157    #[serde_state(stateless)]
158    Neg(OverflowMode),
159    /// Casts are rvalues in MIR, but we treat them as unops.
160    Cast(CastKind),
161}
162
163/// Cast the operand to a new type.
164#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
165#[derive(EnumAsInner)]
166#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
167#[cfg_attr(feature = "charon_on_charon", charon::variants_prefix("Cast"))]
168pub enum CastKind {
169    /// Conversion between scalar types.
170    /// See <https://doc.rust-lang.org/reference/expressions/operator-expr.html#r-expr.as.numeric>
171    Scalar(ScalarTy),
172    /// Convert a raw pointer or function pointer to a raw pointer.
173    RawPtr(Ty),
174    /// Converts a pointer or function pointer to an address, exposing its provenance.
175    /// The parameter is the destination integer type, which need not be `usize`.
176    /// See <https://doc.rust-lang.org/std/primitive.pointer.html#method.expose_provenance>.
177    PtrExposeProvenance(#[serde_state(stateless)] IntegerTy),
178    /// Converts an address to a pointer, which picks up exposed provenance.
179    /// See <https://doc.rust-lang.org/std/ptr/fn.with_exposed_provenance.html>.
180    PtrWithExposedProvenance(Ty),
181    /// Turn a function item into a function pointer, binding exactly its late-bound regions.
182    FnDefToFnPtr,
183    /// Convert a safe function pointer to an unsafe function pointer with the same signature.
184    FnPtrToUnsafe,
185    /// Convert a value to a supertype; this has no runtime effect.
186    Subtype(Ty),
187    /// [Unsize coercion](https://doc.rust-lang.org/std/ops/trait.CoerceUnsized.html). This is
188    /// either `[T; N]` -> `[T]` or `T: Trait` -> `dyn Trait` coercions, behind a pointer
189    /// (reference, `Box`, or other type that implements `CoerceUnsized`).
190    ///
191    /// The special case of `&[T; N]` -> `&[T]` coercion is caught by `UnOp::ArrayToSlice`.
192    Unsize(Ty, UnsizingMetadata, MetadataPath),
193    /// Reinterprets the bits of a value of one type as another type, i.e. exactly what
194    /// [`std::mem::transmute`] does.
195    Transmute(Ty),
196    /// Converts a receiver type with `dyn Trait<...>` to a concrete type `T`, used in vtable method shims.
197    /// Valid conversions are references, raw pointers, and (optionally) boxes:
198    /// - `&[mut] dyn Trait<...>` -> `&[mut] T`
199    /// - `*[mut] dyn Trait<...>` -> `*[mut] T`
200    /// - `Box<dyn Trait<...>>` -> `Box<T>` when no `--treat-box-as-builtin`
201    /// - smart-pointers, e.g. `Rc<dyn Trait<...>>` -> `Rc<T>` or
202    ///   `Pin<&mut dyn Trait<...>>` -> `Pin<&mut T>`
203    ///
204    /// For possible receivers, see: <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>.
205    ///
206    /// With `--index-to-function-calls`, this also converts `&[T]` to `&[T; N]` (or the mutable
207    /// equivalents) when an array subslice projection determines the length statically.
208    // FIXME(#855): smart-pointer receivers should rather be unpacked before the cast and re-packed after,
209    // so that the cast only ever applies to built-in pointers.
210    Concretize(Ty, MetadataPath),
211}
212
213/// Nullary operation
214#[derive(Debug, Clone, PartialEq, Eq)]
215#[derive(EnumAsInner)]
216#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
217#[cfg_attr(feature = "charon_on_charon", charon::rename("Nullop"))]
218pub enum NullOp {
219    /// Returns `true` during const evaluation, and `krate.runtime_checks.ub_checks` at runtime.
220    UbChecks,
221    OverflowChecks,
222    ContractChecks,
223}
224
225#[derive(Debug, Copy, Clone, PartialEq, Eq)]
226#[derive(Serialize, Deserialize, Drive, DriveMut, DriveTwo)]
227#[cfg_attr(feature = "charon_on_charon", charon::variants_prefix("B"))]
228pub enum BorrowKind {
229    Shared,
230    Mut,
231    /// See <https://doc.rust-lang.org/beta/nightly-rustc/rustc_middle/mir/enum.MutBorrowKind.html#variant.TwoPhaseBorrow>
232    /// and <https://rustc-dev-guide.rust-lang.org/borrow_check/two_phase_borrows.html>
233    TwoPhaseMut,
234    /// Those are typically introduced when using guards in matches, to make sure guards don't
235    /// change the variant of an enum value while me match over it.
236    ///
237    /// See <https://doc.rust-lang.org/beta/nightly-rustc/rustc_middle/mir/enum.FakeBorrowKind.html#variant.Shallow>.
238    Shallow,
239    /// Data must be immutable but not aliasable. In other words you can't mutate the data but you
240    /// can mutate *through it*, e.g. if it points to a `&mut T`. This is only used in closure
241    /// captures, e.g.
242    /// ```rust,ignore
243    /// let mut z = 3;
244    /// let x: &mut isize = &mut z;
245    /// let y = || *x += 5;
246    /// ```
247    /// Here the captured variable can't be `&mut &mut x` since the `x` binding is not mutable, yet
248    /// we must be able to mutate what it points to.
249    ///
250    /// See <https://doc.rust-lang.org/beta/nightly-rustc/rustc_middle/mir/enum.MutBorrowKind.html#variant.ClosureCapture>.
251    UniqueImmutable,
252}
253
254impl BorrowKind {
255    pub fn is_unique(&self) -> bool {
256        matches!(
257            self,
258            BorrowKind::Mut | BorrowKind::TwoPhaseMut | BorrowKind::UniqueImmutable,
259        )
260    }
261}
262
263/// For `Unsize` and `Concretize` casts, the fields to follow from the cast value to the built-in
264/// pointer whose metadata is changed, e.g. `[ptr, pointer]` for `Rc<T>`. Empty for built-in
265/// pointers.
266pub type MetadataPath = Vec<FieldId>;
267
268#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
269#[derive(EnumAsInner)]
270#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
271#[cfg_attr(feature = "charon_on_charon", charon::variants_prefix("Meta"))]
272pub enum UnsizingMetadata {
273    /// Cast from `[T; N]` to `[T]`.
274    Length(ConstantExpr),
275    /// Cast from a sized value to a `dyn Trait` value. The `TraitRef` is the proof of the `dyn
276    /// Trait` predicate; the constant expression is a reference to the vtable `static` value.
277    VTable(PolyTraitRef, ConstantExpr),
278    /// Cast from `dyn Trait` to `dyn OtherTrait`. The fields indicate how to retreive the vtable:
279    /// it's always either the same we already had, or the vtable for a (possibly nested) supertrait.
280    ///
281    /// Note that we cheat in one case: when upcasting to a marker trait (e.g. `dyn Trait -> dyn
282    /// Sized`), we keep the current vtable.
283    VTableUpcast(Vec<FieldId>),
284    Unknown,
285}
286
287/// An aggregated ADT.
288///
289/// Note that ADTs are desaggregated at some point in MIR. For instance, if
290/// we have in Rust:
291/// ```ignore
292///   let ls = Cons(hd, tl);
293/// ```
294///
295/// In MIR we have (yes, the discriminant update happens *at the end* for some
296/// reason):
297/// ```text
298///   (ls as Cons).0 = move hd;
299///   (ls as Cons).1 = move tl;
300///   discriminant(ls) = 0; // assuming `Cons` is the variant of index 0
301/// ```
302///
303/// Rem.: in the Aeneas semantics, both cases are handled (in case of desaggregated
304/// initialization, `ls` is initialized to `⊥`, then this `⊥` is expanded to
305/// `Cons (⊥, ⊥)` upon the first assignment, at which point we can initialize
306/// the field 0, etc.).
307#[derive(Debug, Clone, PartialEq, Eq)]
308#[derive(SerializeState, DeserializeState, Drive, DriveMut, DriveTwo)]
309#[cfg_attr(feature = "charon_on_charon", charon::variants_prefix("Aggregated"))]
310pub enum AggregateKind {
311    /// A struct, enum or union aggregate. The `VariantId`, if present, indicates this is an enum
312    /// and the aggregate uses that variant. The `FieldId`, if present, indicates this is a union
313    /// and the aggregate writes into that field. Otherwise this is a struct.
314    Adt(TypeDeclRef, Option<VariantId>, Option<FieldId>),
315    /// We don't put this with the ADT cas because this is the only built-in type
316    /// with aggregates, and it is a primitive type. In particular, it makes
317    /// sense to treat it differently because it has a variable number of fields.
318    /// The third field is the proof that the element type is `Sized`; it is absent with
319    /// `--hide-marker-traits`.
320    Array(Ty, ConstantExpr, Option<TraitRef>),
321    /// Construct a raw pointer from a pointer value, and its metadata (can be unit, if building
322    /// a thin pointer). The type is the type of the pointee.
323    RawPtr(Ty, RefKind),
324}
325
326impl Rvalue {
327    pub fn unit_value() -> Self {
328        Rvalue::Aggregate(
329            AggregateKind::Adt(
330                TypeDeclRef {
331                    id: TypeDeclId::UNIT,
332                    generics: Box::new(GenericArgs::empty()),
333                    builtin: Some(BuiltinAdt::Tuple),
334                },
335                None,
336                None,
337            ),
338            Vec::new(),
339        )
340    }
341}
342
343impl Operand {
344    pub fn mk_const_unit() -> Self {
345        Operand::Const(ConstantExpr::mk_unit())
346    }
347
348    pub fn ty(&self) -> &Ty {
349        match self {
350            Operand::Copy(place, _) | Operand::Read(place) | Operand::Move(place) => place.ty(),
351            Operand::Const(constant_expr) => constant_expr.ty(),
352        }
353    }
354}
355
356impl BorrowKind {
357    pub fn mutable(x: bool) -> Self {
358        if x { Self::Mut } else { Self::Shared }
359    }
360
361    pub fn is_mut(self) -> bool {
362        matches!(self, Self::Mut | Self::TwoPhaseMut | Self::UniqueImmutable)
363    }
364}
365
366impl BinOp {
367    pub fn with_overflow(&self, overflow: OverflowMode) -> Self {
368        match self {
369            BinOp::Add(_) => BinOp::Add(overflow),
370            BinOp::Sub(_) => BinOp::Sub(overflow),
371            BinOp::Mul(_) => BinOp::Mul(overflow),
372            BinOp::Div(_) => BinOp::Div(overflow),
373            BinOp::Rem(_) => BinOp::Rem(overflow),
374            BinOp::Shl(_) => BinOp::Shl(overflow),
375            BinOp::Shr(_) => BinOp::Shr(overflow),
376            _ => {
377                panic!(
378                    "Cannot set overflow mode for this binary operator: {:?}",
379                    self
380                );
381            }
382        }
383    }
384}
385
386impl UnOp {
387    pub fn with_overflow(&self, overflow: OverflowMode) -> Self {
388        match self {
389            UnOp::Neg(_) => UnOp::Neg(overflow),
390            _ => {
391                panic!(
392                    "Cannot set overflow mode for this unary operator: {:?}",
393                    self
394                );
395            }
396        }
397    }
398}
399
400impl From<BorrowKind> for RefKind {
401    fn from(value: BorrowKind) -> Self {
402        RefKind::mutable(value.is_mut())
403    }
404}
405
406impl From<RefKind> for BorrowKind {
407    fn from(value: RefKind) -> Self {
408        match value {
409            RefKind::Shared => BorrowKind::Shared,
410            RefKind::Mut => BorrowKind::Mut,
411        }
412    }
413}