Documentation

CslibFrontier.DataStructure.AVLTree.PointerMachine.Balance

Pointer-machine AVL balancing #

balance_correct proves that a finite pointer-machine program implements the existing AVLTree.balance in at most 121 instructions. It permits an arbitrary old root cache and requires height-consistent represented children. The implementation allocates no nodes; it preserves every scalar payload field except the height, and all records outside the tree.

Balance.readHeights, Balance.inChild, and Balance.heavyCase give the shared assembly blocks for cached-height selection, child reconnection, and single/double rotations.

Read the two cached child heights into scalar registers one and two.

Run a child-subtree block, reconnect its result, then return to the original parent.

def Cslib.DataStructure.AVLTree.PointerMachine.Balance.heavyCase {M : PointerMachine.Model} {extra regs : ℕ} (side : Bool) (zero maxSucc : M.Op) (le : M.Test) (field : Fin (extra + 1)) :

Handle a heavy child: compare its two child heights and perform a single or double rotation. side = true selects the left-heavy case and its final right rotation.

def Cslib.DataStructure.AVLTree.PointerMachine.balance {M : PointerMachine.Model} {extra regs : ℕ} (zero maxSucc : M.Op) (heavy le : M.Test) (field : Fin (extra + 1)) :

Balance at cursor zero using cached child/grandchild heights. heavy a b means b + 1 < a; le compares heights. Pointer register one and scalar register zero are client registers; the other declared scratch registers may change.

theorem Cslib.DataStructure.AVLTree.PointerMachine.balance_correct {M : PointerMachine.Model} {extra regs : ℕ} (zero maxSucc : M.Op) (heavy le : M.Test) (encode : ℕ → M.Value) (zero_spec : ∀ (a b : M.Value), M.evalOp zero a b = encode 0) (max_spec : ∀ (a b : ℕ), M.evalOp maxSucc (encode a) (encode b) = encode (max a b + 1)) (heavy_spec : ∀ (a b : ℕ), M.evalTest heavy (encode a) (encode b) = decide (b + 1 < a)) (le_spec : ∀ (a b : ℕ), M.evalTest le (encode a) (encode b) = decide (a ≤ b)) (field : Fin (extra + 1)) (notKey : field ≠ 0) (s : PointerMachine.State M (SearchTree.PointerMachine.layout extra (regs + 1))) (label : SearchTree.PointerMachine.Label M extra) (l r : BinaryTree (SearchTree.PointerMachine.Label M extra)) (A B : AVLTree M.Value) (parent : PointerMachine.Pointer) (rep : SearchTree.PointerMachine.Represents s.heap parent (BinaryTree.node label l r)) (distinct : SearchTree.PointerMachine.AddressesDistinct (BinaryTree.node label l r)) (ml : Matches encode field l A) (mr : Matches encode field r B) (hl : A.HeightConsistent) (hr : B.HeightConsistent) (cursor : s.ptr 0 = some label.address) (pc : s.pc = 0) :

The concrete balance program implements AVLTree.balance in at most 121 instructions, without allocation. Children must have consistent encoded caches; the old root cache may be arbitrary. Register six retains the former root for the caller's subsequent reconnection.