Reversible functions

Put #[reversible(inverse_name)] on a function to generate its inverse. Both names are ordinary functions in the same module. They have the same parameter types, parameter modes and visibility. If the forward function is pub, importers can call the inverse through the module alias.

#[reversible(unmix)]
pub fn mix(inout x: u8, key: u8) {
    x ^= key
    x *%= 3
    x +%= 5
}

fn main() {
    var x: u8 = 42
    mix(&x, 7)
    inverse(mix)(&x, 7)
    assert(x == 42, "round trip")
}

Pass the same read-only arguments to both calls. The inverse applies the inverse updates in reverse order. For a body with only total operations, either order of calls recovers the initial values. The checked operators += and -= give a partial inverse. When a checked forward call succeeds, its inverse succeeds on that output. An inverse started on an arbitrary value can overflow.

Declarations

A reversible function is a safe free function with a body and at least one inout parameter. An inout slot can hold any concrete non-view type, including String, Vec, Box and aggregates that contain them. Read-only parameters can be integers or non-view Copy aggregates (types that satisfy Plain). A function returns unit unless it has a sink slot. Methods, trait items, generic functions, extern fn and export fn are excluded. The inverse name must be unused in the module. Both functions are available at compile time and at run time.

Function identity and inverse

inverse(F) resolves the generated partner of a named reversible function. For example, inverse(mix)(&x, 7) calls unmix and inverse(inverse(mix))(&x, 7) calls mix. Qualified names such as weights.mix resolve by the imported declaration. A comptime f: fn(inout u8, u8) parameter can bind to a named declaration or to its inverse and call it directly. The builtin requires a named reversible declaration, including when its operand comes through such a parameter.

Quantum compute routines

A quantum reversible routine takes an inout std.quantum.Circuit, zero or more shared Qubit controls, and an inout Qubit scratch. Its unit-returning body composes std.quantum.x, cnot, toffoli and other certified quantum reversible routines. The compiler checks that each call’s operands are distinct and all gate targets are the scratch parameter. The inverse reverses the gate order and calls the partner of each nested pair. Phase gates, rotations and measurement are outside this qfree subset.

with_ancilla1 and with_ancilla2 use this guarantee to uncompute scratch. Quantum circuits guide

Owned state and sink slots

A reversible function can have one sink T slot and a matching by-value result -> T. The last expression must be move of that exact slot. The inverse receives the forward result in its own sink slot. For example, each direction of this pair exchanges two owned strings.

import std.mem

#[reversible(unexchange)]
fn exchange(inout stored: String, sink cargo: String) -> String {
    mem.swap(&stored, &cargo)
    move cargo
}

A paired call that consumes a sink slot must put its result back in the same slot immediately, as in cargo = exchange(&stored, move cargo). The assignment can appear in branches and loops that preserve an initialized slot on every continuing path. Early returns, discarding owned values, assigning fresh values, projections, indexing and arbitrary methods are outside the reversible subset. After move and drop elaboration, the compiler rejects any surviving drop in either member of a reversible pair, including drops guarded by a flag.

Updates

An arithmetic or bitwise update targets a bare inout integer parameter. A swap works on two whole, distinct, same-type mutable slots.

Forward update Inverse
x += r, x -= r Checked subtraction or addition of r
x +%= r, x -%= r Wrapping subtraction or addition of r
x ^= r XOR with r
x *%= c with odd constant c Wrapping multiply by the inverse of c modulo 2 to the integer width
x ^= x << k XOR with left shifts by k, 2k, 4k, … below the width
x ^= x >> k on an unsigned integer XOR with right shifts by k, 2k, 4k, … below the width
x +%= x << k Wrapping multiply by the inverse of 1 + 2^k modulo 2 to the integer width
x = !x, x = 0 -% x The same update
x = (x << k) | (x >> (n - k)) on an unsigned n-bit integer Rotate in the other direction
mem.swap(&a, &b) from std.mem Swap the same two whole slots

The ordinary operands r cannot read x. Each special shift or rotation uses a constant k with 0 < k < n. A rotation also accepts the two sides of the OR in either order and accepts a constant expression for either count.

Replay and control flow

The inverse recomputes expressions using integer and bool literals, scalar bindings, resolved constants, primitive scalar casts, bitwise operators, wrapping arithmetic, and boolean operators and comparisons. Shift counts must be provably in range. For example, n & 7 is a valid count for a shift of a byte. Checked arithmetic in a replayed expression must be known at compile time to fit. Division, modulo and arbitrary function calls are excluded.

  • A read-only let binds one integer or bool, optionally with a type annotation. Its initializer’s dependencies must stay unchanged through the rest of the lexical block, even across nested writes and calls. The inverse recomputes the lets in declaration order when it enters the block.
  • An if condition can read bindings that neither branch writes. An omitted else is an empty branch. An else if is allowed.
  • for i in lo..hi and for i in lo..=hi use same-type integer bounds that the body never writes; _ may stand for the index. The inverse evaluates the bounds once and visits the same indices in descending order. For lo..=hi it starts at hi and ends at lo, even at the integer type’s limits. If lo > hi, neither direction runs.
  • A direct call to either member of a reversible pair is inverted by calling its partner. Each inout argument must be a distinct &name naming a mutable slot of the caller. A read-only aggregate argument must be a bare name. Read-only arguments must be independent of all mutable arguments of that call, including its sink slot. Reversible calls cannot form a cycle.

Runnable hash and xorshift examples

Reversible chain pebbling and checkpointing

Esc