{"slug": "an-overview-of-the-aeneas-rust-verification-toolchain", "title": "An Overview of the Aeneas Rust Verification Toolchain", "summary": "The Aeneas verification toolchain translates safe Rust programs into pure functional programs so proof engineers can verify functional properties in theorem provers such as Lean without reasoning about memory or aliasing, according to a new blog post by the tool's author. Aeneas performs its translation through a symbolic execution that implements a borrow-checker, which the author says has been formalized and can validate some programs rejected by Rust's current borrow-checker or Polonius. Microsoft is using Aeneas to verify implementations of its SymCrypt cryptographic library.", "body_md": "# An Overview of the Aeneas Rust Verification Toolchain\n\nI finally took some time to write a blog-post that presents Aeneas. This post is essentially the original ICFP 22 paper but with more examples and up-to-date explanations (the formalism has evolved quite a bit). The explanations I present here do not cover the latest features supported by the implementation such as nested (mutable) borrows, iterators, or dyn traits, but is nonetheless a quite comprehensive overview. Enjoy!\n\n## Introduction\n\n[Aeneas](https://github.com/AeneasVerif/aeneas) is a verification toolchain\nfor Rust programs. It leverages Rust’s ownership discipline to translate Rust\ncode into pure functional programs, eliminating memory reasoning entirely. The\nproof engineer can then verify the resulting code in a theorem prover such as\nLean, focusing on *functional* properties rather than on memory or aliasing.\n\nThe key observation is that a large class of safe Rust programs are functional in\nessence. References and borrows are an implementation device for performance and memory\nlayout; coupled with Rust’s linear ownership discipline, these programs admit a pure\nfunctional equivalent. Aeneas makes this equivalence concrete.\nThe key technical device that allows supporting the most subtle patterns,\nfunctions returning mutable borrows, is something I called *backward functions*.\n\nAeneas is also more than a compiler from Rust to whatever theorem prover you want: making the translation work required introducing novel semantics for safe Rust, while the translation itself is performed by means of a symbolic execution (or abstract interpretation, depending on your way of seeing things) for this semantics. Importantly, this symbolic execution implements a borrow-checker, a fact that we have formalized. This means that whenever you run Aeneas to translate a program you actually also borrow-check it. Interestingly, this borrow-checker can validate some programs that are not supported by the current borrow-checker or Polonius (see the examples in the blog post).\n\nAeneas is being used in practice! Microsoft is\nusing it to verify implementations of the\n[SymCrypt](https://github.com/microsoft/SymCrypt) cryptographic library\n([blog post](https://www.microsoft.com/en-us/research/blog/rewriting-symcrypt-in-rust-to-modernize-microsofts-cryptographic-library/)).\n\n## Aeneas and its Functional Translation, by Example\n\nBefore jumping into the various facets of our formalism, we keep an eye on the\nprize, and immediately showcase how Aeneas translates Rust programs to pure\nequivalents. In this section, and for the remainder of this post, we use\nLean syntax for our functional translation; it greatly resembles OCaml and\nother ML languages, and as such should be familiar to the reader. A brief note\nabout terminology: we refer to *regions*, emphasizing that a region encompasses a set of\nborrows and loans at a given program point. The Rust compiler and documentation, however,\nrefer to *lifetimes*, which conveys the idea of a syntactic bracket, and a specific\nimplementation technique to enforce soundness. In this post, whenever we talk about Rust\nspecifically, we use “lifetime”; whenever we emphasize our semantic view of ownership, we\nuse “region”.\n\n### Mutable Borrows, Functionally\n\nTo warm up, we consider an example that, albeit small, showcases\nmany of Rust’s\nfeatures, including its ownership mechanism. In the Rust program below,\n`incr` increments a reference, and `test_incr` acts as a\nrepresentative caller of the function.\n\n``` js\nfn incr(x: &mut i32) {\n  *x = *x + 1;\n}\n\nfn test_incr() {\n  let mut y = 0i32;\n  incr(&mut y);\n  assert!(y == 1);\n}\n```\n\nThe `incr` function operates by reference; that is, it receives the address of\na 32-bit signed integer `x`, as indicated by the `&` (reference) type. In\naddition, `incr` is allowed to modify the contents at address `x`, because\nthe reference is of the `mut` (mutable) kind, which permits memory\nmodification. Finally, the Rust type system enforces that mutable references\nhave a unique owner: the definition of `incr` type-checks, meaning that\nthe function not only *guarantees* it does not duplicate ownership of\n`x`, but also can *rely* on the fact that no one else owns `x`.\n\nIn `test_incr`, we allocate a mutable value (` let mut`) on the stack; upon\ncalling `incr`, we take a mutable reference (`&mut`) to `y`.\nStatically, `y` becomes unavailable as long as `&mut y` is active. In Rust\nparlance, `y` is *mutably borrowed* and its ownership has been\ntransferred to the mutable reference.\nTo type-check the call, the type-checker performs a lifetime analysis: the\n`incr` function has type `(&'a mut i32) -> ()`, and the `&mut y`\nborrow has type `&'b mut i32`; both `'a` and `'b` are lifetime variables.\n\nFor now, suffices to say that the type-checker ascertains that the lifetime\n`'b` of the mutable borrow satisfies the lifetime annotation `'a` in the\ntype of the callee, and deems the call valid.\nImmediately after the call, Rust *terminates* the\nregion `'b`, in effect *relinquishing* ownership of the mutable reference\n`&'b mut y` so as to make `y` usable again inside `test_incr`.\nThis in turn allows the\n`assert` to type-check, and thus the whole program.\nUndoubtedly, this is a very minimalistic program; yet, there are two properties\nof interest that we may want to establish already. The obvious one: the\nassertion always succeeds. More subtly, doing so requires us to prove an\nadditional property, namely that the addition at line 2 does not overflow.\n\nThe key insight of Aeneas is that even though the program manipulates\nreferences and borrows, none of this is informative when it comes to reasoning\nabout the program. More precisely: `x` and `y` are uniquely owned, meaning\nthat there are no stray aliases through which `x` or `y` may be modified;\nin other words, to understand what happens to `y`, it suffices to track what\nhappens to `&mut y`, and therefore to `x`.\nFeeding this program to Aeneas generates the following translation, where\n`+` is syntactic sugar for an Aeneas primitive that captures the semantics of\nerror-on-overflow in Rust.\n\n```\ndef incr (x : I32) : Result I32 :=\n  x + 1#i32 -- evaluates to `fail` in case of overflow\n\ndef test_incr : Result Unit := do\n  let y <- incr 0#i32 -- monadic bind\n  massert (y = 1#i32) -- monadic assert\n\n#assert (test_incr = ok ())\n```\n\nThis program is semantically equivalent to the original Rust code, but does not\nrely on the memory: we have leveraged the precise ownership discipline of Rust\nto generate a functional, pure version of the program. In hindsight, the usage\nof references in Rust was merely an implementation detail, which is why\n`incr` becomes a simple (possibly-overflowing) addition. Should the\ncall to `incr` succeed, its result is bound to `y`;\nthe `assert` simply becomes a boolean test that may generate a failure\nin the error monad.\n\nFor the purposes of unit-testing, we can use Lean’s normalize to evaluate that\n`test_incr` always succeeds, leveraging the fact that Aeneas produces an\nexecutable translation, not a logical encoding.\nIn the remainder of this section, we use `<-`, Lean’s bind\noperator in the error monad.\n\n### Returning a Mutable Borrow, and Backward Functions\n\nRust programs, however, rarely admit such immediate translations. To see why,\nconsider the following example, where the `choose` function returns a borrow,\nas indicated by its return type `&'a mut`.\n\n``` php\nfn choose<'a, T>(b: bool, x: &'a mut T, y: &'a mut T) -> &'a mut T {\n  if b { return x; } else { return y; }\n}\n\nfn test_choose() {\n  let mut x = 0i32;\n  let mut y = 0i32;\n  let z = choose(true, &mut x, &mut y);\n  *z = *z + 1;\n  assert!(*z == 1);\n  assert!(x == 1);\n  assert!(y == 0);\n}\n```\n\nThe `choose` function is polymorphic over type `T` and lifetime `'a`; the\nlifetime annotation captures the expectation that both `x` and `y` be in the\nsame region.\nAt call site, `x` and `y` are borrowed (line 7): they become unusable,\nand give birth to two intermediary values `&mut x` and `&mut y` of type\n`&'a mut i32`. The value returned by `choose` also lives in region\n`'a`, i.e., `z` also has type `&'a mut i32`.\nThe usage of `z` (lines 8-9) is valid because the region `'a` still\nexists; the Rust type-checker infers that region `'a` ought to be terminated\nafter line 9, which ends the borrows and therefore allows the caller to regain\nfull ownership of `x` and `y`, so that the `assert` s at lines 10-11 are\nwell-formed.\n\nAt first glance, it appears we can translate `choose` to an obvious\nconditional.\nBut if we reason about the semantics of `choose` from the\ncaller’s perspective, it turns out that the intuitive translation is not\nsufficient to capture what happens, e.g., the fact that `x` is updated while\n`y` is left unchanged, as we observe at lines 10 and 11.\nTo solve this issue we observe that at call site, `choose` is an opaque,\nseparate function, meaning the caller\ncannot reason about its precise definition — all that is\navailable is the function type. This type, however, contains precise region\ninformation, which one can use to summarize its behavior.\nWhen performing the function call, the ownership of `x` and\n`y` is transferred to region `'a` in exchange for `z`; symmetrically,\nwhen the lifetime\n`'a` terminates, `z` is relinquished to region\n`'a` in exchange for regaining ownership of `x` and `y`. The former\noperation flows *forward*; the latter flows *backward*. Using a\nseparation-logic oriented analogy: borrows and regions encode a magic wand that\nis introduced in a function call and eliminated when the corresponding region\nterminates.\n\nOur point is: both function call and region termination are semantically\nmeaningful. With the `choose` example,\nAeneas emits a *forward* function which itself returns a *backward* continuation.\nThe forward function is used to model the function call at line 7,\nwhile the backward continuation is used to propagate changes back into `x` and `y`\nwhen lifetime `'a` terminates.\n\n```\ndef choose {T : Type} (b : Bool) (x : T) (y : T) :\n  Result (T × (T → T × T)) :=\n  if b\n  then ok (x, fun z => (z, y))\n  else ok (y, fun z => (x, z))\n\ndef test_choose : Result Unit := do\n  let (z, choose_back) <- choose true 0#i32 0#i32\n  let z1 <- z + 1#i32\n  massert (z1 = 1#i32) -- monadic assert\n  let (x, y) := choose_back z1\n  massert (x = 1#i32)\n  massert (y = 0#i32)\n  ok ()\n\n#assert (test_choose = ok ())\n```\n\nThe call to `choose` returns a pair: the selected value, and a backward\ncontinuation `choose_back`. We bind the result of the addition\n(provided no overflow occurs) to `z1`; then, per the rules of Rust’s type-checker,\nregion `'a` terminates which compels us to call the backward continuation\n`choose_back`.\nThe intuitive effect of calling `choose_back` is as follows: we relinquish\n`z1`, which was in region `'a`; doing so, we propagate any updates\nthat may have been performed through `z` onto the\nvariables whose ownership was\ntransferred to `'a` in the first place, namely `x` and `y`.\nThis bidirectional approach is akin to lenses, except we propagate\nthe output back to possibly-many inputs; in this case, `z` is a view\nover either `x` or `y`, and the backward function reflects the update to\n`z` onto the original variables.\nThus, both variables are re-bound,\nbefore chaining the two asserts.\n\nThe key advantage of returning the backward function as a continuation is that\nit captures the choice made by `choose` (i.e., whether `b` was true or false)\nin a closure, so the caller does not need to pass back the original arguments.\n\nFrom the caller’s perspective, the computational content of `choose` is\nunknown; but the signature of `choose` reveals the effect it may have onto its\ninputs `x` and `y`, which in turns allows us to derive the type of the\nforward and backward functions from the signature of `choose` itself.\nThe result is a modular, functional\ntranslation that does not rely on any sort of cross-function inlining or\nwhole-program analysis.\nTo synthesize the backward continuation, it suffices to invert the direction\nof assignments; in one case, `z` flows to `x` and `y` remains\nunchanged; the other case is symmetrical.\n\n### Recursion and Data Structures\n\nIt might not be immediately obvious that this translation technique scales up\nbeyond toy examples; we now crank up the complexity and\nshow how Aeneas can handle a wide variety of idioms while still delivering on the\noriginal promise of a lightweight functional translation.\nOur next example is\n`list_nth_mut`, which allows taking a mutable reference to the *n*-th\nelement of a list, mutating it, and regaining ownership of the list.\n\n```\nenum List<T> {\n  Cons(T, Box<List<T>>),\n  Nil,\n}\n\nfn list_nth_mut<'a, T>(l: &'a mut List<T>, i: usize) -> &'a mut T {\n  match l {\n    Nil => { panic!() }\n    Cons(x, tl) => {\n      if i == 0 { x }\n      else { list_nth_mut(tl, i - 1) }\n    }\n  }\n}\n\nfn sum(l: & List<i32>) -> i32 {\n  match l {\n    Nil => { return 0; }\n    Cons (x, tl) => { return *x + sum(tl); }\n  }\n}\n\nfn test_nth() {\n  let mut l = Cons (1, Box::new(Cons (2, Box::new(Nil))));\n  let x = list_nth_mut(&mut l, 1);\n  *x = *x + 1;\n  assert!(sum(&l) == 4);\n}\n```\n\nThis example relies on several new concepts. Parametric data type declarations\nresemble those in any functional programming language such as OCaml\nor SML. The `Box` type denotes a heap-allocated, uniquely-owned piece of\ndata. Without the `Box` indirection, `List` would describe a type of\ninfinite size and would be rejected. Immutable (or shared) borrows\ndo not sport a\n`mut` keyword; they do not permit mutation, but the programmer may create\ninfinitely many of them. Only when all shared borrows have been relinquished\ndoes full ownership return to the borrowed value.\n\nThe complete translation is as follows:\n\n``` php\ninductive List (T : Type) :=\n| Cons : T -> List T -> List T\n| Nil : List T\n\ndef list_nth_mut {T : Type} (l : List T) (i : Usize) :\n  Result (T × (T -> List T)) :=\n  match l with\n  | Cons x tl =>\n    if i = 0#usize\n    then ok (x, fun x' => Cons x' tl)\n    else do\n      let i1 <- i - 1#usize\n      let (v, list_nth_mut_back) <- list_nth_mut tl i1\n      ok (v, fun v' => Cons x (list_nth_mut_back v'))\n  | Nil => fail\n\ndef sum (l : List I32) : Result I32 :=\n  match l with\n  | Cons x tl => do\n    let i <- sum tl\n    x + i\n  | Nil => ok 0#i32\n\ndef test_nth : Result Unit := do\n  let l := Cons 1 (Cons 2 Nil)\n  let (x, list_nth_mut_back) <- list_nth_mut l 1\n  let x1 <- x + 1#i32\n  let l1 := list_nth_mut_back x1\n  let i <- sum l1\n  massert (i = 4#i32)\n\n#assert (test_nth = ok ())\n```\n\nWe first focus on the caller’s point of view.\nContinuing with the lens analogy, we focus on (or “get”) the *n*-th element of the list via\na call to `list_nth_mut`; modify the element; then\nclose (or “put” back) the lens, and propagate the modification back to the\nlist via a call to `list_nth_mut_back`.\nThe backward continuation is of particular interest.\nIn the `Nil` case (i.e., when `i = 0`), it simply updates the list to replace the head (` x`) with its\nnew value (`x'`).\nIn the `Cons` case, it updates the tail of the list by using the backward continuation\nreturned by the recursive call,\nand reconstructs the complete list by consing the (unchanged) head value.\n\n## An Ownership-Centric Semantics for Rust\n\nBefore explaining the functional translation above, we must first present our input language and its operational semantics. We now present a series of short Rust snippets, and show in comments how our execution environments model the effect of each statement. The language we use is called LLBC (Low Level Borrow Calculus). It is essentially MIR but with a reconstructed control-flow and a bit of cleaning. In effect, it looks like Rust’s surface syntax, but where everything is explicit, in particular moves and copies.\n\n#### Mutable borrows\n\nAfter line 1, `x` points to `0`, which we write `x ↦ 0`. At line 2, `px` *mutably* borrows `x` (“MB” stands for “mutable borrow”). As we\nmentioned earlier, a mutable borrow grants exclusive ownership of a value, and\nrenders the borrowed value unusable for the duration of the borrow. We reflect this\nfact in our execution environment as follows: `x` is marked as\n“loaned-out” (“ML” stands for “mutable loan”), in a mutable fashion, and `px` is known to be a\nmutable borrow. Furthermore, ownership of the borrowed value now\nrests with `px`, so the value within the mutable borrow is 0. Finally, we\nneed to record that `px` is a borrow *of `x`*: we issue a fresh loan\nidentifier ℓ that ties `x` and `px` together.\nThe same operation is repeated at line 3. Value 0 is now held by `ppx`, and\n`px`, too, becomes “loaned out”.\n\n``` js\nlet mut x = 0;       // x ↦ 0\nlet mut px = &mut x; // x ↦ ML ℓ,   px ↦ MB ℓ 0\nlet ppx = &mut px;   // x ↦ ML ℓ,   px ↦ ML ℓ',     ppx ↦ MB ℓ' (MB ℓ 0)\n```\n\nOur environments thus precisely track ownership; doing so, they capture the aliasing\ngraph in an exact fashion. Another point about our style:\nthis representation allows us to adopt a *focused* view of the borrowed\nvalue (e.g., 0), solely\nthrough its owner (e.g., `ppx`), without worrying about following indirections\nto other variables.\nWe believe this\napproach is unique to our semantics; it has, in our experience, greatly\nsimplified our reasoning and in particular the functional translation.\n\nWe remark that our style\ndeparts from Stacked Borrows, where the modified value\nremains with `x`. We also note that our formalism cannot account for unsafe\nblocks; allowing unfettered aliasing would lead to potential cycles, which we\ncannot represent. This is an intentional design choice for us: we circumbscribe\nthe problem space in order to achieve an intuitive, natural semantics and a\nlightweight functional translation. Aeneas shines on non-unsafe Rust programs,\nand can be complemented by more advanced tools such as RustBelt for unsafe\nparts.\n\n#### Shared borrows\n\nShared borrows behave more like traditional pointers. Multiple shared borrows\nmay be created for the same value; each of them grants read-only access to the\nunderlying value.\nThe owner also retains a read-only access to the borrowed value;\nregaining full ownership requires\nterminating all of the borrows. In the example\nbelow, the value (0, 1) is borrowed in a shared fashion, at line 2. This time,\nthe value remains with `x`; but taking an immutable reference to\n`x` still requires book-keeping. We issue a new loan ℓ, and record that\n`px1` is now a shared borrow associated to loan ℓ; to understand which\nvalue `px1` points to, we simply look up in the environment who is the owner\nof ℓ, and read the associated value.\nRepeated shared borrows are permitted: at line 3,\nwe create a new shared borrow of `x`; as `x` is already borrowed we do not need to\nupdate its value and simply reuse the loan identifier ℓ.\nAt line 4, we copy the first component of `x`; remember that moves and copies are explicit\nin our language. Values that are loaned\nimmutably, like `x`, can still be read; in the resulting environment, `y` points to a copy of\nthe first component, and bears no relationship whatsoever to `x`.\nFinally, at line 5, we *reborrow* (through `px1`) the first component of\nthe pair only. First, to dereference `px1`, we perform a lookup and find that\n`x` owns ℓ. Then, we perform book-keeping and update the value loaned by\n`x`, so as to reflect that its first component has been loaned out, introducing a fresh\nloan identifier ℓ’ at the same time.\n\n``` js\nlet x = (0, 1);    // x ↦ (0, 1)\nlet px1 = &x;      // x ↦ SL ℓ (0,1),       px1 ↦ SB ℓ\nlet px2 = &x;      // x ↦ SL ℓ (0, 1),      px1 ↦ SB ℓ,   px2 ↦ SB ℓ\nlet y = copy x.0;  // x ↦ SL ℓ (0, 1),      px1 ↦ SB ℓ,   px2 ↦ SB ℓ,   y ↦ 0\nlet z = &(*px1.0); // x ↦ SL ℓ ((SL ℓ' 0), 1), px1 ↦…, px2 ↦ …, y ↦ 0, z ↦ SB ℓ'\n```\n\nNote that `px1` and `px2` share the *same* loan identifier ℓ: shared\nborrow identifiers are not unique. This is in contrast with mutable borrows, where\neach borrow has a unique loan identifier to enforce exclusive ownership.\nFor shared borrows, since no mutation is allowed, there is no need to distinguish\nbetween different borrows of the same value — they all grant the same read-only\naccess. As a consequence, ending a shared loan simply requires checking that there\nare no more live borrows referencing that loan.\n\nIn our presentation, shared borrows behave like pointers, and every one of them\nis statically accounted for via the loan identifier attached to the borrowed value.\nThe reader might find this design choice surprising: indeed, in Rust, shared\nborrows behave like immutable values and we ought to be able to treat them as\nsuch. Recall, however, that one of our key design goals is to give a\n*semantic* explanation of borrows; as such, our precise tracking of\nshared borrows allows us to know precisely when all aliases\nhave been relinquished, and full ownership of the borrowed value has been\nregained. This allows us to justify why, in the example below, the update to\n`x` is sound; without our exact alias tracking, we would have to trust the\nborrow checker, something we explicitly do not want to do.\n\n``` js\nlet mut x = 0;  // x ↦ 0\nlet px1 = &x;   // x ↦ SL ℓ 0,       px1 ↦ SB ℓ\nlet px2 = &x;   // x ↦ SL ℓ 0,       px1 ↦ SB ℓ,   px2 ↦ SB ℓ\n                // After ending the loan ℓ:\n                // x ↦ 0,   px1 ↦ ⊥,   px2 ↦ ⊥\nx = 1;          // x ↦ 1\n```\n\nFinally, we reiterate our remark that our formalism allows keeping track of the aliasing graph in a precise fashion; the discipline of Rust bans cycles, meaning that the aliasing graph is always a tree. This style of representation resembles Mezzo, where loan identifiers are akin to singleton types, and entries in the environment are akin to permissions.\n\n#### Rewriting an Old Value, a.k.a. Reborrowing\n\nWe now consider a particularly twisted example accepted by the Rust compiler. While the\ncomplexity seems at first gratuitous, it turns out that the pattern of borrowing\na dereference (i.e., `&mut (*px)`) is particularly common in Rust. The reason\nis subtle: in the post-desugaring MIR internal Rust representation, moves and\ncopies are explicit, meaning function calls of the form `f(move px)` abound.\nSuch function calls *consume* their argument, and render the\nuser-declared reference `px` unusable past the function call.\nTo offer a better user experience, Rust automatically “reborrows” the\ncontents pointed to by `px`, and rewrites the call into `f(move (&mut (*px)))` at desugaring-time.\nThus, only the intermediary value is “lost” to the function call;\nrelying on its lifetime analysis, the Rust compiler concludes that the\nuser-declared reference `px` remains valid past the function call, hence\nmaking the programmer’s life easier.\n\nAnother common pattern is to directly mutate a borrow, i.e., assign a fresh\nborrow into a variable `x` of type `&mut t` that was *itself*\ndeclared as `let mut`.\nCapturing the semantics of such an update must be done with great care, in order\nto preserve precise aliasing information.\n\nWe propose an example that combines both patterns; the fact that we make\n`px` reborrow itself is what makes the example “twisted”.\nRust accepts this\nprogram; we now explain with our semantics *why* it is sound.\nIn the example below, after line\n2, the environment offers no surprises. Justifying the write at line 3 requires\ncare. We borrow `*px`, which modifies `px` to point to `MB ℓ' 0`,\nand returns `ML ℓ'`; the value about to be overwritten is stored in a\nfresh variable `px_old`, and `ML ℓ'`\ngets written to `px`.\n\n``` js\nlet mut x = 0;       // x ↦ 0\nlet mut px = &mut x; // x ↦ ML ℓ,   px ↦ MB ℓ 0\npx = &mut (*px);     // x ↦ ML ℓ,   px_old ↦ MB ℓ (ML ℓ'),   px ↦ MB ℓ' 0\n                     // x ↦ ML ℓ,   px_old ↦ MB ℓ 0, px ↦⊥\nassert!(x==0);       // x ↦ 0, px_old ↦ ⊥, px ↦ ⊥\n```\n\nSaving the old value is crucial for line 4.\nFor the assertion, we need to regain full ownership of `x`. To do so,\nwe first terminate ℓ’.\nThis *reorganizes* the environment, with two consequences.\nFirst, `px` becomes unusable, which we write `px ↦ ⊥`. Second, `px_old`, which we had judiciously kept in the\nenvironment, becomes `MB ℓ 0`. We reorganize the environment again, to\nterminate ℓ; the effect is similar, and results in `x ↦ 0`, i.e., full ownership of `x`.\nThis example illustrates a key characteristic of our approach, which is that we\nreorganize borrows in a lazy fashion, and don’t terminate a borrow until we\nneed to get the borrowed value back.\n\n#### An Illegal Borrow\n\nWe offer an final example which leverages our reorganization rules;\nfurthermore, the example illustrates how our semantics reaches the same\nconclusion as `rustc`, though by different means, on a borrowing error.\nAt line 2, a borrow is introduced, which results in a fresh loan ℓ.\nTo make progress, we\nterminate borrow ℓ at line 3.\nLine 4 then type-checks, with a fresh borrow ℓ’. Then, we error\nout at line 5: `px₁` has been terminated, and we cannot dereference ⊥.\n\nThe Rust compiler proceeds differently, and implements an analysis which requires computing borrow constraints for an entire function body. The compiler notices that lifetime ℓ must go on until line 6 (because of the assert), which prevents a new borrow from being issued at line 4. Rust thus ascribes the error to an earlier location than we do, that is, line 4. We remark that the Rust behavior is semantically equivalent to ours; however, our lazy approach which terminates borrows only as needed has the advantage that evaluation can proceed in a purely forward fashion, without requiring a non-local analysis. This on-demand approach is similar to Stacked Borrows.\n\n``` js\nlet mut x = 0;    // x ↦ 0\nlet px1 = &mut x; // x ↦ ML ℓ,   px1 ↦ MB ℓ 0\n                  // x ↦ 0,   px1 ↦ ⊥\nlet px2 = &mut x; // aeneas: x ↦ ML ℓ',   px1 ↦ ⊥,    px2 ↦ MB ℓ' 0\n                  // rustc: error: cannot borrow `px1` as mutable more than once at a time\nassert!(*px1 == 0); // aeneas: error, attempt to deference unusable variable px1\n```\n\n#### Two-Phase Borrows\n\nWe finally review *two-phase* borrows, which are introduced by the Rust compiler\nat desugaring time. A two-phase borrow starts as a shared borrow in a\n“reservation phase”, and later gets activated into a full mutable borrow.\nReserved borrows enable a variety of very common idioms without resorting to\nmore advanced desugarings.\n\nBelow, we create a two-phase borrow at line 3. From the point of view of the\nlender, a two-phase borrow acts as a shared borrow; the value of `x`, which\nis already immutably borrowed, remains unchanged. However, `px2` maps to the\n*reserved* borrow `RB ℓ`.\nAt line 4, we evaluate the assertion as before.\nHowever, at line 5 we need to use the two-phase borrow to perform an in-place\nupdate. We thus reorganize the environment by ending the shared borrow ℓ\ncontained by `px1`. There now only remains a single borrow pointing to `x`,\nthe reserved borrow of `px2`, that we can promote to a mutable borrow. This\nallows us to evaluate the in-place update.\n\n``` js\nlet mut x = 0;          // x ↦ 0\nlet px1 = &x;           // x ↦ SL ℓ 0,       px1 ↦ SB ℓ\nlet px2 = &two-phase x; // x ↦ SL ℓ 0,       px1 ↦ SB ℓ,   px2 ↦ RB ℓ\nassert!(*px1 == 0);     // x ↦ SL ℓ 0,       px1 ↦ SB ℓ,   px2 ↦ RB ℓ\n                        // After ending the shared borrow of px1:\n                        // x ↦ SL ℓ 0,       px1 ↦ ⊥,      px2 ↦ RB ℓ\n                        // After promoting the reserved borrow of px2:\n                        // x ↦ ML ℓ,         px1 ↦ ⊥,      px2 ↦ MB ℓ 0\n*px2 = 1;               // x ↦ ML ℓ,         px1 ↦ ⊥,      px2 ↦ MB ℓ 1\n```\n\n## From Symbolic Semantics to Functional Code\n\nWe now explain how Aeneas, using the symbolic semantics, generates a pure translation\nof the original LLBC program. We show this through two detailed examples:\nfirst the translation of a *caller* (`call_choose`), then the translation\nof a *callee* (`choose`) which requires synthesizing a backward function.\n\nThe translation is carried out by performing a symbolic execution on the source program and synthesizing a functional AST in parallel. At each step, we show the symbolic environment alongside the progressively-built Lean translation.\n\nA key insight is that the synthesis rules are exclusively concerned with\n*symbolic values*; the actual variables from the source program (`x ↦ ...`)\nare mere bookkeeping devices and have no relevance to the translated program.\nSymbolic values σ, however, cannot be determined statically; they thus compute\nat run-time, and as such are let-bound in the target program.\n\n### Translation Example: `call_choose`\n\nAs a starting example, we consider the translation of the `call_choose` function\nbelow, presented in LLBC syntax with explicit writes and moves, along with a\nfully-explicit return variable `x_ret`.\n\n``` php\nfn call_choose(mut p : (u32, u32)) -> u32 {\n  let px = &mut p.0;                       // line 2\n  let py = &mut p.1;                       // line 3\n  let pz = choose(true, move px, move py); // line 4\n  *pz = *pz + 1;                           // line 5\n  x_ret = move p.0;                        // line 6\n  return;\n}\n```\n\nWe start the translation by initializing an environment where `p` maps to a\nsymbolic value σ₀. In parallel, we synthesize the function as an AST with a\nhole `[.]` to be progressively filled.\n\n**Environment:**\n\n```\np ↦ (σ₀ : (u32, u32))\n```\n\n**Synthesized code:**\n\n```\ndef call_choose (s0 : (U32 × U32)) :\n  Result U32 := do\n  [.]\n```\n\nAt line 2, accessing field 0 requires us to expand σ₀; doing so introduces a let-binding in the translation.\n\n**Environment:**\n\n```\np ↦ (σ₁ : u32, σ₂ : u32)\n```\n\n**Synthesized code:**\n\n```\ndef call_choose (s0 : (U32 × U32)) :\n  Result U32 := do\n  let (s1, s2) := s0\n  [.]\n```\n\nThe expansion allows us to evaluate the two mutable borrows on lines 2–3. Importantly, borrows and assignments just lead to bookkeeping in the environment: the synthesized translation is left unchanged.\n\n**Environment:**\n\n```\np  ↦ (ML ℓ₁, ML ℓ₂)\npx ↦ MB ℓ₁ (σ₁ : u32)\npy ↦ MB ℓ₂ (σ₂ : u32)\n```\n\n**Synthesized code:**\n\n```\ndef call_choose (s0 : (U32 × U32)) :\n  Result U32 := do\n  let (s1, s2) := s0\n  [.]\n```\n\nWe then reach the function call at line 4. To account for the call, we introduce\na region abstraction to account for `'a`, transfer ownership of the effective\narguments to the abstraction, then introduce a fresh mutably borrowed value\n`MB ℓ₃ (σ₃ : u32)` to account for the returned value stored in `pz`.\nWe also attach a *continuation* to the region abstraction A(α) that we\nwill use upon ending A(α). This continuation is simply the backward function\nof `choose`; it consumes the value retrieved upon ending ℓ₃ and produces\nthe values to give back to ℓ₁ and ℓ₂.\n\nIn parallel, we introduce a call to `choose` in the synthesized translation. The\nborrow types are translated to the identity; the input arguments are thus simply\n`s1` and `s2`, while `choose` outputs `s3`, together with the backward\nfunction `back`.\n\n**Environment:**\n\n```\np  ↦ (ML ℓ₁, ML ℓ₂)\npx ↦ ⊥\npy ↦ ⊥\n\nA(α) {\n    _,\n    MB ℓ₁ (σ₁ : u32),\n    MB ℓ₂ (σ₂ : u32),\n    ML ℓ₃,\n} ⟦ (ℓ₁, ℓ₂): λ ℓ₃ ⇒ back ℓ₃ ⟧\n\npz ↦ MB ℓ₃ (σ₃ : u32)\n```\n\n**Synthesized code:**\n\n```\ndef call_choose (s0 : (U32 × U32)) :\n  Result U32 := do\n  let (s1, s2) := s0\n  let (s3, back) ← choose true s1 s2\n  [.]\n```\n\nWe can now symbolically execute the increment, which merely introduces an addition and generates a fresh variable σ₄:\n\n**Environment:**\n\n```\np  ↦ (ML ℓ₁, ML ℓ₂)\npx ↦ ⊥\npy ↦ ⊥\n\nA(α) {\n    _,\n    MB ℓ₁ (σ₁ : u32),\n    MB ℓ₂ (σ₂ : u32),\n    ML ℓ₃,\n} ⟦ (ℓ₁, ℓ₂): λ ℓ₃ ⇒ back ℓ₃ ⟧\n\npz ↦ MB ℓ₃ (σ₄ : u32)\n```\n\n**Synthesized code:**\n\n```\ndef call_choose (s0 : (U32 × U32)) :\n  Result U32 := do\n  let (s1, s2) := s0\n  let (s3, back) ← choose true s1 s2\n  let s4 ← s3 + 1\n  [.]\n```\n\nFinally, the move at line 6 requires retrieving the ownership of `p.0`. Doing\nso requires ending the region abstraction A(α) (introduced by the call to\n`choose`), which in turn requires ending the loan inside the abstraction.\nAccordingly, we first end ℓ₃ which leads to the environment below.\nImportantly, we update the continuation associated with A(α) to account for\nthe fact that it consumes the value given back upon ending ℓ₃.\nEnding a loan (or a borrow, depending on the point of view) leaves the\nsynthesized code unchanged.\n\n**Environment:**\n\n```\np  ↦ (ML ℓ₁, ML ℓ₂)\npx ↦ ⊥\npy ↦ ⊥\n\nA(α) {\n    _,\n    MB ℓ₁ (σ₁ : u32),\n    MB ℓ₂ (σ₂ : u32),\n    (σ₄ : u32)\n} ⟦ (ℓ₁, ℓ₂): back σ₄ ⟧\n\npz ↦ ⊥\n```\n\nThen, we actually end the region abstraction A(α) by moving back the borrows\nℓ₁ and ℓ₂ in the environment, with fresh symbolic values σ₅ and σ₆. Those\nare the values given back *by* `choose`. On the side of the translated code,\nwe materialize the end of A(α) by introducing a call to its continuation. This\ncontinuation consumes the value given back to the loan ℓ₃ upon ending it (that\nis, σ₄); it also outputs the values given back to ℓ₁ and ℓ₂ (that is, the\npair (σ₅, σ₆)).\n\n**Environment:**\n\n```\np  ↦ (ML ℓ₁, ML ℓ₂)\npx ↦ ⊥\npy ↦ ⊥\n_  ↦ MB ℓ₁ (σ₅ : u32)\n_  ↦ MB ℓ₂ (σ₆ : u32)\npz ↦ ⊥\n```\n\n**Synthesized code:**\n\n```\ndef call_choose (s0 : (U32 × U32)) :\n  Result U32 := do\n  let (s1, s2) := s0\n  let (s3, back) ← choose true s1 s2\n  let s4 ← s3 + 1\n  let (s5, s6) ← back s4\n  [.]\n```\n\nWe can finally end the borrow ℓ₁ and evaluate the `return`, which ends the\ntranslation. As we save meta-information about the assignments to generate\nsuitable names for the variables, Aeneas actually generates the following\nfunction:\n\n```\ndef call_choose (p : (U32 × U32)) : Result U32 := do\n  let (px, py) := p\n  let (pz, back) ← choose true px py\n  let pz0 ← pz + 1\n  let (px0, _) ← back pz0\n  ok px0\n```\n\n### Translation Example: `choose`\n\nWe now proceed with the synthesis of `choose`, which requires synthesizing a\nbackward function. We recall its definition; like in the previous example,\nwe make all the statements explicit.\n\n``` php\nfn choose<'a, T>(b : bool, x : &'a mut T, y : &'a mut T) -> &'a mut T {\n  if b {\n    x_ret = move x;\n    return;\n  }\n  else {\n    x_ret = move y;\n    return;\n  }\n}\n```\n\nUnlike `call_choose`, the `choose` function takes borrows as input parameters.\nWe thus need to track their provenance, from the point of view of the callee.\nAs a consequence, we initialize the environment by introducing an abstraction\ncontaining loans so as to model the values owned by the caller and *loaned* to\nthe function for as long as α lives.\nThis is the dual of the caller’s point of view: the abstraction contains\ntwo mutable borrows ℓ⁰ₓ and ℓ⁰ᵧ, whose loans are not in the environment;\nthey stand for the values we consumed upon calling the function.\nThe abstraction also contains two mutable loans ℓₓ and ℓᵧ, associated to the\nborrows of the input values `x` and `y`.\nImportantly, we attach a continuation that we will use for the synthesis, and\nwhich is currently the identity; intuitively, this means that ℓ⁰ₓ and ℓₓ are\nactually the same (and similarly for ℓ⁰ᵧ and ℓᵧ). The link between borrows\nand loans inside the input region abstraction will become more complex as we\nproceed through the synthesis.\n\n**Environment:**\n\n```\nA_input(α) {\n    MB ℓ⁰ₓ (_),\n    MB ℓ⁰ᵧ (_),\n    ML ℓₓ,\n    ML ℓᵧ,\n} ⟦ (ℓ⁰ₓ, ℓ⁰ᵧ): λ ℓₓ ℓᵧ ⇒ (ℓₓ, ℓᵧ) ⟧\n\nb ↦ σ_b\nx ↦ MB ℓₓ (σₓ : T)\ny ↦ MB ℓᵧ (σᵧ : T)\n```\n\n**Synthesized code:**\n\n```\ndef choose\n  {T : Type} (b : Bool) (x y : T) :\n  Result (T × (T → (T × T))) := do\n  [.]\n```\n\nWe then evaluate the `if`, branching over the symbolic value σ_b.\nWe duplicate the environment and substitute σ_b with `true` for the first\nbranch, and `false` for the second branch.\nBelow, we show the environment for the first branch of the `if`:\n\n**Environment (first branch):**\n\n```\nA_input(α) {\n    MB ℓ⁰ₓ (_),\n    MB ℓ⁰ᵧ (_),\n    ML ℓₓ,\n    ML ℓᵧ,\n} ⟦ (ℓ⁰ₓ, ℓ⁰ᵧ): λ ℓₓ ℓᵧ ⇒ (ℓₓ, ℓᵧ) ⟧\n\nb ↦ true\nx ↦ MB ℓₓ (σₓ : T)\ny ↦ MB ℓᵧ (σᵧ : T)\n```\n\n**Synthesized code:**\n\n```\ndef choose\n  {T : Type} (b : Bool) (x y : T) :\n  Result (T × (T → (T × T))) := do\n  if b then [.]\n  else [.]\n```\n\nWe proceed with the evaluation of the first branch. Upon reaching `x_ret = move x`,\nwe move `x` to the return variable; the synthesized code is left unchanged.\n\n**Environment:**\n\n```\nA_input(α) {\n    MB ℓ⁰ₓ (_),\n    MB ℓ⁰ᵧ (_),\n    ML ℓₓ,\n    ML ℓᵧ,\n} ⟦ (ℓ⁰ₓ, ℓ⁰ᵧ): λ ℓₓ ℓᵧ ⇒ (ℓₓ, ℓᵧ) ⟧\n\nb     ↦ true\nx     ↦ ⊥\ny     ↦ MB ℓᵧ (σᵧ : T)\nx_ret ↦ MB ℓₓ (σₓ : T)\n```\n\nWe then reach the `return`. This is the crucial part of the translation. We\nneed to transform the environment so that it matches a target environment given\nby the signature of `choose`. In the process, we will introduce and merge\nregion abstractions, thus progressively synthesizing the backward function for\nthe first branch of the `if`.\n\nWe first move the values of `b` and `y` to anonymous values, and eliminate the\nvalue of `b` as it doesn’t contain any borrows; this has no effect on the\nsynthesis. We then transform the borrow moved from `y` into a region\nabstraction A₀. This region abstraction has no inputs, as it doesn’t contain\nmutable loans, and a single output, the value to give back for the mutable\nborrow ℓᵧ; we thus attach a continuation stating that upon ending A₀ we\nretrieve a value for ℓᵧ, which is actually σᵧ.\n\n**Environment:**\n\n```\nA_input(α) {\n    MB ℓ⁰ₓ (_),\n    MB ℓ⁰ᵧ (_),\n    ML ℓₓ,\n    ML ℓᵧ,\n} ⟦ (ℓ⁰ₓ, ℓ⁰ᵧ): λ ℓₓ ℓᵧ ⇒ (ℓₓ, ℓᵧ) ⟧\n\nb     ↦ ⊥\nx     ↦ ⊥\ny     ↦ ⊥\nx_ret ↦ MB ℓₓ (σₓ : T)\n\nA₀ {\n    MB ℓᵧ (_)\n} ⟦ ℓᵧ: σᵧ ⟧\n```\n\nWe perform one last step by merging A_input(α) and A₀ together. Merging the content of region abstractions is done as before; in particular the borrow and the loan for ℓᵧ cancel out. Merging two region abstractions also requires composing their continuations. Importantly, the fact that a borrow and a loan cancel out is mirrored by the fact that the continuation of A_input(α) consumes a borrow (ℓᵧ) which is actually an output of A₀. The resulting continuation of A_input(α) thus only has one input, the value consumed upon ending ℓₓ.\n\nThis yields an environment which matches our target environment: `x_ret` maps\nto a valid borrow, all the other local variables map to ⊥, and we have a\nsingle region abstraction for α which acts as an interface between the caller\nand the callee. We can thus end the translation of the first branch: the\nreturned value is the value inside `x_ret` (i.e., σₓ) while the backward\nfunction is given by the continuation attached to A_input(α).\n\n**Environment:**\n\n```\nA_input(α) {\n    MB ℓ⁰ₓ (_),\n    MB ℓ⁰ᵧ (_),\n    ML ℓₓ,\n} ⟦ (ℓ⁰ₓ, ℓ⁰ᵧ): λ ℓₓ ⇒ (ℓₓ, σᵧ) ⟧\n\nb     ↦ ⊥\nx     ↦ ⊥\ny     ↦ ⊥\nx_ret ↦ MB ℓₓ (σₓ : T)\n```\n\n**Synthesized code:**\n\n```\ndef choose\n  {T : Type} (b : Bool) (x y : T) :\n  Result (T × (T → (T × T))) := do\n  if b then ok (x, fun x0 => (x0, y))\n  else [.]\n```\n\nThe translation of the second branch is similar; we omit it.\n\n## Soundness\n\nWe claimed that a symbolic interpreter for LLBC implements a borrow-checker for Rust; we now summarize the formal argument that substantiates this claim. The full details are in the ICFP 2024 paper and my thesis manuscript.\n\nThe soundness of LLBC’s symbolic semantics (LLBCS) is predicated on the LLBC model being a sound foundation. LLBC has several unusual features, such as attaching values to pointers rather than to the underlying memory location, or not relying on an explicit heap; it therefore requires a formal argument to establish that this is an acceptable way to model Rust programs. We remark that this question is orthogonal to the RustBelt line of work: RustBelt establishes the soundness of Rust’s type system with regards to λ_Rust, whose classic, unsurprising semantics does not warrant scrutiny. Clarifying the link between LLBC and a standard heap-and-addresses model is not just a matter of theory: once the Rust compiler emits LLVM bitcode, the heap and addresses become real.\n\nWe address this question in two steps:\n\n1. \nWe introduce PL, for “pointer language”, which uses a traditional, explicit heap inspired by CompCert’s C memory model, and show that it refines LLBC. This establishes that a low-level model (where values live at a given address) refines the Rust model given by LLBC (where borrows hold the value they are borrowing).\n2. \nWe prove that LLBC itself refines the symbolic version of LLBC (LLBCS). Combined with the previous result, this allows us to precisely state why LLBCS is a borrow-checker for LLBC: if an LLBCS execution succeeds, then any corresponding low-level PL execution is safe for all inputs.\n\nMore precisely, a program which is successfully evaluated following the symbolic\nsemantics is *memory safe*, and its evaluation following the semantics of LLBC\nis in *bisimulation* with an evaluation using the heap-based PL semantics.\n\nTo conduct these proofs of refinement, we introduce a novel proof technique that\nrelies on the fact that our languages operate over the same grammar of\nexpressions, but give it different *meanings*, or *views*. Rather than go\nfull-throttle with a standard compilation-style proof of simulation, we reason\nmodularly over local or pointwise transformations that rewrite one piece of\nstate to another — proofs over those elementary transformations are much easier.\nWe then show that two states that are related by the transitive closure of these\nelementary transformations continue to relate throughout their execution,\nultimately giving a proof of refinement.\n\nWe note that the functional translation is currently trusted: its correctness is not yet formally established, and is left as future work.\n\nFinally, there is an ongoing effort to mechanize these proofs, which are currently pen-and-paper. The goal is to obtain a machine-checked formalization of the soundness of LLBCS as a borrow-checker.\n\n## Beyond the Rust Borrow-Checker\n\nBecause our approach to borrow-checking is semantic rather than syntactic, Aeneas can actually borrow-check (and translate) programs which are not accepted by Rust’s current borrow checker.\n\n### A Limitation of Rust’s Borrow-Checker\n\nIn the process of testing Aeneas on B-epsilon trees, we bumped into a limitation\nof the current Rust borrow-checking algorithm. The `get_suffix_at_x` function\nbelow looks for an element in a list and returns a mutable borrow to the suffix\nstarting at that element. The current Rust borrow-checker is too coarse to\nnotice that the `Cons` branch is valid. More specifically, it considers that the\nreborrows performed through `hd` and `tl` should last until the end of the\nlexical scope, that is, until the end of the `Cons` branch.\n\nInstead, one may notice that it is possible to end those borrows earlier, after\nevaluating the conditional, in order to retrieve full ownership of the value\nborrowed by `ls` in the first branch of the `if`, and make the example\nborrow-check. The ongoing replacement of the borrow-checker in Rust, named\nPolonius, implements a more refined lifetime analysis and accepts this program.\n\nMore interestingly, our semantic approach of borrows makes this program borrow-check without issues; since our discipline is based on symbolic execution and a semantic approach to loans, we accept the example without troubles, and are resilient to further syntactic tweaks of the program.\n\n``` php\nfn get_suffix_at_x<'a>(ls: &'a mut List<u32>, x: u32) -> &'a mut List<u32> {\n  match ls {\n    Nil => { ls }\n    Cons(hd, tl) => { // error: first mutable borrow occurs here\n      if *hd == x { ls // second mutable borrow occurs here\n      } else { get_suffix_at_x(tl, x) } } } }\n```\n\n### Precise Reborrows\n\nBecause of the way we handle reborrows, there are actually cases of programs deemed invalid even by Polonius, but supported by Aeneas.\n\nIn the example below, we first create a shared borrow that we store in `pp`,\nthen a reborrow of a subvalue borrowed by `pp` that we store in `px`. Upon\nevaluating the assignment `p.1 = 2`, `px` simply maps to a shared borrow of the\nfirst component of `p`. Importantly, even though `px` reborrows part of `pp`,\nthere are no links between `px` and `pp`: our semantics does not track the\nhierarchy between borrows and their subsequent reborrows. In other words,\n`let px = &(*pp.0)` is equivalent to `let px = &p.0`, where we borrow directly\nfrom `p` without resorting to `pp`. This implies that, upon ending the borrow\nℓ_p stored in `pp` at the assignment, we do not need to end ℓ_x stored in `px`,\nwhich in turn allows us to legally evaluate the assertion.\n\n``` js\nlet mut p = (0, 1);\nlet pp = &p;\n// p  ↦ SL ℓ_p (0, 1)\n// pp ↦ SB ℓ_p\nlet px = &(*pp.0);\n// p  ↦ SL ℓ_p (SL ℓ_x 0, 1)\n// pp ↦ SB ℓ_p\n// px ↦ SB ℓ_x\np.1 = 2;\n// p  ↦ (SL ℓ_x 0, 2)\n// pp ↦ ⊥\n// px ↦ SB ℓ_x\nassert!(*px == 0);\n```\n\nWhen we attempt to borrow-check this program (with Polonius or the current\nimplementation of the borrow checker), the Rust borrow checker considers that\n`px` reborrows `pp`, and thus needs to end before `pp` ends.\n\nThe code snippet below illustrates a similar example with mutable borrows.\nWe create a borrow `px1` of (the value of) `x`, then reborrow this value\nthrough `px2`. We then update `px1` to borrow `y`. At this point, `px2` still\nborrows `x`. The important point to notice is that upon performing this update,\nwe remember the old value of `px1` in an anonymous variable to not lose\ninformation about the borrow graph. Similarly to the previous example with\nshared borrows, the resulting environment doesn’t track the fact that `px2` was\ncreated by reborrowing the value initially borrowed by `px1`: there are no links\nbetween those two variables. Consequently, upon ending borrow ℓ_y (stored in\n`px1`) to access `y`, we don’t need to end ℓ₂ (stored in `px2`). This in\nreturn allows us to legally dereference `px2` at the end.\n\n``` js\nlet mut x = 0;\nlet mut px1 = &mut x;\nlet px2 = &mut (*px1); // Reborrow: px2 now borrows (the value of) x\n// x   ↦ ML ℓ₁\n// px1 ↦ MB ℓ₁ (ML ℓ₂)\n// px2 ↦ MB ℓ₂ 0\nlet mut y = 1;\npx1 = &mut y; // Update px1 to borrow y instead of x\n// x   ↦ ML ℓ₁\n// _   ↦ MB ℓ₁ (ML ℓ₂)\n// px2 ↦ MB ℓ₂ 0\n// y   ↦ ML ℓ_y\n// px1 ↦ MB ℓ_y 1\nassert!(*px1 == 1);\nassert!(*px2 == 0);\nassert!(y == 1); // End the borrow of y through px1 (shouldn't impact px2!)\n// x   ↦ ML ℓ₁\n// _   ↦ MB ℓ₁ (ML ℓ₂)\n// px2 ↦ MB ℓ₂ 0\n// y   ↦ 1\n// px1 ↦ ⊥\nassert!(*px2 == 0); // Considered invalid by rustc, but accepted by Aeneas\n```\n\nThe two examples above exemplify cases where both the Rust borrow checker and Polonius deem a program as invalid, while Aeneas accepts it. We do not claim that this is a strong limitation of the Rust borrow checker: these use cases seem quite anecdotal and are probably useless in practice. However, we believe the ability of Aeneas to precisely capture the behavior of such use cases supports our claim that our semantics really captures the essence of the borrow mechanism.\n\nMore examples of programs rejected by the Rust compiler but accepted by Aeneas\ncan be found in the\n[test suite](https://github.com/AeneasVerif/aeneas/blob/main/tests/src/rust-borrow-check-issues.rs).\n\n## Verifying Rust Programs with Aeneas\n\nAeneas is being used in practice to verify real-world Rust code. In particular,\nMicrosoft is using Aeneas to verify implementations of the\n[SymCrypt](https://github.com/microsoft/SymCrypt) cryptographic library, as\ndescribed in their\n[blog post](https://www.microsoft.com/en-us/research/blog/rewriting-symcrypt-in-rust-to-modernize-microsofts-cryptographic-library/).\nWe now showcase the verification workflow through a few examples.\n\n### A Simple Arithmetic Example\n\nConsider `mul2_add1`, which Aeneas translates as follows:\n\n``` php\npub fn mul2_add1(x: u32) -> u32 {\n    (x + x) + 1\n}\njs\ndef mul2_add1 (x : U32) : Result U32 := do\n  let x1 ← x + x\n  let x2 ← x1 + 1#u32\n  ok x2\n```\n\nLe us show how to prove that `mul2_add1` evaluates to `2 * x + 1` provided there is no overflow.\nWe write specifications in the Hoare-logic style: `mul2_add1 x ⦃ y => y.val = 2 * x.val + (1 : Nat) ⦄`\nbelow means that `mul2_add1 x` successfully evaluates to some value `y` (in particular, it doesn’t panic)\nthat satisfies `y.val = 2 * x.val + 1` (`x.val` means `x` seen as an unbounded mathematical integer).\n\n```\ntheorem mul2_add1_spec (x : U32) (h : 2 * x.val + 1 ≤ U32.max) :\n  mul2_add1 x ⦃ y => y.val = 2 * x.val + 1 ⦄ := by\n  unfold mul2_add1\n  progress as ⟨ i ⟩\n  progress as ⟨ i' ⟩\n  scalar_tac\n```\n\nInitially, Lean shows us the following goal to be proven:\n\n``` js\nx : U32\nh : 2 * x.val + 1 ≤ U32.max\n⊢ mul2_add1 x ⦃ y => y.val = 2 * x.val + 1 ⦄\n```\n\nProving that this holds looks a lot like a debugging session: the first thing we need to do\nis dive into the body of `unfold mul2_add1`. We can do so with the `unfold` tactic (“tactic” is the\nname of the instructions that are used to guide the proofs), revealing:\n\n``` js\nx : U32\nh : 2 * x.val + 1 ≤ U32.max\n⊢ (do\n    let x1 ← x + x\n    let x2 ← x1 + 1#u32\n    ok x2) ⦃\n  y => y.val = 2 * x.val + 1 ⦄\n```\n\nWe now need to step through the function body and provide a dedicated tactic, `progress`.\nThe `progress` tactic looks at the first monadic operation in the goal, finds a\nmatching specification and applies it, introducing the result variable. The\n`as ⟨ i ⟩` clause names it.\nThe first `progress as ⟨ i ⟩` processes `x + x`, proving on the fly that there is no overflow\n(we have `x.val + x.val ≤ U32.max`) and updating the context accordingly:\n\n```\nx : U32\nh : 2 * x.val + 1 ≤ U32.max\ni : U32\n_ : i.val = x.val + x.val\n⊢ (do\n    let x2 ← i + 1#u32\n    ok x2) ⦃\n  y => y.val = 2 * x.val + 1 ⦄\n```\n\nThe second `progress as ⟨ i' ⟩` removes the second addition, leaving a pure arithmetic goal:\n\n```\ni : U32\n_ : i.val = x.val + x.val\ni' : U32\n_ : i'.val = i.val + 1\n⊢ i'.val = 2 * x.val + 1\n```\n\nThis goal can trivially be solved by using an arithmetic solver (`scalar_tac` in our case).\n\n### Using Registered Theorems\n\nConsider a caller of `mul2_add1`:\n\n``` php\npub fn mul2_add1_add(x: u32, y: u32) -> u32 {\n    mul2_add1(x) + y\n}\njs\ndef use_mul2_add1 (x : U32) (y : U32) : Result U32 := do\n  let x1 ← mul2_add1 x\n  x1 + y\n```\n\nWhen doing the proof, we want to reuse the specification we just proved for `mul2_add1`.\nWe can do so by explicitly instructing `progress` to use `mul2_add1_spec` through the\n`with` keyword: `progress with mul2_add1_spec`. Even better, if we mark `mul2_add1_spec`\nwith the `@[progress]` attribute, `progress` can automatically look it up when encountering\n`mul2_add1`. This looks like this:\n\n```\n@[progress]\ntheorem mul2_add1_spec (x : U32) (h : 2 * x.val + 1 ≤ U32.max) :\n  mul2_add1 x ⦃ y => y.val = 2 * x.val + 1 ⦄ := by\n  ...\n\ntheorem use_mul2_add1_spec (x : U32) (y : U32)\n  (h : 2 * x.val + 1 + y.val ≤ U32.max) :\n  use_mul2_add1 x y ⦃ z => z.val = 2 * x.val + (1 : Nat) + y.val ⦄ := by\n  unfold use_mul2_add1\n  progress as ⟨ i ⟩    -- automatically uses mul2_add1_spec\n  progress as ⟨ i' ⟩\n  scalar_tac\n```\n\n### Constant-Time Modular Addition\n\nLet’s now look at a real example.\n\nCryptographic code often requires constant-time implementations to prevent side-channel attacks: if the execution time of a cryptographic operation depends on the value of a secret key, an attacker can measure that time across many invocations and statistically recover the key. For this reason, cryptographic implementations must avoid branches and data-dependent operations that would cause the execution time to vary depending on the value of their secret inputs.\n\nThe following example appears in the SymCrypt implementation of ML-KEM, where we\nneed to do operations modulo prime number 3329.\nIn particular,  given `a` and `b` two numbers smaller than (the prime number) 3329,\nthe following function computes `(a + b) % 3329`.\nIt cannot use `%` — the division and conditional branch would produce\nvariable-time code. Instead, the implementation uses a branchless trick based\non underflow and bitmasking:\n\n``` php\nfn mod_add(a: u32, b: u32) -> u32 {\n    assert!(a < 3329);\n    assert!(b < 3329);\n    let sum = a + b;                  // 0 <= a + b <= 2 * 3328\n    let res = sum.wrapping_sub(3329);\n    let mask = res >> 16;             // mask = 0xffff if a + b < 3329, 0 otherwise\n    let q = 3329 & mask;              // q = 3329 if a + b < 3329, 0 otherwise\n    res.wrapping_add(q)\n}\n```\n\nBecause of properties of the modulo, either `a + b` is smaller than 3329, in which\ncase `(a + b) % 3329 = a + b`, or it is greater, in which case we have:\n`(a + b) % 3329 = a + b - 3329`.\nThis means that computing the modulo simply requires conditionally subtracting 3329.\nSame as with the modulo operation, we can not branch on `a + b < 3329`, as it would \nlead to non-constant time code revealing information about `a + b` (the branches of the\n`if then else` would not require the same number of instructions to execute, not even\nmentioning the problem of speculative execution).\nThe trick is to always subtract 3329, then use the result to conditionally add 3329 back\nin case we didn’t have to do the subtraction in the first place.\nThis works because in case the subtraction was not needed (i.e., `a + b < 3329`)\n`wrapping_sub` underflows: `res` wraps to a large value\nwhose upper bits are set, so the right shift yields `0xffff`. Then\n`q = 3329 & 0xffff = 3329`, and adding it back wraps around to `sum`.\nIn the other case (`a + b < 3329`), the shift gives a mask equal to 0, meaning `wrapping_add` adds 0.\nIn both cases the result is `(a + b) % 3329`, without any branch.\n\nAeneas translates this to:\n\n```\ndef mod_add (a : Std.U32) (b : Std.U32) : Result Std.U32 := do\n  massert (a < 3329#u32)\n  massert (b < 3329#u32)\n  let sum ← a + b\n  let res ← lift (core.num.U32.wrapping_sub sum 3329#u32)\n  let mask ← res >>> 16#i32\n  let q ← lift (3329#u32 &&& mask)\n  ok (core.num.U32.wrapping_add res q)\n```\n\nThe correctness proof is:\n\n```\ntheorem mod_add.spec (x y : U32) (h : x.val < 3329 ∧ y.val < 3329) :\n  mod_add x y ⦃ z => z.val = (x.val + y.val) % 3329 ⦄ := by\n  unfold mod_add\n  progress*\n  bv_tac 32\n```\n\nRather than calling `progress` step by step, `progress*` applies it repeatedly\nuntil no monadic operations remain, leaving a goal containing arithmetic operations\nand bit-vector operations. We provide a set of tactics and solvers to discharge\nthe various proof obligations encountered when verifying such code; in the present\ncase, it suffices to call `bv_tac`,\na bitvector decision tactic that handles the remaining bit-level reasoning.\n\nOne last remark: when developing proofs interactively, one often wants to go fast by means\nof, e.g., `progress*`, but also have the possibility of diving into the details of the proof.\nFor this reason we provide `progress*?` that works like `progress*` but also generates a\ndetailed proof script that can be inserted in the code via VS Code code actions (one just needs\nto click a button). For `mod_add`, we get:\n\n```\n  let* ⟨ ⟩ ← massert_spec\n  let* ⟨ ⟩ ← massert_spec\n  let* ⟨ sum, sum_post ⟩ ← U32.add_spec\n  let* ⟨ res, res_post ⟩ ← core.num.U32.wrapping_sub.progress_spec\n  let* ⟨ mask, mask_post1, mask_post2 ⟩ ← U32.ShiftRight_IScalar_spec\n  let* ⟨ q, q_post1, q_post2 ⟩ ← UScalar.and_spec\n```\n\nNotation `let* ⟨ x ⟩ ← spec` is syntactic sugar for `progress with spec as ⟨ x ⟩`.\nAfter these steps, only the pure bitvector goal remains.", "url": "https://wpnews.pro/news/an-overview-of-the-aeneas-rust-verification-toolchain", "canonical_source": "https://www.sonho.fr//2026/03/18/aeneas-overview.html", "published_at": "2026-11-27 06:26:32+00:00", "updated_at": "2026-11-27 06:43:00.478551+00:00", "lang": "en", "topics": ["developer-tools", "ai-research"], "entities": ["Aeneas", "Rust", "Lean", "Microsoft", "SymCrypt", "Polonius"], "also_reported_by": [], "takeaway": "Aeneas translates safe Rust into pure functional programs for verification in Lean, and its formalized symbolic-execution borrow-checker accepts some programs the current Rust borrow-checker or Polonius reject.", "recommendation": null, "alternates": {"html": "https://wpnews.pro/news/an-overview-of-the-aeneas-rust-verification-toolchain", "markdown": "https://wpnews.pro/news/an-overview-of-the-aeneas-rust-verification-toolchain.md", "text": "https://wpnews.pro/news/an-overview-of-the-aeneas-rust-verification-toolchain.txt", "jsonld": "https://wpnews.pro/news/an-overview-of-the-aeneas-rust-verification-toolchain.jsonld"}}