Chapter 36Replays, mirrors and detours
The pointer machine of Chapter 7 and the command streams of Chapter 10 are enough to state the results on combining search trees and on deamortization. Their proofs treat pointer computations as data. A computation is recorded as a list of instructions, replayed later on another cursor, or undone. A cursor leaves its work for a moment, visits a requested key, and comes back to exactly the configuration it left. A construction proved on the left side of a tree is transferred to the right side by mirroring. The depth of every key is tracked at every instruction boundary of a long computation, not only at its ends. And cursors move over trees whose nodes carry data: labels that travel with their nodes under rotations, payload words, and the interval of keys below each node, which lets a cursor find any key by looking only at the node it stands on.
This chapter collects these tools. It has no theorem of its own and no headline result. It is a toolbox, and most of its statements are lemmas used inside proofs. The table says which chapters use each part.
| Section | Lean modules | Used by |
|---|---|---|
| Recorded instruction streams | Models/Multifinger/Program/Replay |
the emitted programs of deamortization (Chapter 30) and of the combined finger bound (Chapter 31); the replay logs of ComboBST workers (Section 29.2); saving and restoring tree states (Section 39.1, Section 39.2); interruptible pop-tarts and heavy paths (Section 37.2, Section 38.2, Section 38.4) |
| Walks and detours | Models/Pointer/Walk, Models/Pointer/Detour |
serving a request in the middle of pending work (Chapter 30); requests during the heavy-path simulation (Section 38.4) |
| Mirror images | Models/Pointer/Mirror |
right-hand pop-tarts (Section 37.1) and paired heavy paths (Section 38.1) |
| Depths along a computation | Bounds/StaticTree/Trace, Models/Pointer/Invariant |
the bounded-depth simulation behind deamortization: Chocolate pop-tarts (Section 37.2), heavy paths (Section 38.1 to Section 38.4) and the request window of Chapter 30 |
| Labelled cursors | Models/Labelled/Cursor, Models/Labelled/Cursor/Map |
the source configurations of the deamortization (Chapter 30) and of heavy paths (Section 38.1); tree-buffer nodes (Section 39.1); ComboBST request replay (Section 29.2) |
| Data in the nodes | Models/Labelled/Metadata |
tree-buffer cells (Section 39.1) |
| Interval fields and local routing | Models/Pointer/Routing, Models/Labelled/Intervals |
tree buffers and scans (Section 39.1), snapshot startup (Section 39.2), and through them every ComboBST policy (Section 29.4, Chapter 31) |
A reader who only wants to check the headline theorems of Section 29.1 to Chapter 31 needs two definitions from here. The programs emitted by the deamortized and combined algorithms are stated as legal by Multifinger.replay, from the first section. The ComboBST theorems are quantified over arbitrary old contents of the interval words, fields : Nat → IntervalMetadata.Bounds, from the last section; that parameter is only the initial content of memory, so the reader may treat it as “whatever was there”. Everything else is proof machinery. Read the section on depths if you want to see why the deamortized algorithms have a worst-case bound per request, and the section on interval fields if you want to see how a ComboBST cursor finds keys without a search from the root.
The models extend three earlier ones. Chapter 7 gives the single cursor, its configurations Pointer.Config, its instructions Pointer.Step and traces Pointer.Trace, and the navigation-only Pointer.Walk. Chapter 10 gives the six opcodes Multifinger.Opcode and their executable reading Multifinger.perform. Chapter 11 gives search in a LabelledTree whose nodes carry keys; here, nodes carry arbitrary data and the cursor may start anywhere.
36.1 Recorded instruction streams
A Multifinger.Program of Chapter 10 is a relation: a legal command stream between two multi-finger states. Algorithms that emit instructions one at a time, and proofs that store, concatenate or invert such streams, need a plain function that runs a list of opcodes on one cursor.
/-- Replay a recorded stream on one persistent cursor. Illegal instructionsfail explicitly; neither their target tree nor their target key is supplied. -/def replay : List Opcode → Pointer.Config → Option Pointer.Config | [], cursor => some cursor | op :: ops, cursor => (perform op cursor).bind (replay ops)replay ops c runs the opcodes in order from the configuration c, using Multifinger.perform for each one. It returns none as soon as one instruction is illegal, for instance a move onto an empty child or a rotation at the root. Nothing else is supplied: the stream names neither the tree it should produce nor the keys it should reach. Whether a stream is legal, and where it ends, is computed from the configuration alone. There is no finger index, since a single cursor is meant; the multi-finger reading is Command.Step.
/-- Undo a primitive instruction while restoring both tree and cursor.Undoing a rotation requires three instructions because its old parent was demoted. -/def Opcode.inverse : Opcode → List Opcode | .downLeft => [.upLeft] | .downRight => [.upRight] | .upLeft => [.downLeft] | .upRight => [.downRight] | .rotateLeftChild => [.downRight, .rotateRightChild, .downLeft] | .rotateRightChild => [.downLeft, .rotateLeftChild, .downRight]/-- Undo in reverse chronological order, expanding each primitive inverse. -/def undo (ops : List Opcode) : List Opcode := ops.reverse.flatMap Opcode.inverseOpcode.inverse undoes one instruction and restores the whole configuration, tree and cursor. A move is undone by the opposite move. A rotation needs three instructions. After rotateLeftChild, the cursor is still on the promoted node, and its old parent is now its right child. The cursor steps down to it (downRight), rotates it back up (rotateRightChild), and steps down to the original node (downLeft). undo ops undoes the stream in reverse chronological order, expanding each instruction into its inverse.
The five results say that streams and traces are the same thing, and that undoing works.
- Streams are traces. A successful replay is a
Pointer.Tracewith exactly one instruction per opcode (physical). Conversely, every trace of instructions is the replay of some stream of length (record). - Undoing restores. If
opstakesatob, thenundo opstakesbback toa(restore), soops ++ undo opsreturns fromatoa(roundtrip). The undo stream is at most three times as long as the original (inverse_size).
/-- Replaying a successful log gives exactly its length in physical operations. -/theorem physical {ops : List Opcode} {a b : Pointer.Config} (run : replay ops a = some b) : Pointer.Trace a b ops.length := replay_trace runtheorem record {a b : Pointer.Config} {k : Nat} (trace : Pointer.Trace a b k) : ∃ ops, ops.length = k ∧ replay ops a = some b := trace_replay trace/-- The inverse restores the entire cursor, not just its tree. -/theorem restore {ops : List Opcode} {a b : Pointer.Config} (run : replay ops a = some b) : replay (undo ops) b = some a := undo_replay runtheorem inverse_size (ops : List Opcode) : (undo ops).length ≤ 3 * ops.length := undo_length opstheorem roundtrip {ops : List Opcode} {a b : Pointer.Config} (run : replay ops a = some b) : replay (ops ++ undo ops) a = some a := replay_roundtrip runThe restoration is of the configuration: the cursor comes back to the same node, with the same path to the root, not only the same tree. This is the step behind the tree-state buffer of the ComboBST paper (Demaine et al. 2013, Section 3). There, a tree state is saved by recording the operations of a linear-time algorithm that turns the tree into a path, and it is loaded by turning the current tree into a path and then undoing the recorded operations. The snapshots of Section 39.2 formalize this. The factor of inverse_size is the same factor as in the reversal of pointer traces inside the reshaping theorem Results.reshape of Chapter 7.
36.2 Walks and detours
A walk only moves the cursor, so it never changes the tree. The three facts that make this precise are short.
theorem primitive {a b : Config} (move : Move a b) : Step a b := move.steptheorem physical {a b : Config} {k : Nat} (walk : Walk a b k) : Trace a b k := walk.tracetheorem fixed_tree {a b : Config} {k : Nat} (walk : Walk a b k) : a.tree = b.tree := walk.tree_eqA Pointer.Move is a Pointer.Step, a Pointer.Walk of moves is a Pointer.Trace of instructions, and the two ends of a walk represent the same tree.
The proof of Theorem 6 of Bose, Collette, Fagerberg and Langerman (2012a) serves a request in the middle of other work. The simulated algorithm has a pending sequence of operations. Whenever too many of them have been performed without reaching the next requested key, the deamortized algorithm “accesses this element by moving the finger to it and back”. This is a detour: a walk from the current configuration to the requested key, and the reverse walk, after which the pending work resumes exactly where it stopped. The library states it in five steps.
theorem trace_nonempty {a b : Config} {cost : Nat} (trace : Trace a b cost) (live : a.focus ≠ .nil) : b.focus ≠ .nil := RotationBST.Pointer.Detour.trace_nonempty trace liveA cursor that stands on a node keeps standing on a node: every trace from a configuration with a nonempty focus ends at a nonempty focus. This holds because no instruction moves the cursor onto an empty subtree (Chapter 7). It lets a detour start at any intermediate configuration of a computation that started on a node.
theorem walk {start : Config} {current target : Nat} (key : start.key? = some current) (valid : target < start.tree.size) : ∃ (visited : Config) (cost : Nat), visited.key? = some target ∧ visited.tree = start.tree ∧ Walk start visited cost ∧ Walk visited start cost ∧ cost ≤ Tree.depth start.tree current + Tree.depth start.tree target ∧ (current = target → cost = 0) := RotationBST.Pointer.Detour.walk key validTheorem (walk there and back). Let the cursor of start be on rank current, and let target be a rank of the same tree. Some configuration visited has the cursor on target, in the same tree, and there are walks from start to visited and from visited back to start with the same number of moves. That number is at most , and it is if the cursor is already on the target.
The walk goes up to the lowest common ancestor and down again. The depths are Tree.depth, in edges, of the tree that start represents.
theorem record {a b : Config} {cost : Nat} (walk : Walk a b cost) : ∃ ops : List Multifinger.Opcode, ops.length = cost ∧ Multifinger.replay ops a = some b ∧ ∀ cut, ∃ middle, Multifinger.replay (ops.take cut) a = some middle ∧ middle.tree = a.tree := RotationBST.Pointer.Detour.record walkA walk is recorded as a stream of the same length, and every prefix of that stream replays to a configuration of the same tree. The prefix clause matters because the deamortized algorithm may be interrupted again inside a detour; whatever the cut, the tree is the one the detour started from.
theorem bounded {start : Config} (live : start.focus ≠ .nil) {target : Nat} (valid : target < start.tree.size) {height : ℝ} (depths : ∀ x < start.tree.size, (Tree.depth start.tree x : ℝ) ≤ height) : ∃ (visited : Config) (before after : List Multifinger.Opcode), Multifinger.replay before start = some visited ∧ visited.key? = some target ∧ Multifinger.replay after visited = some start ∧ (1 + before.length + after.length : ℝ) ≤ 1 + 4 * height ∧ (start.key? = some target → before = [] ∧ after = []) ∧ (∀ cut, ∃ middle, Multifinger.replay (before.take cut) start = some middle ∧ middle.tree = start.tree) ∧ (∀ cut, ∃ middle, Multifinger.replay (after.take cut) visited = some middle ∧ middle.tree = start.tree) := RotationBST.Pointer.Detour.bounded live valid depthsTheorem (bounded detour). Suppose the cursor of start is on a node, target is a rank of the tree, and every rank of the tree has depth at most height. Then there are streams before, from start to a configuration on target, and after, from there back to start, with
Both streams are empty if the cursor is already on the target, and every prefix of either stream stays in the same tree.
The leading is the request unit of Pointer.Serves, so the left side is the cost of one detour as a request. The bound is and not because both the way there and the way back may climb from one key to the common ancestor and descend to the other. height is a real number, so that it can be a logarithm.
theorem resume {start middle visited finish : Config} {earlier before after later : List Multifinger.Opcode} (first : Multifinger.replay earlier start = some middle) (outward : Multifinger.replay before middle = some visited) (backward : Multifinger.replay after visited = some middle) (last : Multifinger.replay later middle = some finish) : Multifinger.replay (earlier ++ before ++ after ++ later) start = some finish := RotationBST.Pointer.Detour.resume first outward backward lastFinally, a detour can be spliced into a stream. If earlier reaches middle, the detour leaves middle and returns to it, and later continues from middle to finish, then the concatenation earlier ++ before ++ after ++ later runs from start to finish. Together with bounded, this is how Results.serve of Chapter 30 serves a request with a bounded number of extra instructions while keeping the pending work intact. That theorem needs the depth of every rank to be bounded at the moment of interruption, which is the subject of the section after next.
36.3 Mirror images
Reflecting a tree exchanges left and right everywhere.
def Tree.mirror : Tree → Tree | .nil => .nil | .node l r => .node r.mirror l.mirrordef Frame.mirror : Frame → Frame | .left r => .right r.mirror | .right l => .left l.mirrordef Config.mirror (c : Config) : Config := ⟨c.focus.mirror, c.context.map Frame.mirror⟩Tree.mirror swaps the two children of every node. A frame left r, where the cursor is in the left subtree of an ancestor whose right subtree is r, becomes right r.mirror, and conversely. A configuration is mirrored focus and frames alike. The inorder order is reversed: rank of t becomes rank of t.mirror.
Mirroring is an involution on trees, frames and configurations; it keeps the size; it commutes with Pointer.plug, so the mirror of a configuration represents the mirror of its tree; and it turns every instruction into an instruction and every trace into a trace of the same length.
theorem tree_involution (t : Tree) : t.mirror.mirror = t := Tree.mirror_mirror ttheorem tree_size (t : Tree) : t.mirror.size = t.size := Tree.mirror_size ttheorem frame_involution (f : Frame) : f.mirror.mirror = f := Frame.mirror_mirror ftheorem config_involution (c : Config) : c.mirror.mirror = c := Config.mirror_mirror ctheorem plug (cs : List Frame) (t : Tree) : (Pointer.plug cs t).mirror = Pointer.plug (cs.map Frame.mirror) t.mirror := mirror_plug cs ttheorem config_tree (c : Config) : c.mirror.tree = c.tree.mirror := Config.mirror_tree ctheorem step {a b : Config} (h : Step a b) : Step a.mirror b.mirror := h.mirrortheorem trace {a b : Config} {k : Nat} (h : Trace a b k) : Trace a.mirror b.mirror k := h.mirrorUnder the mirror, downLeft becomes downRight, upLeft becomes upRight and rotateLeftChild becomes rotateRightChild, and conversely. The use is economy of proof. The heavy-path representation of the deamortization paper keeps, for the path from the root to the finger, the nodes that leave the path to the left and those that leave it to the right in two weighted stacks, and . The library builds and analyses only the left-hand pop-tart, and obtains the right-hand one as its mirror image (Section 37.1, Section 38.1). The results above, and the depth versions below, carry costs and depth bounds across the reflection.
36.4 Depths along a computation
36.4.1 Why depths are tracked
The deamortization of Chapter 30 runs a simulation of the source algorithm and may stop it after any instruction to serve a request by a detour. A detour costs at most times the largest depth in the current tree, by bounded above. The current tree is an intermediate tree of the simulation: one that the algorithm passes through, between two of its own requests, and that no amortized analysis speaks about. A bound on the cost of each request therefore needs a depth bound that holds at every instruction boundary of the simulation.
That is what the heavy-path simulation provides. In Results.simulation, every cut of the emitted stream reaches a tree in which every rank has depth at most , where is the rank’s weight and the total weight. The deamortization uses unit weights, so the bound is . With it, each response of the deamortized algorithm costs less than . The deamortized Splay theorems of Chapter 30, from scanning to static optimality and static finger, are all stated for one implementation and one run, so they hold together with this worst-case bound; the bound itself rests on the lemmas of this section. Static optimality is not derived from these depth bounds: it comes from the total-cost comparison with Splay.
The depth bounds of the simulation are assembled from bounds for each piece: one pop-tart operation, one heavy-path update, one change inside a subtree, the mirror image of a left-hand operation, and operations in sequence. The lemmas below are the glue. All depths are Tree.depth, in edges, indexed by inorder rank, the same function as in the static-tree bounds of Chapter 14.
36.4.2 One instruction changes a depth by at most one
Theorem (rotations). One rotation increases the depth of any rank by at most . A sequence of rotations increases it by at most .
theorem rotate_depth {s t : Tree} (rotation : Rotate s t) (x : Nat) : depth t x ≤ depth s x + 1 := RotationBST.StaticTree.Trace.rotate_depth rotation xtheorem rotations_depth {s t : Tree} {cost : Nat} (rotations : Rotations s t cost) (x : Nat) : depth t x ≤ depth s x + cost := RotationBST.StaticTree.Trace.rotations_depth rotations xTheorem (traces). Along a pointer trace of instructions from s to t, the depth of every rank changes by at most , in both directions: and .
theorem trace_depth {s t : Pointer.Config} {cost : Nat} (trace : Pointer.Trace s t cost) (x : Nat) : depth t.tree x ≤ depth s.tree x + cost := RotationBST.StaticTree.Trace.trace_depth trace xtheorem trace_depth_reverse {s t : Pointer.Config} {cost : Nat} (trace : Pointer.Trace s t cost) (x : Nat) : depth s.tree x ≤ depth t.tree x + cost := RotationBST.StaticTree.Trace.trace_depth_reverse trace xMoves do not change the tree, and a rotation changes each depth by at most one in either direction, since it can be undone by one rotation. The quantifier ranges over all natural numbers . For in a nonempty tree, Tree.depth follows the right spine and returns one more than the depth of the maximum, so these cases add nothing.
Theorem (cut a stream anywhere). If a stream ops runs from s to t, then for every cut point the prefix ops.take cut reaches some middle, the suffix ops.drop cut continues from middle to t, and every rank satisfies
If the whole stream has at most budget instructions, then .
theorem replay_prefix_depth {ops : List Multifinger.Opcode} {s t : Pointer.Config} (executed : Multifinger.replay ops s = some t) (cut : Nat) : ∃ middle, Multifinger.replay (ops.take cut) s = some middle ∧ Multifinger.replay (ops.drop cut) middle = some t ∧ ∀ x, depth middle.tree x ≤ min (depth s.tree x + (ops.take cut).length) (depth t.tree x + (ops.drop cut).length) := RotationBST.StaticTree.Trace.replay_prefix_depth executed cuttheorem replay_prefix_bound {ops : List Multifinger.Opcode} {s t : Pointer.Config} (executed : Multifinger.replay ops s = some t) {budget : ℝ} (cost : (ops.length : ℝ) ≤ budget) (cut : Nat) : ∃ middle, Multifinger.replay (ops.take cut) s = some middle ∧ Multifinger.replay (ops.drop cut) middle = some t ∧ ∀ x, (depth middle.tree x : ℝ) ≤ depth s.tree x + budget := RotationBST.StaticTree.Trace.replay_prefix_bound executed cost cutThese are the bounds for streams that are short compared with the depths, such as the bounded number of instructions that the deamortized algorithm executes per request. For long computations an additive bound is useless, and the depth must be controlled by an invariant.
36.4.3 The trace invariant
/-- A physical trace whose whole tree satisfies an invariant at everyinstruction boundary, including both endpoints. -/inductive TraceWithin (holds : Tree → Prop) : Config → Config → Nat → Prop where | refl {a : Config} : holds a.tree → TraceWithin holds a a 0 | step {a b c : Config} {cost : Nat} : holds a.tree → Step a b → TraceWithin holds b c cost → TraceWithin holds a c (cost + 1)TraceWithin holds a c cost is a pointer trace of cost instructions from a to c, together with the fact that the tree satisfies holds at every instruction boundary, both endpoints included. It is Pointer.Trace with one more hypothesis in each constructor. The invariants used in the library all have the same shape: relative to the starting tree s, every intermediate tree u has the same size and
with a factor and a constant . The size clause is what makes depths of different trees comparable: rotations keep the size and the inorder order, so rank names the same key in all of them.
Theorem (every trace satisfies the additive invariant). A trace of instructions from a satisfies the invariant with and .
theorem within_size_depth {a b : Pointer.Config} {cost : Nat} (trace : Pointer.Trace a b cost) : Pointer.TraceWithin (fun t => t.size = a.tree.size ∧ ∀ x, depth t x ≤ depth a.tree x + cost) a b cost := RotationBST.StaticTree.Trace.within_size_depth traceThis is the previous section, at every boundary. The pieces of the heavy-path simulation are short, so this lemma starts most of their invariants.
Theorem (composition). If a trace from a to b satisfies the invariant with relative to a, and a trace from b to c satisfies it with relative to b, where , then the concatenated trace satisfies it with factor and constant relative to a.
theorem within_append {a b c : Pointer.Config} {firstCost lastCost f g u v : Nat} (positive : 1 ≤ g) (first : Pointer.TraceWithin (fun t => t.size = a.tree.size ∧ ∀ x, depth t x ≤ f * depth a.tree x + u) a b firstCost) (last : Pointer.TraceWithin (fun t => t.size = b.tree.size ∧ ∀ x, depth t x ≤ g * depth b.tree x + v) b c lastCost) : Pointer.TraceWithin (fun t => t.size = a.tree.size ∧ ∀ x, depth t x ≤ (g * f) * depth a.tree x + (g * u + v)) a c (firstCost + lastCost) := RotationBST.StaticTree.Trace.within_append positive first lastThe constants compose like affine maps: . Factors multiply, so this composition is meant for a bounded number of pieces: a long sequence of pieces, each with a factor larger than , would let the bound grow geometrically.
Theorem (embedding in a context). If ’s depths are bounded by s’s depths plus , with and equal sizes, then the same bound holds after both trees are plugged into the same context cs. Consequently, a root-to-root trace from s to t satisfying the invariant becomes a root-to-root trace from plug cs s to plug cs t of cost that satisfies the invariant relative to plug cs s, provided that s and t are nonempty.
theorem plug_bound (cs : List Pointer.Frame) {s t : Tree} {factor constant : Nat} (factorPositive : 1 ≤ factor) (size : t.size = s.size) (bound : ∀ x, depth t x ≤ factor * depth s x + constant) : ∀ x, depth (Pointer.plug cs t) x ≤ factor * depth (Pointer.plug cs s) x + constant := RotationBST.StaticTree.Trace.plug_bound cs factorPositive size boundtheorem within_embed {s t : Tree} {cost factor constant : Nat} (cs : List Pointer.Frame) (factorPositive : 1 ≤ factor) (h : Pointer.TraceWithin (fun u => u.size = s.size ∧ ∀ x, depth u x ≤ factor * depth s x + constant) ⟨s, []⟩ ⟨t, []⟩ cost) (liveS : s ≠ .nil) (liveT : t ≠ .nil) : Pointer.TraceWithin (fun u => u.size = (Pointer.plug cs s).size ∧ ∀ x, depth u x ≤ factor * depth (Pointer.plug cs s) x + constant) ⟨Pointer.plug cs s, []⟩ ⟨Pointer.plug cs t, []⟩ (cs.length + cost + cs.length) := RotationBST.StaticTree.Trace.within_embed cs factorPositive h liveS liveTThe embedded trace walks down the context to the subtree, runs the computation there, and walks back up; the two walks cost each. A key outside the subtree keeps its depth, and a key inside has its depth in the subtree plus ; the condition makes the bound survive the extra . This is how an operation on one pop-tart, deep inside the heavy-path representation, contributes to the depth invariant of the whole tree. The nonemptiness hypotheses let the cursor stand on the root of the subtree at both ends.
Theorem (mirror images). Mirroring moves rank to rank and keeps its depth. Depth bounds of the invariant’s form, and the invariant along a trace, transfer to the mirror images.
theorem mirror_rank_depth (t : Tree) (x : Nat) (inside : x < t.size) : depth t.mirror (t.size - 1 - x) = depth t x := RotationBST.StaticTree.Trace.mirror_rank_depth t x insidetheorem mirror_bound {s t : Tree} {factor constant : Nat} (factorPositive : 1 ≤ factor) (size : t.size = s.size) (bound : ∀ x, depth t x ≤ factor * depth s x + constant) : ∀ x, depth t.mirror x ≤ factor * depth s.mirror x + constant := RotationBST.StaticTree.Trace.mirror_bound factorPositive size boundtheorem within_mirror_depth {a b : Pointer.Config} {cost factor constant : Nat} (factorPositive : 1 ≤ factor) (h : Pointer.TraceWithin (fun t => t.size = a.tree.size ∧ ∀ x, depth t x ≤ factor * depth a.tree x + constant) a b cost) : Pointer.TraceWithin (fun t => t.size = a.mirror.tree.size ∧ ∀ x, depth t x ≤ factor * depth a.mirror.tree x + constant) a.mirror b.mirror cost := RotationBST.StaticTree.Trace.within_mirror_depth factorPositive hmirror_bound compares the mirrors at the same rank, which is legitimate because both trees have the same size, so the reflection of ranks is the same on both sides. With within_mirror_depth and Results.trace, every depth guarantee proved for a left-hand pop-tart holds for the right-hand one.
36.5 Labelled cursors
The configurations of Chapter 7 are shapes: a node has no content, and its key is its inorder rank, computed from subtree sizes. Most structures of the deamortization and combination chapters store something in their nodes: a weight, a key and a stored interval, a payload word. They need a cursor on a LabelledTree whose instructions carry each label along with its node.
inductive Frame (α : Type) where | left (entry : α) (right : LabelledTree α) | right (left : LabelledTree α) (entry : α) deriving DecidableEqdef plug {α : Type} : List (Frame α) → LabelledTree α → LabelledTree α | [], t => t | .left entry r :: cs, t => plug cs (.node t entry r) | .right l entry :: cs, t => plug cs (.node l entry t)def Frame.erase {α : Type} : Frame α → Pointer.Frame | .left _ r => .left r.erase | .right l _ => .right l.eraseA labelled frame records one ancestor of the cursor, now with its label: left entry r says that the cursor is in the left subtree of an ancestor labelled entry whose right subtree is r, and right l entry is the mirror case. As in Pointer.Frame, the constructor names the side on which the cursor is. plug rebuilds the labelled tree from the focus and the frames, nearest ancestor first, and Frame.erase forgets the labels.
structure Config (α : Type) where focus : LabelledTree α context : List (Frame α) deriving DecidableEqdef Config.tree {α : Type} (c : Config α) : LabelledTree α := plug c.context c.focusdef Config.erase {α : Type} (c : Config α) : Pointer.Config := ⟨c.focus.erase, c.context.map Frame.erase⟩A labelled configuration is a focused labelled subtree with its labelled context. tree is the labelled tree it represents, and erase is the underlying shape configuration of Chapter 7.
/-- Read the entry physically under the cursor. -/def Config.read {α : Type} (c : Config α) : Option α := match c.focus with | .nil => none | .node _ entry _ => some entry/-- Replace only the entry physically under the cursor. -/def Config.write {α : Type} (c : Config α) (entry : α) : Option (Config α) := match c.focus with | .nil => none | .node l _ r => some ⟨.node l entry r, c.context⟩read returns the label of the node under the cursor, and write entry replaces it, keeping both children and the whole context. Both fail on an empty focus. They are the only ways to inspect or change a label, and they act only at the cursor: a structure that wants to read the label of another node must first walk there. The cursor model charges nothing for them; the models that use them (the word costs below, and the cell costs of Section 39.1) charge for reads and writes explicitly.
/-- Stored labels travel with their physical nodes. No rank or subtree sizecomputation is used by these pointer primitives. -/def perform {α : Type} : Multifinger.Opcode → Config α → Option (Config α) | .downLeft, ⟨.node (.node a x b) y r, cs⟩ => some ⟨.node a x b, .left y r :: cs⟩ | .downRight, ⟨.node l x (.node a y b), cs⟩ => some ⟨.node a y b, .right l x :: cs⟩ | .upLeft, ⟨.node a x b, .left y r :: cs⟩ => some ⟨.node (.node a x b) y r, cs⟩ | .upRight, ⟨.node a y b, .right l x :: cs⟩ => some ⟨.node l x (.node a y b), cs⟩ | .rotateLeftChild, ⟨.node a x b, .left y r :: cs⟩ => some ⟨.node a x (.node b y r), cs⟩ | .rotateRightChild, ⟨.node a y b, .right l x :: cs⟩ => some ⟨.node (.node l x a) y b, cs⟩ | _, _ => noneperform op c executes one of the six opcodes of Multifinger.Opcode on a labelled configuration. The patterns are those of Multifinger.perform, with labels added. A rotation moves the labels with their nodes: after rotateLeftChild at the node labelled x, whose parent is labelled y, the node labelled x is on top and the node labelled y is its right child. As the docstring says, no rank or subtree size is computed by these primitives.
The results say that the labelled cursor is the shape cursor with labels attached, and nothing more.
theorem erase_tree {α : Type} (c : Config α) : c.tree.erase = c.erase.tree := RotationBST.LabelledCursor.erase_tree ctheorem perform_erase {α : Type} (op : Multifinger.Opcode) (c : Config α) : (perform op c).map Config.erase = Multifinger.perform op c.erase := RotationBST.LabelledCursor.perform_erase op ctheorem perform_physical {α : Type} {op : Multifinger.Opcode} {s t : Config α} (step : perform op s = some t) : Pointer.Step s.erase t.erase := RotationBST.LabelledCursor.perform_physical steptheorem write_erase {α : Type} {s t : Config α} {entry : α} (write : s.write entry = some t) : t.erase = s.erase := RotationBST.LabelledCursor.write_erase writeErasing commutes with building the tree (erase_tree) and with every instruction (perform_erase): a labelled instruction succeeds exactly when the shape instruction succeeds, and it then does the same thing to the shape. In particular each successful labelled instruction is one Pointer.Step (perform_physical), so labelled computations are charged by the pointer machine of Chapter 7. A write leaves the shape configuration unchanged (write_erase).
/-- Lift an already identified shape cursor to its labelled-tree view. -/theorem lift {α : Type} (cursor : Pointer.Config) (whole : LabelledTree α) (shape : whole.erase = cursor.tree) : ∃ c : Config α, c.tree = whole ∧ c.erase = cursor := lift_config cursor whole shapeConversely, every shape cursor can be labelled: if a labelled tree whole has the shape of the tree of a shape configuration cursor, then some labelled configuration of whole erases to cursor. So a shape computation, a Pointer.Trace for example, can always be followed on a labelled tree of the same shape.
36.5.1 Projecting fields
A node often stores a tuple of fields, of which a sub-structure uses only some. The library projects a labelled tree or cursor by a function on labels.
def LabelledTree.map {α β : Type} (f : α → β) : LabelledTree α → LabelledTree β | .nil => .nil | .node l entry r => .node (l.map f) (f entry) (r.map f)def Frame.map {α β : Type} (f : α → β) : Frame α → Frame β | .left entry r => .left (f entry) (r.map f) | .right l entry => .right (l.map f) (f entry)/-- A proof projection of node fields, not a traversal run by the machine. -/def Config.map {α β : Type} (f : α → β) (c : Config α) : Config β := ⟨c.focus.map f, c.context.map (Frame.map f)⟩These apply f to every label of a tree, a frame, or a configuration. The docstring is explicit: Config.map is a proof projection, not a traversal run by the machine. It is used to say that the routing view of a tree-buffer node (Section 39.1), its key and interval, evolves exactly as the interval model of the last section, whatever the other fields of the node hold.
/-- Projecting node fields does not change the physical cursor. -/theorem map_erase {α β : Type} (f : α → β) (c : Config α) : (c.map f).erase = c.erase := LabelledCursor.map_erase f c/-- Field projections commute with every pointer primitive. -/theorem perform_map {α β : Type} (f : α → β) (op : Multifinger.Opcode) (c : Config α) : (perform op c).map (Config.map f) = perform op (c.map f) := LabelledCursor.perform_map f op c/-- Lift an exact labelled cursor through any field projection. -/theorem lift_map {α β : Type} (f : α → β) (cursor : Config β) (whole : LabelledTree α) (mapped : whole.map f = cursor.tree) : ∃ c : Config α, c.tree = whole ∧ c.map f = cursor := LabelledCursor.lift_map f cursor whole mappedA projection keeps the shape configuration (map_erase) and commutes with every instruction (perform_map). And a cursor on the projected tree lifts to a cursor on the full tree with the same projection (lift_map), so a computation on the projected fields can be followed on the full nodes.
36.6 Data in the nodes
The ComboBST paper allows each node to store bits of augmented data, and builds its buffers from them (Section 3). The library describes the data attached to a tree of shape t by a payload function on ranks.
/-- Render the payload attached to each physical key. The total function is asemantic representation: only the tree's finite key interval is stored. -/def label {α : Type} (data : Nat → α) : Tree → Nat → LabelledTree (Nat × α) | .nil, _ => .nil | .node l r, lo => .node (label data l lo) (lo + l.size, data (lo + l.size)) (label data r (lo + l.size + 1))Metadata.label data t lo labels the node of rank with the pair , where ranks start at lo. It is Tree.labelFrom of Chapter 1, with a payload next to each key. data is a total function on all natural numbers, but only its values on the keys of the tree appear in the result: as the docstring says, the function is a semantic representation, and only the tree’s finite key interval is stored.
/-- A labelled node carrying a given key and payload. This is structuralmembership; access permission must additionally identify the current cursor. -/inductive At {α : Type} : LabelledTree (Nat × α) → Nat → α → Prop where | root (l r : LabelledTree (Nat × α)) (x : Nat) (value : α) : At (.node l (x, value) r) x value | left {l r : LabelledTree (Nat × α)} {entry : Nat × α} {x : Nat} {value : α} : At l x value → At (.node l entry r) x value | right {l r : LabelledTree (Nat × α)} {entry : Nat × α} {x : Nat} {value : α} : At r x value → At (.node l entry r) x value/-- Replace exactly one node's payload, leaving its key and both children fixed.The contextual cases describe the location; they do not grant free navigation. -/inductive Write {α : Type} : LabelledTree (Nat × α) → Nat → α → LabelledTree (Nat × α) → Prop where | root (l r : LabelledTree (Nat × α)) (x : Nat) (old value : α) : Write (.node l (x, old) r) x value (.node l (x, value) r) | left {l l' r : LabelledTree (Nat × α)} {entry : Nat × α} {x : Nat} {value : α} : Write l x value l' → Write (.node l entry r) x value (.node l' entry r) | right {l r r' : LabelledTree (Nat × α)} {entry : Nat × α} {x : Nat} {value : α} : Write r x value r' → Write (.node l entry r) x value (.node l entry r')At t x v says that some node of t has key x and payload v. Write t x v t' says that t' is t with the payload of the node with key x replaced by v, everything else unchanged. Both are structural relations, which locate a node by its position. They do not grant access: as the docstrings warn, a structure that reads or writes a payload must have its cursor on that node, through Config.read and Config.write. The library proves (internally, in Models/Labelled/Metadata) that a write at the cursor is a Write and that a read at the cursor gives an At.
36.7 Interval fields and local routing
A ComboBST cursor does not restart at the root. It finds the next key from wherever it stands, as a lazy finger does (Chapter 15). On the pointer machine, the key of a node is its inorder rank, and computing it requires the sizes of subtrees off the cursor’s path. A real implementation must decide the direction from what is stored in the node. The library stores, in each node, its key and the half-open interval of the keys in its subtree. Three words suffice to choose the next edge toward any target.
36.7.1 The routing rule
/-- Three bounded integers read at the current node: its key and thehalf-open interval of keys in its subtree. -/structure View where low : Nat key : Nat high : Nat deriving DecidableEq/-- Semantic correctness of the locally stored interval. Computing offsetsand subtree sizes here is specification only; `choose` reads the three fields. -/def View.Valid (v : View) (cursor : Config) : Prop := v.low = offset cursor.context ∧ cursor.key? = some v.key ∧ v.high = v.low + cursor.focus.sizeA view is the three words read at the current node: low, key and high. It is valid for a cursor when low is the number of keys before the focused subtree (Pointer.offset), key is the rank under the cursor, and high is low plus the size of the focused subtree. So the subtree holds exactly the ranks in . Validity is a specification: computing offsets and sizes there is not part of the model, and the rule below reads only the three fields.
inductive Direction where | left | right | parent deriving DecidableEq/-- Local comparisons select the unique edge toward an existing target. -/def choose (v : View) (target : Nat) : Option Direction := if target = v.key then none else if v.low ≤ target ∧ target < v.high then some (if target < v.key then .left else .right) else some .parentchoose v target compares the target with the three words. It returns none if the target is the current key: the cursor has arrived. If the target is inside the interval, it goes left or right according to the key. Otherwise it goes to the parent.
/-- Follow one child or parent pointer. Pattern matching inspects only thecurrent node, whether the selected child exists, and the parent link. -/def perform : Direction → Config → Option Config | .left, ⟨.node (.node a b) r, cs⟩ => some ⟨.node a b, .left r :: cs⟩ | .right, ⟨.node l (.node a b), cs⟩ => some ⟨.node a b, .right l :: cs⟩ | .parent, ⟨.node a b, .left r :: cs⟩ => some ⟨.node (.node a b) r, cs⟩ | .parent, ⟨.node a b, .right l :: cs⟩ => some ⟨.node l (.node a b), cs⟩ | _, _ => nonedef next (v : View) (cursor : Config) (target : Nat) : Option Config := (choose v target).bind fun direction => perform direction cursorperform follows the chosen pointer, with the patterns of Pointer.Move, and fails if the child is empty or there is no parent. next chooses and then follows. The library proves (internally, in Models/Pointer/Routing) that with a valid view and a target in the tree, next makes one Pointer.Move that decreases the lazy-finger distance LazyFinger.distance to the target by exactly one, and that every move with this property is the one next chooses. The routing rule is therefore a shortest-path walk, decided locally. The tree-buffer scans of Section 39.1 state the consequence in their reading interface, for example Results.labelled_route.
36.7.2 Stored intervals
structure Bounds where low : Nat high : Nat deriving DecidableEq/-- Finite node fields describing the interval of each rooted subtree. Therecursive annotation is the representation invariant, not the routing code. -/def label : Tree → Nat → LabelledTree (Nat × Bounds) | .nil, _ => .nil | .node l r, lo => .node (label l lo) (lo + l.size, ⟨lo, lo + (Tree.node l r).size⟩) (label r (lo + l.size + 1))Bounds is a pair of words. IntervalMetadata.label t lo is the canonical annotation of a shape: the node of rank gets the label , the interval of its own subtree. The docstring says that this recursive annotation is the representation invariant, not the routing code: the routing code reads fields, and this function says what the fields should contain.
A rotation changes the intervals of exactly two subtrees, those of the two rotated nodes.
/-- A rotation updates only the promoted and demoted node fields, using keysand bounds already at those two adjacent nodes. Context fields stay untouched. -/inductive Update : LabelledTree (Nat × Bounds) → LabelledTree (Nat × Bounds) → Prop where | right (a b c : LabelledTree (Nat × Bounds)) (x y : Nat) (bx byBounds : Bounds) : Update (.node (.node a (x, bx) b) (y, byBounds) c) (.node a (x, ⟨bx.low, byBounds.high⟩) (.node b (y, ⟨x + 1, byBounds.high⟩) c)) | left (a b c : LabelledTree (Nat × Bounds)) (x y : Nat) (bx byBounds : Bounds) : Update (.node a (x, bx) (.node b (y, byBounds) c)) (.node (.node a (x, ⟨bx.low, y⟩) b) (y, ⟨bx.low, byBounds.high⟩) c) | inLeft {a b c : LabelledTree (Nat × Bounds)} {entry : Nat × Bounds} : Update a b → Update (.node a entry c) (.node b entry c) | inRight {a b c : LabelledTree (Nat × Bounds)} {entry : Nat × Bounds} : Update a b → Update (.node c entry a) (.node c entry b)Update s t relates two annotated trees when t is a rotation of s in which only the two rotated nodes get new intervals, computed from their own keys and old intervals. In the case right, the left child is promoted over . Its subtree is now the whole old subtree of , with interval , and ’s subtree now starts just after , with interval . The case left is symmetric, and inLeft, inRight place the update anywhere in the tree. The ancestors keep their intervals, because a rotation does not change the set of keys below any other node. The library proves internally that a rotation of the shape turns the canonical annotation into the canonical annotation by such an update.
/-- Read the actual key and interval words, then choose a neighboring link.The successful charge is three word reads plus one pointer move. -/def route (target : Nat) (c : LabelledCursor.Config (Nat × Bounds)) : Option (Nat × LabelledCursor.Config (Nat × Bounds)) := do let (key, bounds) ← c.read let direction ← Pointer.Routing.choose ⟨bounds.low, key, bounds.high⟩ target let next ← match direction with | .left => LabelledCursor.perform .downLeft c | .right => LabelledCursor.perform .downRight c | .parent => match c.context with | .left _ _ :: _ => LabelledCursor.perform .upLeft c | .right _ _ :: _ => LabelledCursor.perform .upRight c | [] => none return (4, next)def Canonical (c : LabelledCursor.Config (Nat × Bounds)) : Prop := c.tree = label c.tree.erase 0route target c is the routing step on an annotated labelled cursor. It reads the key and the interval at the cursor, chooses a direction with Routing.choose, and performs the corresponding labelled move. It charges units: three word reads and one pointer move. It fails if the cursor has arrived (and then nothing needs to be done) or the move is impossible. Canonical c says that every field of the whole tree is correct, that is, the tree is the canonical annotation of its shape. The library proves internally that from a canonical cursor and a target in the tree, route succeeds with cost , makes a move that brings the cursor one step closer to the target, changes no field, and leaves the cursor canonical.
36.7.3 Initializing the fields
The ComboBST theorems quantify over the old contents of the memory, fields : Nat → IntervalMetadata.Bounds: the library does not assume that the intervals are already in place. A startup traversal writes them, with one cursor and a constant number of registers.
inductive Mode where | write | left | right | up deriving DecidableEq/-- A stackless traversal: one cursor, a finite mode, and two pending boundregisters. Ancestor information remains in parent links and initialized fields. -/structure State where cursor : Pointer.Config fields : Nat → Bounds pending : Bounds mode : ModeThe state is a shape cursor, the field memory fields, indexed by key, one pending interval in two registers, and a mode. As the docstring says, the traversal is stackless: it keeps no stack of ancestors. What it needs when it returns to an ancestor is in the parent links of the zipper and in the fields that it has already written.
/-- Initialize two bound words, inspect a child link, or follow a parent link.A descent charges three word reads (key and bounds) and one pointer move;a write charges two word writes. Null-link/control checks cost one unit.As in the pointer shape model, offset plus left size denotes the stored cursorkey; its recursive evaluation is not part of this abstract word-cost model. -/def tick (s : State) : Option (Nat × State) := match s.mode, s.cursor.focus, s.cursor.context with | .write, .node l _, _ => some (2, { s with fields := Function.update s.fields (Pointer.offset s.cursor.context + l.size) s.pending, mode := .left }) | .left, .node .nil _, _ => some (1, { s with mode := .right }) | .left, .node (.node a b) r, cs => let key := Pointer.offset cs + (Tree.node a b).size some (4, ⟨⟨.node a b, .left r :: cs⟩, s.fields, ⟨(s.fields key).low, key⟩, .write⟩) | .right, .node _ .nil, _ => some (1, { s with mode := .up }) | .right, .node l (.node a b), cs => let key := Pointer.offset cs + l.size some (4, ⟨⟨.node a b, .right l :: cs⟩, s.fields, ⟨key + 1, (s.fields key).high⟩, .write⟩) | .up, .node a b, .left r :: cs => some (1, { s with cursor := ⟨.node (.node a b) r, cs⟩, mode := .right }) | .up, .node a b, .right l :: cs => some (1, { s with cursor := ⟨.node l (.node a b), cs⟩ }) | _, _, _ => noneOne tick is one step of a depth-first traversal.
write: store the pending interval in the field of the current key, at cost (two word writes), and turn to the left child.left: if there is no left child, pay for the null check and turn right. Otherwise descend, at cost : the new pending interval runs from the current node’s storedlowto the current key.right: symmetric. The new pending interval runs from the current key plus one to the storedhigh.up: climb to the parent at cost . Coming from a left child, turn to the parent’s right child; coming from a right child, keep climbing.
At the root in mode up, and at an empty tree, no case applies and the traversal halts. The current key is written Pointer.offset … + l.size. As the docstring explains, this denotes the key stored at the cursor, as in the shape model; its recursive evaluation is not part of the word-cost model.
inductive Run : State → State → Nat → Prop where | refl {s : State} : Run s s 0 | step {s t u : State} {cost rest : Nat} : tick s = some (cost, t) → Run t u rest → Run s u (cost + rest)def initial (tree : Tree) (n : Nat) (fields : Nat → Bounds) : State := ⟨⟨tree, []⟩, fields, ⟨0, n⟩, .write⟩Run s t cost is a sequence of ticks with their summed charges. initial tree n fields starts at the root, in mode write, with the pending interval and arbitrary old fields.
/-- Mathematical effect of the traversal, used only to state and prove itsoutput. Runtime child bounds are computed from local keys and stored fields. -/def populate : Tree → Nat → (Nat → Bounds) → (Nat → Bounds) | .nil, _, fields => fields | .node l r, lo, fields => populate r (lo + l.size + 1) (populate l lo (Function.update fields (lo + l.size) ⟨lo, lo + (Tree.node l r).size⟩))def work : Tree → Nat | .nil => 0 | .node l r => 2 + (if l = .nil then 1 else 5 + work l) + (if r = .nil then 1 else 5 + work r)populate is the mathematical effect of the traversal, the field memory with every key of the tree set to its canonical interval. The docstring stresses that it is used only to state the output; the running traversal computes each child’s interval from the parent’s key and stored field. work t is the total charge: per node, per missing child, and per existing child (descent and return). The library proves internally that work t + 4 = 8 |t| for a nonempty tree, and that the traversal started by initial halts at the root after cost at most , with every field of the tree equal to its canonical interval and every field of a key unchanged.
/-- A word-size invariant. The limit may be larger than the key universe toallow arbitrary old word contents; only two bounds are held in registers. -/def State.Bounded (limit : Nat) (s : State) : Prop := s.cursor.tree.size ≤ limit ∧ s.pending.low ≤ limit ∧ s.pending.high ≤ limit ∧ ∀ x, (s.fields x).low ≤ limit ∧ (s.fields x).high ≤ limitBounded limit s is a word-size invariant: the tree size, the two registers, and every stored field are at most limit. The limit may exceed , so that old memory may hold any bounded garbage. The library proves internally that every prefix of the traversal keeps this invariant if the start satisfies it.
/-- Tail-recursive bounded loop. Fuel and the accumulated charge are scalarregisters; no return stack or instruction list is retained by the controller. -/def runLoop : Nat → Nat → State → Option (Nat × State) | 0, spent, s => match tick s with | none => some (spent, s) | some _ => none | fuel + 1, spent, s => match tick s with | none => some (spent, s) | some (cost, next) => runLoop fuel (spent + cost) next/-- Execute the initializer with an explicit loop budget. -/def runFuel (fuel : Nat) (s : State) : Option (Nat × State) := runLoop fuel 0 srunFuel fuel s runs the traversal as a loop with a budget of fuel ticks and an accumulated charge, again in scalar registers only. It returns the halted state and the charge, or none if the traversal has not halted within the budget. The snapshot startup of Section 39.2 runs a variant of this loop, for nodes that carry a data word as well, with budget .
36.7.4 Maintaining the fields under rotations
A source algorithm simulated in a ComboBST tree rotates. After each rotation the two changed intervals must be rewritten, at the cursor, with a constant number of operations.
inductive Side where | left | right deriving DecidableEqdef Side.opcode : Side → Multifinger.Opcode | .left => .rotateLeftChild | .right => .rotateRightChildSide names which child is promoted: left stands for rotateLeftChild, which promotes a left child over its parent, and right for rotateRightChild.
/-- Two saved node entries occupy six scalar registers. The cursor addressesan explicitly labelled tree; the zipper represents parent links, not a stackallocated by the controller. -/structure State where cursor : LabelledCursor.Config (Nat × Bounds) child : Nat × Bounds parent : Nat × Bounds deriving DecidableEqinductive Op where | pointer (opcode : Multifinger.Opcode) | readChild | readParent | writeChild (side : Side) | writeParent (side : Side) deriving DecidableEqdef Op.moves : Op → Nat | .pointer _ => 1 | _ => 0def Op.cost : Op → Nat | .pointer _ => 1 | .readChild | .readParent => 3 | .writeChild _ | .writeParent _ => 2The state is an annotated labelled cursor and two saved node entries, child and parent, each a key and an interval: six scalar registers. An operation is a pointer instruction, a read of the current entry into child or parent, or a write of a new interval at the cursor. Op.moves counts pointer instructions, rotations included. Op.cost charges per pointer instruction, per read (key and two bounds) and per write (two bounds).
def childBounds (side : Side) (s : State) : Bounds := match side with | .left => ⟨s.child.2.low, s.parent.2.high⟩ | .right => ⟨s.parent.2.low, s.child.2.high⟩def parentBounds (side : Side) (s : State) : Bounds := match side with | .left => ⟨s.child.1 + 1, s.parent.2.high⟩ | .right => ⟨s.parent.2.low, s.child.1⟩/-- Store two interval words at the cursor, retaining the key in place. -/def writeBounds (c : LabelledCursor.Config (Nat × Bounds)) (bounds : Bounds) : Option (LabelledCursor.Config (Nat × Bounds)) := match c.focus with | .nil => none | .node l (key, _) r => some ⟨.node l (key, bounds) r, c.context⟩childBounds and parentBounds compute the new intervals of the promoted node and of the demoted one from the saved registers alone, exactly as in IntervalMetadata.Update. For left, the promoted child gets and the demoted parent ; right is symmetric. writeBounds stores an interval at the cursor and keeps the stored key.
/-- Every read and write is guarded by an existing node at the current cursor.Writes preserve its stored key and replace only the two interval words. -/def tick (op : Op) (s : State) : Option State := do match op with | .pointer opcode => return { s with cursor := ← LabelledCursor.perform opcode s.cursor } | .readChild => return { s with child := ← s.cursor.read } | .readParent => return { s with parent := ← s.cursor.read } | .writeChild side => return { s with cursor := ← writeBounds s.cursor (childBounds side s) } | .writeParent side => return { s with cursor := ← writeBounds s.cursor (parentBounds side s) }def run : List Op → State → Option State | [], s => some s | op :: ops, s => (tick op s).bind (run ops)tick executes one operation. Every operation is guarded by a node under the cursor, and writes change only the two interval words. run executes a list of operations and fails if one fails.
def program : Side → List Op | .left => [.readChild, .pointer .upLeft, .readParent, .pointer .downLeft, .pointer .rotateLeftChild, .writeChild .left, .pointer .downRight, .writeParent .left, .pointer .upRight] | .right => [.readChild, .pointer .upRight, .readParent, .pointer .downRight, .pointer .rotateRightChild, .writeChild .right, .pointer .downLeft, .writeParent .right, .pointer .upLeft]/-- The fixed program uses six word reads, four word writes, four moves,and one rotation. It begins at the child and finishes at that promoted node. -/def maintain (side : Side) (s : State) : Option State := run (program side) sprogram left is the fixed sequence: read the child’s entry, go up to the parent and read its entry, come back down, rotate, write the promoted node’s interval, step down to the demoted node, write its interval, and come back up. It starts and ends on the promoted node. maintain side runs it.
def charge (ops : List Op) : Nat := (ops.map Op.cost).sumdef pointerCount (ops : List Op) : Nat := (ops.filter fun op => match op with | .pointer _ => true | _ => false).lengthcharge adds the costs and pointerCount counts the pointer instructions of an operation list. For either program, the charge is : two reads (), two writes (), four moves and one rotation (). The library proves internally that whenever the shape rotation is legal and the fields are canonical, maintain succeeds, performs that rotation on the shape, leaves all fields canonical, and is a pointer trace of instructions. The tree-buffer nodes of Section 39.1 run this program for their rotations.
- What is charged. The interval programs charge word reads and writes, null-link checks and pointer instructions. Only pointer instructions are pointer-machine work; the others are the word costs of the paper’s augmented nodes. The ComboBST theorems of Section 29.4 state their costs in pointer instructions and requests.
- What is not charged. Lean’s evaluation of offsets and subtree sizes, which appear in the specification (
View.Valid,Canonical,populate) and, in the initialization, in the name of the current key. The docstrings say so, and the routing rules themselves read only stored fields. - No theorem in this chapter for the interval programs. Their correctness theorems (
Initialization.complete,Access.progress,Maintenance.implementand the routing lemmas) are internal. They reach the reading interface through the tree-buffer and scan theorems of Section 39.1.