Notation for in-place programs #
The root module ScalarArray doesn't import this one, because it makes inplace a keyword.
Outside of inplace … do blocks it adds nothing else: no other keyword, and no other term. The
statements are parsed only in a block, the terms of the expansion aren't terms that can be written,
and inplace_bound, the tactic that proves the bounds of indices, isn't a keyword.
inplace a do … writes an in-place program (XArray.InPlace) on the array a in a small
imperative language, and runs it, which returns the program's result and the new array, or hands
them to a continuation then k. It works for all 13 array types, and for their slices (see
Slices):
inplace a do
for j in 0...len with (c := 0) (b := 0) do
let u := a[xs + j]
let v := a[ys + j]
let (s, c') := addc u v c
let (d, b') := subb u v b
a[xs + j] := s
a[ts + j] := d
c := c'
b := b'
return (c, b)
Statements #
a[i]in the terms of a statement reads the current element at theUSizeindexi, before the statement runs:let x := a[i]reads it intox, anda[i] := a[i] + 1increments it. So a read can't be under a binder, or in a branch of a term (if,match, or the right side of&&,||,∧and∨), which would run later or not at all: read it first withlet x := a[i], or branch with anifstatement.a[i] := ewriteseati.let x ← mruns an in-place programm : XArray.InPlace n α, for the program's sizen, and binds its result, so that programs compose.let p := ebinds a pure value, wherepcan be a pattern such as(s, c), andlet x : t := eone of typet.let mut x := eorlet mut x : t := edeclares a mutable variable, andx := eassigns it, or(x, y) := efor a pattern of mutable variables. As indonotation, aletcan't shadow a mutable variable.have h : t := padds a fact to the context, for the bounds of later indices. As in terms,hdefaults tothisandtto the type ofp:have : t := p,have h := p.if c then … else …andif h : c then … else …run one of two blocks, which may read, write, loop and assign mutable variables. Theelseblock is optional, andunless c do …isif ¬c then ….if let p := e then … else …runs the first block, with the variables of the patternp, ifematches it, and the second one, which is optional, otherwise.match e with | p => … | q => …runs the block of the first pattern thatematches, andmatch e, f with | p, q => …matches several terms.for j in lo...hi do …loops overlo ≤ j < hiupward, andfor j in reverse lo...hi do …over the same range downward, fromhi - 1tolo. The bounds areUSizes, and the ranges are those of core:lo...hiandlo...<hi,lo...=hi(up tohi),lo<...hiandlo<...=hi(fromlo + 1), and*...hiand*...=hi(from0).lo.toNat ≤ j.toNatandj.toNat < hi.toNatare in context in the body, orj.toNat ≤ hi.toNatandlo.toNat < j.toNatfor the other ranges, which needhi.toNat + 1 < USize.sizeandlo.toNat + 1 < USize.size, proved like the bounds of indices. A bound that is a literal, as in0...4, is in context as aNatliteral too,j.toNat < 4, which proofs such asget_elem_tacticuse.for h : j in lo...hi do …names the bounds,h : lo.toNat ≤ j.toNat ∧ j.toNat < hi.toNat, or the bounds of the other ranges (only the upper one for*...hi).for j in lo...hi by s do …runs overlo,lo + s, … belowhi, fors > 0, andreverseruns over the same indices downward.- An optional
with (x := init) …clause names the loop's variables, as(x : t := init)with their types: up to four, which the loop keeps as separate unboxed arguments. They are mutable in the body, and they hold their last values after the loop. Loops nest, and a nested loop allocates nothing either. while c do …andwhile h : c do …loop whilecholds, with awithclause likefor. The condition runs, with its reads, before each step. Awhileloop stops afterUSize.size - 1steps at the most.breakleaves the innermost loop, and its variables keep their current values after it.continuegoes on with the loop's next step.return eends the program with the resulte, anywhere, even in a loop, andreturnwith(). Without it, the result is(). Nothing in a block can follow areturn, abreakor acontinue.
A loop body can assign only its own variables: to update a variable across a loop, carry it, as
with (c := c).
Results #
inplace a do … returns the pair of the program's result and the new array. With then k after
the statements, it is k x a' h instead, for the result x, the new array a' and
h : a'.size = a.size:
inplace a do
for j in 0...len with (c := 0) (b := 0) do
…
return (c, b)
then fun (c, b) a' h => g c b a' h
The program calls k where it ends, inside its last loop if it ends with one, so the result goes
into no pair, and scalars such as the carries above reach k unboxed. h lets k run another
program on a' with the bounds proved for a.
Slices #
On a slice s of an array (an XArray.Slice), inplace s do … reads and writes the slice's
elements, at indices counted from the start of the slice, with bounds i.toNat < s.size, and
s.usize is its size as a USize. The program runs on the slice's array in place, with
XArray.Slice.runInPlaceThenOf, and returns the new slice, on the new array; with then k, k
gets the new slice and h : s'.size = s.size. let x ← m works on arrays only.
def double (s : UInt32Array.Slice) : UInt32Array.Slice :=
(inplace s do
for j in 0...s.usize do
s[j] := 2 * s[j]).2
The program reads and writes the array at off + i, where off is the slice's start as a USize.
When the array's size is less than USize.size, as it always is at runtime, that is the element
i of the slice.
Proofs #
A program is defined by its expansion, which runInPlaceThenOf_eq and the run lemmas of
XArray.InPlace.Tail take apart (ScalarArrayTest/Notation.lean has these examples):
- A program without branches or loops:
simp [XArray.runInPlaceThenOf_eq]runs it. - An
if:simp only [XArray.runInPlaceThenOf_eq, XArray.InPlace.Tail.run_readThen, XArray.InPlace.Tail.ite_eq]lifts it out of the program, and the cases follow, for example byby_cases hc : c <;> simp [hc]. - A loop: after
XArray.InPlace.Tail.forIn_eq,Tail.run_forInFromruns the loop asiterRange f lo hiof a functionfof the step, the loop's variables and the array, for a step thathbodyproves.iterRange_prod_of_snddrops the array when the loop only reads.Tail.run_forInFrom_modifyandTail.run_forInFrom_writerun the loops that writea[e j] := …, asmodifyAt, andTail.run_forInRevFromand its forms the loops down.
How the notation expands may change in later versions, so proofs that take a program apart may need adjusting after an upgrade.
Compilation #
The program expands to a tail program (XArray.InPlace.Tail) on arrays of size n, run with
a.runInPlaceThenOf n h, where n and a.usize are bound to variables before the program runs,
and the program uses them in place of a.size and a.usize. So nothing in the compiled program
refers to a, which the compiler would otherwise keep alive past the point where the program makes
the array exclusive, and the array would be copied. The program ends with Tail.done x k, where k
is the then continuation or makes the pair. Its statements expand to the tail programs readThen,
writeThen, ite, dite and the loops Tail.forIn, Tail.forIn2, … and Tail.forInRev, …, in
continuation-passing style: a loop body ends by calling next on the loop's variables, which runs
the next step, and the loop ends by calling the rest of the program, so the variables are arguments
of both and stay unboxed. continue calls next, and break calls the rest of the program, which
a loop that breaks binds to a local function. A nested loop ends by calling the outer loop's
next, so the two compile to mutually recursive loops with no allocation, and the program compiles
to the same loops as a hand-written one. The rest of the program after an if becomes a local
function of the mutable variables, which the compiler turns into a join point: an if in a loop
allocates nothing.
Bounds #
The bound of each index is proved by the tactic inplace_bound, from the hypotheses in context:
- for an index
off + jin a loop overj < len, from a window hypothesisoff.toNat + len.toNat ≤ a.size(tried only on indices that are sums, so that other indices don't pay for it); - otherwise by
lia; - otherwise, for indices with
USizearithmetic such asj - 17or2 * j + 1, bygrind, which splits on the platform widthSystem.Platform.numBits(see thegrind_patterninScalarArray.Internal), so the proof holds on both widths.
It looks inside conjunctions. A loop body has both bounds of its index, lo.toNat ≤ j.toNat and
j.toNat < hi.toNat, in context, and the program has a.usize.toNat ≤ a.size, so a.usize
works as a loop bound with no other hypothesis. A bound that needs more is given by a have
before the index, or by a hypothesis around the program, and a bound that inplace_bound can't
prove is reported with its goal. For example, in this left shift of 64-bit limbs by
1111 bits:
if h : 18 ≤ a.size then
(inplace a do
for j in reverse 18...a.usize do
a[j] := (a[j - 17] <<< 23) ||| (a[j - 18] >>> 41)
a[17] := a[0] <<< 23
for j in 0...17 do
a[j] := 0).2
else UInt64Array.mk (Array.replicate a.size 0)
Limits #
ais a local variable: the program's array or slice.b[i] := eon another arraybis an error, whileb[i]in a term is ordinary indexing ofb, with its own bound.- Inside the program,
ais the array before the program runs, so it is an error outside of the readsa[i]and its sizea.sizeora.usize:a[i]!,a[i]'hora.toArraywould read old elements, and keep the old array alive, which copies it. Ahaveand the proofs inbyblocks may usea, and so maythen k, which runs after the program, butkkeeps the old array alive if it uses more than its size. - Reads are written
a[i], not← a[i]:←runs a program. - A loop has at most four variables.
- A block has at least one statement.
- A program makes the array exclusive before it runs, even when it only reads, so a shared array
is copied. For a computation that only reads, use plain reads
a[i],foldlor the folds of slices, which don't copy. - There is no
x += e, and a term such aspure xis no statement: both are errors that say what to write instead.
The index off + i of a window of n elements at off is in bounds, for i < n: the bound of the
indices of a program on a slice, in the slice's array.
For internal use by the inplace notation.
The number of steps of the range lo...hi by s, for s > 0: of the indices lo + s * k below
hi.
For internal use by the inplace notation.
Instances For
f k. The notation inplace writes a loop that may break as withExit (fun brk => loop) k, with
the rest k of the program after the loop, which break calls: elaborated as the arguments of
withExit, the loop comes first and fixes the type of k.
For internal use by the inplace notation.
Instances For
The index of a loop over lo...hi + 1, which is lo...=hi, is at most hi. The proof doesn't need
hi + 1 not to wrap around, but the loop does, so the notation passes that fact here too.
For internal use by the inplace notation.
Proves the bound i.toNat < n of an index in an inplace program: for i = off + j, from a
window hypothesis off.toNat + len.toNat ≤ n and the loop bound j.toNat < len.toNat, or else by
lia from the hypotheses in context, or else by grind, for USize arithmetic that may wrap
around. Conjunctions in context are split first.
Instances For
Elaborates inplace_bound: runs its proof search, and reports a failure with the bound.
Instances For
let x ← m runs the in-place program m (an XArray.InPlace n α, for the program's size n)
and binds its result to x.
Instances For
let mut x := e declares the mutable variable x, and let mut x : t := e gives its type.
Instances For
let x : t := e binds the value of the pure term e of type t to x.
Instances For
let p := e binds the value of the pure term e to the pattern p.
Instances For
have h : t := p adds the fact h to the context, for the bounds of later indices; as in terms,
h defaults to this, and t to the type of p.
Instances For
(x, y) := e assigns the mutable variables of the pattern (x, y).
Instances For
if c then … else … runs one of two blocks.
Instances For
if let p := e then … else … runs the first block if e matches the pattern p, with its
variables, and the second one otherwise.
Instances For
unless c do … runs the block if c doesn't hold.
Instances For
The variables of a loop, with (x := init) (y : t := init) ….
Instances For
A loop over j in a range such as lo...hi or reverse lo...hi, by steps of s with by s, with
the variables of its with clause; for h : j in … names the bounds of j.
Instances For
A loop that runs while c holds, with the variables of its with clause.
Instances For
break leaves the innermost loop, with the current values of its variables.
Instances For
continue goes on with the next step of the innermost loop.
Instances For
An alternative | p => … of a match statement.
Instances For
match e with | p => … | q => … runs the block of the first pattern that e matches.
Instances For
return e ends the program with the result e, and return with ().
Instances For
x += e isn't a statement of an inplace program: this reports it, with what to write.
Instances For
x -= e isn't a statement of an inplace program: this reports it, with what to write.
Instances For
x *= e isn't a statement of an inplace program: this reports it, with what to write.
Instances For
An application f x …, such as pure x, isn't a statement of an inplace program: this reports
it, with the statements that are, rather than a parse error.
Instances For
inplace a do … is the in-place program on a that the statements describe, run on a: it
returns the program's result and the new array, or, with then k, k on them and the new array's
size. See the module documentation of ScalarArray.Notation.
Instances For
The internal terms of the expansion of an inplace program. They aren't terms of the term
category, so they can't be written outside of the expansion, and their names aren't keywords.
Instances For
inplace_elem a v is the value v of a write to the array or slice a of an inplace program,
elaborated as an element of a, so that a type error names v.
Instances For
inplace_choose a e f is e if a is an array and f if it is a slice: inplace a do … expands
to both programs, and elaborates the one for the type of a.
Instances For
Elaborates inplace_choose.
Instances For
Elaborates inplace_index.
Instances For
Elaborates inplace_elem.