Encoded regular matching jobs and their RAM workspace
DefinitionBackreferenceMatching_RegularCopyJobsregular-expressionsstring-algorithmsword-ram
A matching job contains four ordinary regular expressions and two flags. The expressions constrain the prefix, the copied substring, the intervening substring, and the suffix. The flags choose the direction of the query and determine whether to test adjacent copies. Jobs are serialized consecutively, so the next job starts immediately after the four current automata. The workspace predicates and cost functions specify the array representation and the resources used to evaluate the jobs.
Definition code
import Definitions.Def_BackreferenceMatching_Algorithms
import Definitions.Def_BackreferenceMatching_Languages
import Definitions.Def_BackreferenceMatching_OneUseNormalizer
import Definitions.Def_BodlaenderKloks_TreeDecompositionPrograms
import Mathlib.Algebra.BigOperators.Group.Finset.Basic
import Mathlib.Algebra.BigOperators.Group.Finset.Sigma
import Mathlib.Algebra.BigOperators.Group.List.Basic
import Mathlib.Algebra.BigOperators.Intervals
import Mathlib.Algebra.Order.BigOperators.Group.Finset
import Mathlib.Algebra.Ring.Fin
import Mathlib.Computability.NFA
import Mathlib.Data.Finset.Card
import Mathlib.Data.Fintype.EquivFin
import Mathlib.Data.Fintype.Option
import Mathlib.Data.Fintype.Powerset
import Mathlib.Data.Fintype.Prod
import Mathlib.Data.Fintype.Sum
import Mathlib.Data.LawfulXor.Basic
import Mathlib.Data.List.Basic
import Mathlib.Data.List.FinRange
import Mathlib.Data.List.Lex
import Mathlib.Data.List.Nodup
import Mathlib.Data.List.PeriodicityLemma
import Mathlib.Data.List.Rotate
import Mathlib.Data.Nat.Bitwise
import Mathlib.Data.Nat.Log
import Mathlib.Logic.Equiv.Fin.Basic
import Mathlib.Order.Interval.Finset.Fin
import Mathlib.Tactic
import Mathlib.Tactic.Linarith
import Mathlib.Tactic.Positivity
import Mathlib.Tactic.Ring
import Mathlib.Data.Finset.Sort
import Mathlib.Computability.RegularExpressions
import Mathlib.Data.Nat.Bits
import Mathlib.Data.Fintype.Basic
import Mathlib.Tactic.DeriveFintype
import Mathlib.Algebra.Polynomial.Eval.Defs
import Mathlib.Data.Set.Basic
import Mathlib.Data.List.Infix
import Mathlib.Data.List.Count
import Mathlib.Tactic.Tauto
import Mathlib.Data.Nat.Find
import Definitions.Def_BackreferenceMatching_TextIndexWorkspace
set_option autoImplicit false
set_option maxHeartbeats 6000000
set_option maxRecDepth 60000
set_option linter.unusedSimpArgs false
set_option linter.unusedTactic false
set_option linter.unnecessarySeqFocus false
noncomputable section
namespace BackreferenceMatching.RangeProduct
end BackreferenceMatching.RangeProduct
namespace BackreferenceMatching.Repetition.IndexRAM
end BackreferenceMatching.Repetition.IndexRAM
-- BackreferenceMatching.ReadOnly
section
open scoped Computability
namespace BackreferenceMatching
variable {q : ℕ}
def embedReg : Reg q → Expr q
| .zero => .zero
| .epsilon => .eps
| .char a => .letter a
| .plus e f => .alt (embedReg e) (embedReg f)
| .comp e f => .seq (embedReg e) (embedReg f)
| .star e => .star (embedReg e)
end BackreferenceMatching
end
-- BackreferenceMatching.PrefixSyntax
section
namespace BackreferenceMatching
variable {q : ℕ}
def rename (names : ℕ → ℕ) : Expr q → Expr q
| .zero => .zero
| .eps => .eps
| .letter a => .letter a
| .alt e f => .alt (rename names e) (rename names f)
| .seq e f => .seq (rename names e) (rename names f)
| .star e => .star (rename names e)
| .capture x e => .capture (names x) (rename names e)
| .read x => .read (names x)
/-- Read a single prefix-coded syntax tree. The unconsumed suffix is the next
tree, or the subject word. Fuel bounds the nesting depth. -/
def parseExpr (q : ℕ) : ℕ → List ℕ → Option (Expr q × List ℕ)
| 0, _ => none
| _+1, 0 :: t => some (.zero,t)
| _+1, 1 :: t => some (.eps,t)
| _+1, 2 :: a :: t => if h : a<q then some (.letter ⟨a,h⟩,t) else none
| f+1, 3 :: t => do
let (e,r) ← parseExpr q f t
let (h,s) ← parseExpr q f r
return (.alt e h,s)
| f+1, 4 :: t => do
let (e,r) ← parseExpr q f t
let (h,s) ← parseExpr q f r
return (.seq e h,s)
| f+1, 5 :: t => do
let (e,r) ← parseExpr q f t
return (.star e,r)
| f+1, 6 :: x :: t => do
let (e,r) ← parseExpr q f t
return (.capture x e,r)
| _+1, 7 :: x :: t => some (.read x,t)
| _+1, _ => none
theorem parseExpr_code (xs : List ℕ) (e : Expr q) (fuel : ℕ) (rest : List ℕ)
(hf : e.size ≤ fuel) :
parseExpr q fuel (exprCodeWith xs e ++ rest) = some (rename xs.idxOf e,rest) := by
induction e generalizing fuel rest with
| zero | eps | letter _ | read _ =>
cases fuel <;> simp_all [Expr.size,exprCodeWith,parseExpr,rename]
| star e ih | capture _ e ih =>
cases fuel with
| zero => simp [Expr.size] at hf
| succ f =>
have hh : e.size ≤ f := by simp [Expr.size] at hf; omega
simp [exprCodeWith,parseExpr,rename,ih f rest hh]
| alt e h ih₁ ih₂ | seq e h ih₁ ih₂ =>
cases fuel with
| zero => simp [Expr.size] at hf
| succ f =>
have he : e.size ≤ f := by simp [Expr.size] at hf; omega
have hh : h.size ≤ f := by simp [Expr.size] at hf; omega
simp [exprCodeWith,parseExpr,rename,List.append_assoc,ih₁ _ _ he,ih₂ _ _ hh]
def asReg : Expr q → Option (Reg q)
| .zero => some .zero
| .eps => some .epsilon
| .letter a => some (.char a)
| .alt e f => return .plus (← asReg e) (← asReg f)
| .seq e f => return .comp (← asReg e) (← asReg f)
| .star e => return .star (← asReg e)
| .capture _ _ | .read _ => none
@[simp] theorem asReg_embed (r : Reg q) : asReg (embedReg r) = some r := by
induction r <;> simp_all [asReg,embedReg]
@[simp] theorem rename_embed (f : ℕ → ℕ) (r : Reg q) : rename f (embedReg r) = embedReg r := by
induction r <;> simp_all [rename,embedReg]
theorem embed_code (xs : List ℕ) (r : Reg q) : exprCodeWith xs (embedReg r) = regCode r := by
induction r <;> simp_all [embedReg,exprCodeWith,regCode]
theorem embed_size (r : Reg q) : (embedReg r).size = regSize r := by
induction r <;> simp_all [embedReg,regSize,Expr.size]
def parseReg (q fuel : ℕ) (input : List ℕ) : Option (Reg q × List ℕ) := do
let (e,rest) ← parseExpr q fuel input
return (← asReg e,rest)
theorem parseReg_code (r : Reg q) (fuel : ℕ) (rest : List ℕ) (h : regSize r ≤ fuel) :
parseReg q fuel (regCode r ++ rest) = some (r,rest) := by
have h' := parseExpr_code ([] : List ℕ) (embedReg r) fuel rest (by simpa [embed_size] using h)
rw [embed_code,rename_embed] at h'
simp [parseReg,h']
end BackreferenceMatching
end
-- BackreferenceMatching.PositionAutomaton
section
namespace BackreferenceMatching
variable {q : ℕ}
def suffixes (r : Reg q) (rs : List (Reg q)) : List (Reg q) :=
rs.map (fun t => RegularExpression.comp t r)
/-- Partial derivatives keep alternatives separate when consuming one letter. -/
def front : Reg q → Fin q → List (Reg q)
| .zero, _ | .epsilon, _ => []
| .char b, a => if b = a then [.epsilon] else []
| .plus e f, a => front e a ++ front f a
| .comp e f, a => suffixes f (front e a) ++ (if e.matchEpsilon then front f a else [])
| .star e, a => suffixes e.star (front e a)
/-- One continuation for each literal position. The same continuation may occur twice. -/
def support : Reg q → List (Reg q)
| .zero | .epsilon => []
| .char _ => [.epsilon]
| .plus e f => support e ++ support f
| .comp e f => suffixes f (support e) ++ support f
| .star e => suffixes e.star (support e)
def positions (r : Reg q) := r :: support r
abbrev Position (r : Reg q) := Fin (positions r).length
def startPosition (r : Reg q) : Position r := ⟨0,by simp [positions]⟩
def continuation (r : Reg q) (i : Position r) : Reg q := (positions r).get i
def positionNFA (r : Reg q) : NFA (Fin q) (Position r) where
start := {startPosition r}
accept := {i | (continuation r i).matchEpsilon}
step i a := {j | continuation r j ∈ front (continuation r i) a}
end BackreferenceMatching
end
-- BackreferenceMatching.PositionMatcher
section
namespace BackreferenceMatching.PositionMatcher
variable {q : ℕ}
theorem regCode_injective : Function.Injective (regCode (q := q)) := by
intro r s h
let fuel := max (regSize r) (regSize s)
have hr := parseReg_code r fuel [] (le_max_left ..)
have hs := parseReg_code s fuel [] (le_max_right ..)
rw [h,hs] at hr
exact (Prod.mk.inj (Option.some.inj hr)).1.symm
def edge (r : Reg q) (i : Position r) (a : Fin q) (j : Position r) : Bool :=
(front (continuation r i) a).any (fun t => regCode t == regCode (continuation r j))
theorem edge_iff (r : Reg q) (i : Position r) (a : Fin q) (j : Position r) :
edge r i a j = true ↔ j ∈ (positionNFA r).step i a := by
change (front (continuation r i) a).any _ = true ↔ continuation r j ∈ front (continuation r i) a
rw [List.any_eq_true]
constructor
· rintro ⟨t,ht,he⟩
have h : regCode t = regCode (continuation r j) := by simpa using he
rwa [regCode_injective h] at ht
· intro h
exact ⟨_,h,by simp⟩
end BackreferenceMatching.PositionMatcher
end
-- BackreferenceMatching.RangeProduct
section
namespace BackreferenceMatching.RangeProduct
variable {M : Type} [Monoid M]
def product (xs : List M) (i n : ℕ) := ((xs.drop i).take n).prod
end BackreferenceMatching.RangeProduct
end
-- BackreferenceMatching.TransitionQueries
section
namespace BackreferenceMatching.Automata
/-- Boolean transition matrices, written as relations so the specification
also applies before a numbering of the finite states has been chosen. -/
structure Transition (σ : Type) where
entry : σ → σ → Prop
namespace Transition
variable {σ α : Type}
@[ext] theorem ext {u v : Transition σ} (eq : ∀ i j, u.entry i j ↔ v.entry i j) : u=v := by
cases u with
| mk a =>
cases v with
| mk b =>
exact congrArg Transition.mk (funext fun i => funext fun j => propext (eq i j))
instance : Monoid (Transition σ) where
one := ⟨fun i j => i=j⟩
mul u v := ⟨fun i j => ∃ t, u.entry i t ∧ v.entry t j⟩
one_mul u := by
ext i j
change (∃ t, i=t ∧ u.entry t j) ↔ _
simp
mul_one u := by
ext i j
change (∃ t, u.entry i t ∧ t=j) ↔ _
simp
mul_assoc u v z := by
ext i j
change (∃ t, (∃ a, u.entry i a ∧ v.entry a t) ∧ z.entry t j) ↔ ∃ a, u.entry i a ∧ ∃ t, v.entry a t ∧ z.entry t j
constructor
· rintro ⟨t,⟨a,x,y⟩,k⟩; exact ⟨a,x,t,y,k⟩
· rintro ⟨a,x,t,y,k⟩; exact ⟨t,⟨a,x,y⟩,k⟩
def letter (M : NFA α σ) (c : α) : Transition σ := ⟨fun i j => j∈M.step i c⟩
theorem product_path (M : NFA α σ) (w : List α) (i j : σ) :
(w.map (letter M)).prod.entry i j ↔ j∈M.evalFrom {i} w := by
induction w generalizing i j with
| nil => simp only [List.map_nil,List.prod_nil,NFA.evalFrom_nil,Set.mem_singleton_iff]; exact eq_comm
| cons a w ih =>
simp only [List.map_cons,List.prod_cons,NFA.evalFrom_cons,NFA.stepSet_singleton]
change (∃ t, t∈M.step i a ∧ _) ↔ _
constructor
· rintro ⟨t,first,rest⟩
exact M.mem_evalFrom_iff_exists.mpr ⟨t,first,(ih t j).mp rest⟩
· intro path
obtain ⟨t,first,rest⟩ := M.mem_evalFrom_iff_exists.mp path
exact ⟨t,first,(ih t j).mpr rest⟩
end Transition
end BackreferenceMatching.Automata
end
-- BackreferenceMatching.PatternContinuationProgram
section
namespace BackreferenceMatching.Functional
open Lax689794Proofs.Fun ToVal
variable {q : ℕ}
def selected : Reg q → Bool → ℕ → List (Reg q)
| .zero,_,_ | .epsilon,_,_ => []
| .char ch,m,a => if m && decide (ch.val≠a) then [] else [.epsilon]
| .plus x y,m,a => selected x m a++selected y m a
| .comp x y,m,a => suffixes y (selected x m a)++(if m && !x.matchEpsilon then [] else selected y m a)
| .star x,m,a => suffixes x.star (selected x m a)
end BackreferenceMatching.Functional
end
-- BackreferenceMatching.PatternRowProgram
section
namespace BackreferenceMatching.Functional
open Lax689794Proofs.Fun ToVal
variable {q : ℕ}
def memberBit (xs : List (Reg q)) (r : Reg q) := xs.any (fun s => regCode s==regCode r)
def rowBits (xs : List (Reg q)) (a : ℕ) (r : Reg q) :=
xs.map (fun t => (memberBit (selected r true a) t).toNat)
def letterRows (xs : List (Reg q)) (a : ℕ) := xs.flatMap (rowBits xs a)
end BackreferenceMatching.Functional
end
-- BackreferenceMatching.PatternTablesProgram
section
namespace BackreferenceMatching.Functional
open Lax689794Proofs.Fun ToVal
variable {q : ℕ}
def finals (xs : List (Reg q)) := xs.map fun x => x.matchEpsilon.toNat
def transitionWords (r : Reg q) := (List.range q).flatMap (letterRows (positions r))
def patternWords (r : Reg q) := (positions r).length::(finals (positions r)++transitionWords r)
end BackreferenceMatching.Functional
end
-- BackreferenceMatching.BooleanReduction
section
namespace BackreferenceMatching.ArrayRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning
def anyBody (e : Lax808846Proofs.Imp.Expr) := Com.assign "accepted" (.or (.var "accepted") e)
def anyCode (limit : String) (e : Lax808846Proofs.Imp.Expr) :=
Com.seq (.assign "accepted" (.lit 0)) (forRange "testIndex" limit (anyBody e))
end BackreferenceMatching.ArrayRAM
end
-- BackreferenceMatching.BooleanMatrices
section
namespace BackreferenceMatching.Automata
/-- Each row is a materialized Boolean vector. Matrix multiplication inspects
at most n entries for each of its n² output cells. -/
structure BitMatrix (n : ℕ) where
rows : Vector (Vector Bool n) n
namespace BitMatrix
variable {n : ℕ}
def bit (m : BitMatrix n) (i j : Fin n) := (m.rows[i.val])[j.val]
def ofFn (f : Fin n → Fin n → Bool) : BitMatrix n := ⟨Vector.ofFn (fun i => Vector.ofFn (f i))⟩
@[simp] theorem bit_ofFn (f : Fin n → Fin n → Bool) (i j : Fin n) : (ofFn f).bit i j=f i j := by
simp [bit,ofFn]
def relation (m : BitMatrix n) : Transition (Fin n) := ⟨fun i j => m.bit i j=true⟩
theorem injective : Function.Injective (relation (n := n)) := by
rintro ⟨x⟩ ⟨y⟩ eq
congr 1
apply Vector.ext; intro i h
apply Vector.ext; intro j k
let a : Fin n := ⟨i,h⟩
let b : Fin n := ⟨j,k⟩
have P := congrArg (fun (m : Transition (Fin n)) => m.entry a b) eq
change (x[i][j]=true)=(y[i][j]=true) at P
cases X : x[i][j] <;> cases Y : y[i][j] <;> simp_all
def identity (n : ℕ) : BitMatrix n := ofFn fun i j => decide (i=j)
def multiply (a b : BitMatrix n) : BitMatrix n := ofFn fun i j =>
(List.finRange n).any (fun k => a.bit i k && b.bit k j)
theorem identity_relation : (identity n).relation=1 := by
ext i j; simp [identity,relation]; rfl
theorem multiply_relation (a b : BitMatrix n) : (multiply a b).relation=a.relation*b.relation := by
ext i j
change (multiply a b).bit i j=true ↔ ∃ k, a.bit i k=true ∧ b.bit k j=true
simp [multiply,List.any_eq_true]
instance : Monoid (BitMatrix n) where
one := identity n
mul := multiply
one_mul a := injective (by change (multiply (identity n) a).relation=a.relation; rw [multiply_relation,identity_relation,one_mul])
mul_one a := injective (by change (multiply a (identity n)).relation=a.relation; rw [multiply_relation,identity_relation,mul_one])
mul_assoc a b c := injective (by change (multiply (multiply a b) c).relation=(multiply a (multiply b c)).relation; simp only [multiply_relation,mul_assoc])
def toRelation : BitMatrix n →* Transition (Fin n) where
toFun := relation
map_one' := identity_relation
map_mul' := multiply_relation
def letterBits {q : ℕ} (r : Reg q) (a : Fin q) : BitMatrix (positions r).length :=
ofFn (fun i j => PositionMatcher.edge r i a j)
theorem letter_relation {q : ℕ} (r : Reg q) (a : Fin q) :
(letterBits r a).relation=Transition.letter (positionNFA r) a := by
ext i j
simpa only [relation,letterBits,bit_ofFn,Transition.letter] using PositionMatcher.edge_iff r i a j
theorem range_bits {q : ℕ} (r : Reg q) (w : Word q) (i m : ℕ) (s t : Position r) :
(RangeProduct.product (w.map (letterBits r)) i m).bit s t=true ↔
t∈(positionNFA r).evalFrom {s} ((w.drop i).take m) := by
let word := (w.drop i).take m
have rel : ((word.map (letterBits r)).prod).relation=(word.map (Transition.letter (positionNFA r))).prod := by
change toRelation _=_
rw [map_list_prod]
simp only [List.map_map,Function.comp_def,toRelation,MonoidHom.coe_mk,OneHom.coe_mk,letter_relation]
have view := congrArg (fun (M : Transition (Position r)) => M.entry s t) rel
rw [←Transition.product_path (positionNFA r)]
simpa only [RangeProduct.product,List.map_take,List.map_drop,word,relation] using Iff.of_eq view
end BitMatrix
end BackreferenceMatching.Automata
end
-- BackreferenceMatching.MatrixCellMachine
section
namespace BackreferenceMatching.Automata.MatrixRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
def getBit (bank base row col : String) : Lax808846Proofs.Imp.Expr :=
.get bank (.add (.add (.var base) (.mul (.var row) (.var "dim"))) (.var col))
def productBit (a b : String) := Lax808846Proofs.Imp.Expr.and
(getBit a "leftBase" "matrixI" "testIndex") (getBit b "rightBase" "testIndex" "matrixJ")
def productCell (a b : String) := anyCode "dim" (productBit a b)
end BackreferenceMatching.Automata.MatrixRAM
end
-- BackreferenceMatching.MatrixProductMachine
section
namespace BackreferenceMatching.Automata.MatrixRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
def matrixCoords : Com := .seq (.assign "matrixI" (.div (.var "cellIndex") (.var "dim")))
(.assign "matrixJ" (.sub (.var "cellIndex") (.mul (.var "matrixI") (.var "dim"))))
def writeProduct (dst : String) : Com := .store dst (.add (.var "outputBase") (.var "cellIndex")) (.var "accepted")
def multiplyBody (a b dst : String) := Com.seq matrixCoords (.seq (productCell a b) (writeProduct dst))
def multiplyCode (a b dst : String) := forRange "cellIndex" "cells" (multiplyBody a b dst)
end BackreferenceMatching.Automata.MatrixRAM
end
-- BackreferenceMatching.MatrixBlocks
section
namespace BackreferenceMatching.Automata.MatrixRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
def indexFrom (name : String) := Lax808846Proofs.Imp.Expr.add (.var name) (.var "index")
def moveBlock (src dst : String) := tabulate dst (indexFrom "targetPtr") (.get src (indexFrom "sourcePtr"))
def equalBit (e f : Lax808846Proofs.Imp.Expr) := Lax808846Proofs.Imp.Expr.sub (.lit 1) (.add (.sub e f) (.sub f e))
end BackreferenceMatching.Automata.MatrixRAM
end
-- BackreferenceMatching.PatternPorts
section
namespace BackreferenceMatching.Automata.MatrixRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open BackreferenceMatching.Functional
def readHeader (q : ℕ) : Com :=
.seq (.assign "dim" (.get "returnWords" (.var "patternPtr")))
(.seq (.assign "cells" (.mul (.var "dim") (.var "dim")))
(.seq (.assign "length" (.var "cells"))
(.seq (.assign "transBase" (.add (.add (.var "patternPtr") (.lit 1)) (.var "dim")))
(.assign "nextPatternPtr" (.add (.var "transBase") (.mul (.lit q) (.var "cells")))))))
end BackreferenceMatching.Automata.MatrixRAM
end
-- BackreferenceMatching.NullablePortMachine
section
namespace BackreferenceMatching.Automata.MatrixRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open BackreferenceMatching.Functional
def nullableEntry : Lax808846Proofs.Imp.Expr :=
.get "returnWords" (.add (.add (.var "patternPtr") (.lit 1)) (.var "index"))
def copyNullable (dst : String) : Com := .seq (.assign "length" (.var "dim")) (tabulate dst (.var "index") nullableEntry)
end BackreferenceMatching.Automata.MatrixRAM
end
-- BackreferenceMatching.TextMatrixMachine
section
namespace BackreferenceMatching.Automata.MatrixRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
def expandEntry (dict : String) : Lax808846Proofs.Imp.Expr :=
let i := Lax808846Proofs.Imp.Expr.var "index"
let c := Lax808846Proofs.Imp.Expr.var "cells"
let atWord := Lax808846Proofs.Imp.Expr.div i c
let within := Lax808846Proofs.Imp.Expr.sub i (.mul atWord c)
.get dict (.add (.add (.var "transBase") (.mul (.get "letters" atWord) c)) within)
def expandText (dict dst : String) : Com :=
.seq (.assign "length" (.mul (.var "textSize") (.var "cells")))
(.seq (tabulate dst (.var "index") (expandEntry dict)) (.assign "length" (.var "cells")))
end BackreferenceMatching.Automata.MatrixRAM
end
-- BackreferenceMatching.MatrixIdentityMachine
section
namespace BackreferenceMatching.Automata.MatrixRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
def diagonalBit : Lax808846Proofs.Imp.Expr :=
let i := Lax808846Proofs.Imp.Expr.var "index"
let row := Lax808846Proofs.Imp.Expr.div i (.var "dim")
let col := Lax808846Proofs.Imp.Expr.sub i (.mul row (.var "dim"))
equalBit row col
def identityCode (bank : String) := tabulate bank (indexFrom "targetPtr") diagonalBit
end BackreferenceMatching.Automata.MatrixRAM
end
-- BackreferenceMatching.RangeMatrixIndex
section
namespace BackreferenceMatching.Automata.MatrixRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open BackreferenceMatching.RangeProduct
structure RangeBanks where
letters : String
left : String
right : String
unit : String
def tableEntry (pos : String) := Lax808846Proofs.Imp.Expr.mul (.add (.var "rowOffset") (.var pos)) (.var "cells")
def rangeCoordinates : Com :=
.seq (.assign "lastCell" (.sub (.var "rangeStop") (.lit 1)))
(.seq (.assign "rowOffset" (.mul (.get "logs" (.xor (.var "rangeStart") (.var "lastCell"))) (.var "textSize")))
(.seq (.assign "leftBase" (tableEntry "rangeStart"))
(.seq (.assign "rightBase" (tableEntry "lastCell")) (.assign "outputBase" (.lit 0)))))
end BackreferenceMatching.Automata.MatrixRAM
end
-- BackreferenceMatching.RangeQueryMachine
section
namespace BackreferenceMatching.Automata.MatrixRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open BackreferenceMatching.RangeProduct
abbrev Term := Lax808846Proofs.Imp.Expr
def copyAt (src dst : String) (a b : Term) : Com :=
.seq (.assign "sourcePtr" a) (.seq (.assign "targetPtr" b) (moveBlock src dst))
def queryProduct (banks : RangeBanks) (dst : String) : Com :=
.seq rangeCoordinates (multiplyCode banks.left banks.right dst)
def rangeQuery (banks : RangeBanks) (dst : String) : Com :=
.ite (.eq (.var "rangeStart") (.var "rangeStop")) (copyAt banks.unit dst (.lit 0) (.lit 0))
(.ite (.eq (.add (.var "rangeStart") (.lit 1)) (.var "rangeStop"))
(copyAt banks.letters dst (.mul (.var "rangeStart") (.var "cells")) (.lit 0)) (queryProduct banks dst))
def queryTime (d : ℕ) := (28*d+100)*(d*d+1)+70
end BackreferenceMatching.Automata.MatrixRAM
end
-- BackreferenceMatching.MatrixAccumulate
section
namespace BackreferenceMatching.Automata.MatrixRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
def productAt (left right target : String) (a b : Term) : Com :=
.seq (.assign "leftBase" a) (.seq (.assign "rightBase" b)
(.seq (.assign "outputBase" (.lit 0)) (multiplyCode left right target)))
def scanProduct (forward : Bool) (letters acc tmp : String) : Com :=
if forward then productAt acc letters tmp (.lit 0) (.var "letterBase")
else productAt letters acc tmp (.var "letterBase") (.lit 0)
end BackreferenceMatching.Automata.MatrixRAM
end
-- BackreferenceMatching.RangeScanCoordinates
section
namespace BackreferenceMatching.Automata.MatrixRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open BackreferenceMatching.RangeProduct
def scanPosition (forward : Bool) : Lax808846Proofs.Imp.Expr :=
if forward then .var "scanIndex" else .sub (.sub (.var "textSize") (.lit 1)) (.var "scanIndex")
def scanCoordinates (forward : Bool) : Com :=
.seq (.assign "scanPos" (scanPosition forward))
(.seq (.assign "halfway" (.add (.mul (.div (.var "scanPos") (.var "blockWidth")) (.var "blockWidth")) (.var "halfWidth")))
(.seq (.assign "letterBase" (.mul (.var "scanPos") (.var "cells")))
(.assign "rowAddress" (.mul (.add (.var "levelBase") (.var "scanPos")) (.var "cells")))))
end BackreferenceMatching.Automata.MatrixRAM
end
-- BackreferenceMatching.RangeRowUpdate
section
namespace BackreferenceMatching.Automata.MatrixRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open BackreferenceMatching.RangeProduct
structure ScanBanks where
letters : String
unit : String
acc : String
tmp : String
out : String
def halfGuard (forward : Bool) : Cond :=
if forward then .lt (.var "halfway") (.add (.var "scanPos") (.lit 1)) else .lt (.var "scanPos") (.var "halfway")
def multiplyAcc (dir : Bool) (b : ScanBanks) : Com :=
.seq (scanProduct dir b.letters b.acc b.tmp) (copyAt b.tmp b.acc (.lit 0) (.lit 0))
def updateCode (dir : Bool) (b : ScanBanks) : Com :=
.ite (halfGuard dir) (multiplyAcc dir b) (copyAt b.unit b.acc (.lit 0) (.lit 0))
def updateTime (d : ℕ) := ((28*d+31)*(d*d)+12)+(10+16*(d*d))+8
end BackreferenceMatching.Automata.MatrixRAM
end
-- BackreferenceMatching.RangeRowMachine
section
namespace BackreferenceMatching.Automata.MatrixRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open BackreferenceMatching.RangeProduct
def storeEntry (b : ScanBanks) := copyAt b.acc b.out (.lit 0) (.var "rowAddress")
def rowBody (dir : Bool) (b : ScanBanks) : Com := .seq (scanCoordinates dir) (.seq (updateCode dir b) (storeEntry b))
def rowStepTime (d : ℕ) := 30+updateTime d+(10+16*(d*d))
end BackreferenceMatching.Automata.MatrixRAM
end
-- BackreferenceMatching.RangeRowLoop
section
namespace BackreferenceMatching.Automata.MatrixRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open BackreferenceMatching.RangeProduct
def runRow (dir : Bool) (b : ScanBanks) : Com :=
.seq (copyAt b.unit b.acc (.lit 0) (.lit 0)) (forRange "scanIndex" "textSize" (rowBody dir b))
def rowTime (d n : ℕ) := (10+16*(d*d))+((rowStepTime d+8)*n+6)
end BackreferenceMatching.Automata.MatrixRAM
end
-- BackreferenceMatching.RangeLevelMachine
section
namespace BackreferenceMatching.Automata.MatrixRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
def makeScan (b : RangeBanks) (acc tmp : String) (forward : Bool) : ScanBanks :=
⟨b.letters,b.unit,acc,tmp,if forward then b.right else b.left⟩
def rowPair (b : RangeBanks) (acc tmp : String) :=
Com.seq (runRow false (makeScan b acc tmp false)) (runRow true (makeScan b acc tmp true))
end BackreferenceMatching.Automata.MatrixRAM
end
-- BackreferenceMatching.RangeBuildMachine
section
namespace BackreferenceMatching.Automata.MatrixRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
structure TableLimits (B n d : ℕ) : Prop where
dim : d < B
square : d*d < B
wide : n+2*logCapacity n+2 < B
rows : (n.log2+1)*n < B
space : (n.log2+1)*n*(d*d) < B
def setLevelData : Com :=
.seq (.assign "blockWidth" (.add (.var "halfWidth") (.var "halfWidth")))
(.assign "levelBase" (.mul (.var "rangeLevel") (.var "textSize")))
def buildBody (b : RangeBanks) (acc tmp : String) : Com :=
.seq setLevelData (.seq (rowPair b acc tmp) (.assign "halfWidth" (.var "blockWidth")))
def buildStepTime (d n : ℕ) := 2*rowTime d n+10
def buildIndex (b : RangeBanks) (acc tmp : String) : Com :=
.seq (.assign "rangeLevels" (.add (.get "logs" (.var "textSize")) (.lit 1)))
(.seq (.assign "halfWidth" (.lit 1)) (forRange "rangeLevel" "rangeLevels" (buildBody b acc tmp)))
def buildTime (d n : ℕ) := (buildStepTime d n+8)*(n.log2+1)+14
end BackreferenceMatching.Automata.MatrixRAM
end
-- BackreferenceMatching.PatternPreparation
section
namespace BackreferenceMatching.Automata.MatrixRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open BackreferenceMatching.Functional
def indexedPattern (q : ℕ) (b : RangeBanks) (acc tmp nulls : String) : Com :=
.seq (readHeader q) (.seq (copyNullable nulls) (.seq (expandText "returnWords" b.letters)
(.seq (.assign "targetPtr" (.lit 0)) (.seq (identityCode b.unit) (buildIndex b acc tmp)))))
def patternIndexTime (d n : ℕ) := 25+(16*d+8)+(31*(n*(d*d))+14)+2+(40*(d*d)+6)+buildTime d n
end BackreferenceMatching.Automata.MatrixRAM
end
-- BackreferenceMatching.UnaryPowerAutomata
section
namespace BackreferenceMatching.Repetition
open Automata
variable {α S : Type}
def phase (d i : ℕ) : Fin (d+1) := ⟨i%(d+1),Nat.mod_lt _ (by omega)⟩
end BackreferenceMatching.Repetition
end
-- BackreferenceMatching.UnaryBitTables
section
namespace BackreferenceMatching.Repetition
open Automata
structure UnaryBits (S : Type) where
start : S → Bool
accept : S → Bool
edge : S → S → Bool
first : S → Bool
empty : Bool
namespace UnaryBits
variable {S T : Type}
def append (U : UnaryBits S) (V : UnaryBits T) : UnaryBits (S ⊕ T) where
start | .inl x => U.start x | .inr _ => false
accept | .inl x => U.accept x && V.empty | .inr t => V.accept t
edge
| .inl x,.inl y => U.edge x y
| .inl x,.inr y => U.accept x && V.first y
| .inr _,.inl _ => false
| .inr x,.inr y => V.edge x y
first | .inl x => U.first x | .inr y => U.empty && V.first y
empty := U.empty && V.empty
def stretch [DecidableEq S] (U : UnaryBits S) (d : ℕ) : UnaryBits (Fin (d+1) × S) where
start p := decide (p.1=phase d 0) && U.start p.2
accept p := decide (p.1=phase d 0) && U.accept p.2
edge s t := decide (t.1=phase d (s.1.val+1)) &&
(if s.1.val=d then U.edge s.2 t.2 else decide (t.2=s.2))
first t := decide (t.1=phase d 1) && (if d=0 then U.first t.2 else U.start t.2)
empty := U.empty
end UnaryBits
end BackreferenceMatching.Repetition
end
-- BackreferenceMatching.BlockBitTables
section
namespace BackreferenceMatching.Repetition
open Automata
variable {q : ℕ}
def blockBits (r : Reg q) (pre root post : BitMatrix (positions r).length) : UnaryBits (Position r) :=
let initial := fun j => pre.bit (startPosition r) j
let accept := Vector.ofFn fun i => (List.finRange (positions r).length).any
(fun j => post.bit i j && (continuation r j).matchEpsilon)
let first := Vector.ofFn fun j => (List.finRange (positions r).length).any (fun i => initial i && root.bit i j)
⟨initial,fun i => accept[i.val],root.bit,fun i => first[i.val],
(List.finRange (positions r).length).any (fun i => initial i && accept[i.val])⟩
def MatrixReads (r : Reg q) (M : BitMatrix (positions r).length) (w : Word q) :=
∀ i j : Position r, M.bit i j=true ↔ j∈(positionNFA r).evalFrom {i} w
end BackreferenceMatching.Repetition
end
-- BackreferenceMatching.MatrixRangeIndex
section
namespace BackreferenceMatching.Repetition
open Automata
variable {q : ℕ}
structure MatrixRangeIndex (r : Reg q) (w : Word q) where
fetch : ℕ → ℕ → BitMatrix (positions r).length
valid : ∀ i m, MatrixReads r (fetch i m) ((w.drop i).take m)
namespace MatrixRangeIndex
def accepts (r : Reg q) (P : BitMatrix (positions r).length) : Bool :=
(List.finRange (positions r).length).any fun j => P.bit (startPosition r) j && (continuation r j).matchEpsilon
def emptyRepeat (x y z : Reg q) (w : Word q) (X : MatrixRangeIndex x w) (Z : MatrixRangeIndex z w) :=
y.matchEpsilon && (List.range (w.length+1)).any (fun i => accepts x (X.fetch 0 i) && accepts z (Z.fetch i w.length))
end MatrixRangeIndex
end BackreferenceMatching.Repetition
end
-- BackreferenceMatching.NativeRangeAccess
section
namespace BackreferenceMatching.Automata.MatrixRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open BackreferenceMatching.RangeProduct
structure PatternPort where
banks : RangeBanks
width : String
nulls : String
def xPort : PatternPort := ⟨⟨"matrixLettersX","rangeLeftX","rangeRightX","unitX"⟩,"widthX","nullX"⟩
def yPort : PatternPort := ⟨⟨"matrixLettersY","rangeLeftY","rangeRightY","unitY"⟩,"widthY","nullY"⟩
def zPort : PatternPort := ⟨⟨"matrixLettersZ","rangeLeftZ","rangeRightZ","unitZ"⟩,"widthZ","nullZ"⟩
def directIndex {q : ℕ} (r : Reg q) (w : Word q) : Repetition.MatrixRangeIndex r w :=
⟨RangeProduct.product (w.map (BitMatrix.letterBits r)),BitMatrix.range_bits r w⟩
def selectSize (width : String) : Com := .seq (.assign "dim" (.var width))
(.seq (.assign "cells" (.mul (.var "dim") (.var "dim"))) (.assign "length" (.var "cells")))
def fetchInterval (p : PatternPort) (a b dst : String) : Com :=
.seq (.assign "rangeStart" (.var a)) (.seq (.assign "rangeStop" (.var b)) (.seq (selectSize p.width) (rangeQuery p.banks dst)))
end BackreferenceMatching.Automata.MatrixRAM
end
-- BackreferenceMatching.PatternSlots
section
namespace BackreferenceMatching.Automata.MatrixRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open BackreferenceMatching.Functional
def installPort (q : ℕ) (p : PatternPort) : Com :=
.seq (indexedPattern q p.banks "rangeAcc" "rangeScratch" p.nulls)
(.seq (.assign p.width (.get "returnWords" (.var "patternPtr"))) (.assign "patternPtr" (.var "nextPatternPtr")))
def installationTime (d n : ℕ) := patternIndexTime d n+5
end BackreferenceMatching.Automata.MatrixRAM
end
-- BackreferenceMatching.TriplePatternMachine
section
namespace BackreferenceMatching.Automata.MatrixRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open BackreferenceMatching.Functional
def patternCapacity (n d : ℕ) := (n.log2+1)*n*(d*d)+d*d+d
end BackreferenceMatching.Automata.MatrixRAM
end
-- BackreferenceMatching.WordSelection
section
namespace BackreferenceMatching.ArrayRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning
/-- A fixed decision tree of native word expressions. Evaluating a leaf only
reads the operands on the selected path. -/
inductive WordSelection where
| value : Lax808846Proofs.Imp.Expr → WordSelection
| branch : Cond → WordSelection → WordSelection → WordSelection
namespace WordSelection
def write (x : String) : WordSelection → Com
| .value e => .assign x e
| .branch c l r => .ite c (l.write x) (r.write x)
end WordSelection
end BackreferenceMatching.ArrayRAM
end
-- BackreferenceMatching.LocalPowerMatcher
section
namespace BackreferenceMatching.Repetition
open Automata
variable {q : ℕ}
abbrev LocalState (x y z : Reg q) (d : ℕ) :=
Position x ⊕ ((Fin (d+1) × Position y) ⊕ Position z)
end BackreferenceMatching.Repetition
end
-- BackreferenceMatching.LocalPowerTransitions
section
namespace BackreferenceMatching.Repetition
open Automata
variable {q : ℕ}
abbrev PhaseFree (x y z : Reg q) := Position x ⊕ (Position y ⊕ Position z)
def enterPhase {x y z : Reg q} (d j : ℕ) : PhaseFree x y z → LocalState x y z d
| .inl a => .inl a
| .inr (.inl b) => .inr (.inl (phase d j,b))
| .inr (.inr c) => .inr (.inr c)
def nextPhase {x y z : Reg q} {d : ℕ} : LocalState x y z d → ℕ
| .inr (.inl (p,_)) => p.val+1
| _ => 1
end BackreferenceMatching.Repetition
end
-- BackreferenceMatching.SparseUnaryScan
section
namespace BackreferenceMatching.Repetition
namespace SparseUnary
variable {S : Type} {n k : ℕ}
/-- Each source has k candidate destinations. The flag decides which
of these edges to insert into the next frontier. -/
def mark (next : Vector Bool n) (choices : List (Fin n × Bool)) : Vector Bool n :=
choices.foldl (fun xs v => if v.2 then xs.set v.1.val true else xs) next
def choices (active : Vector Bool n) (dest : Fin n → Fin k → Fin n) (edge : Fin n → Fin n → Bool) (i : Fin n) :=
if active[i.val] then (List.finRange k).map (fun a => (dest i a,edge i (dest i a))) else []
def scan (active : Vector Bool n) (dest : Fin n → Fin k → Fin n) (edge : Fin n → Fin n → Bool) : Vector Bool n :=
(List.finRange n).foldl (fun next i => mark next (choices active dest edge i)) (Vector.replicate n false)
def evaluate (U : UnaryBits S) (E : S ≃ Fin n) (dest : Fin n → Fin k → Fin n) (iters : ℕ) : Bool :=
let start := Vector.ofFn fun i => U.start (E.symm i)
let edge := fun i j => U.edge (E.symm i) (E.symm j)
let finish := (fun v => scan v dest edge)^[iters] start
(List.finRange n).any (fun i => finish[i.val] && U.accept (E.symm i))
end SparseUnary
end BackreferenceMatching.Repetition
end
-- BackreferenceMatching.RecordDecision
section
namespace BackreferenceMatching.Repetition
open Automata
variable {q : ℕ}
def stateCount (x y z : Reg q) (d : ℕ) :=
(positions x).length+((d+1)*(positions y).length+(positions z).length)
def candidateCount (x y z : Reg q) :=
(positions x).length+((positions y).length+(positions z).length)
def numberStates (x y z : Reg q) (d : ℕ) : LocalState x y z d ≃ Fin (stateCount x y z d) :=
(Equiv.sumCongr (Equiv.refl _) ((Equiv.sumCongr finProdFinEquiv (Equiv.refl _)).trans finSumFinEquiv)).trans finSumFinEquiv
def numberCandidates (x y z : Reg q) : PhaseFree x y z ≃ Fin (candidateCount x y z) :=
(Equiv.sumCongr (Equiv.refl _) finSumFinEquiv).trans finSumFinEquiv
def localBits (x y z : Reg q) (d : ℕ) (w : Word q) (r : PowerRecord)
(X : MatrixRangeIndex x w) (Y : MatrixRangeIndex y w) (Z : MatrixRangeIndex z w) :=
let A := blockBits x (X.fetch 0 r.start) (X.fetch r.start r.period) 1
let B := blockBits y 1 (Y.fetch r.start r.period) 1
let C := blockBits z 1 (Z.fetch r.start r.period) (Z.fetch (r.start+r.exponent*r.period) w.length)
A.append ((B.stretch d).append C)
def recordDest (x y z : Reg q) (d : ℕ) (i : Fin (stateCount x y z d)) (t : Fin (candidateCount x y z)) :=
let E := numberStates x y z d
E (enterPhase d (nextPhase (E.symm i)) ((numberCandidates x y z).symm t))
def runRecord (x y z : Reg q) (d : ℕ) (w : Word q) (r : PowerRecord)
(X : MatrixRangeIndex x w) (Y : MatrixRangeIndex y w) (Z : MatrixRangeIndex z w) : Bool :=
SparseUnary.evaluate (localBits x y z d w r X Y Z) (numberStates x y z d) (recordDest x y z d) r.exponent
def decideRecords (x y z : Reg q) (d : ℕ) (w : Word q) (D : PowerIndex w)
(X : MatrixRangeIndex x w) (Y : MatrixRangeIndex y w) (Z : MatrixRangeIndex z w) : Bool :=
MatrixRangeIndex.emptyRepeat x y z w X Z || (records D).any (fun r => runRecord x y z d w r X Y Z)
end BackreferenceMatching.Repetition
end
-- BackreferenceMatching.CoordinateMachine
section
namespace BackreferenceMatching.Repetition.IndexRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM
abbrev E := Lax808846Proofs.Imp.Expr
def coordCase (a b c : E) : WordSelection :=
.branch (.lt (.var "coordinateKey") (.var "widthX")) (.value a)
(.branch (.lt (.var "coordinateKey") (.var "yBoundary")) (.value b) (.value c))
def coordTag := coordCase (.lit 0) (.lit 1) (.lit 2)
def relIndex := Lax808846Proofs.Imp.Expr.sub (.var "coordinateKey") (.var "widthX")
def quotient := Lax808846Proofs.Imp.Expr.div relIndex (.var "widthY")
def coordPos := coordCase (.var "coordinateKey") (.sub relIndex (.mul quotient (.var "widthY")))
(.sub (.var "coordinateKey") (.var "yBoundary"))
def coordPhase := coordCase (.lit 0) quotient (.lit 0)
def decodeCode : Com := .seq (coordTag.write "decodedTag") (.seq (coordPos.write "decodedPos") (coordPhase.write "decodedPhase"))
end BackreferenceMatching.Repetition.IndexRAM
end
-- BackreferenceMatching.CompactMemory
section
namespace BackreferenceMatching.Repetition.IndexRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.Automata.MatrixRAM
variable {q : ℕ} {x y z : Reg q}
def tagChoice (key : String) (a b c : WordSelection) : WordSelection :=
.branch (.eq (.var key) (.lit 0)) a (.branch (.eq (.var key) (.lit 1)) b c)
def vec (key pos : String) : E := .get key (.var pos)
def headBit (key : String) : E := .get key (.lit 0)
def mat (key dim : String) : E := .get key (.add (.mul (.var "fromPos") (.var dim)) (.var "decodedPos"))
def isZero (key : String) := equalBit (.var key) (.lit 0)
def samePos := equalBit (.var "decodedPos") (.var "fromPos")
def falseBit : WordSelection := .value (.lit 0)
end BackreferenceMatching.Repetition.IndexRAM
end
-- BackreferenceMatching.RecordCoordinateRead
section
namespace BackreferenceMatching.Repetition.IndexRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM
def decodeFrom (key endKey : String) : Com :=
.seq (.assign "coordinateKey" (.var key)) (.seq (.assign "yBoundary" (.var endKey)) decodeCode)
def preserveSource : Com := .seq (.assign "fromTag" (.var "decodedTag"))
(.seq (.assign "fromPos" (.var "decodedPos")) (.assign "fromPhase" (.var "decodedPhase")))
def decodeSource (key : String) : Com := .seq (decodeFrom key "stateBoundary") preserveSource
variable {q d B : ℕ} {x y z : Reg q}
end BackreferenceMatching.Repetition.IndexRAM
end
-- BackreferenceMatching.NetworkLayoutMachine
section
namespace BackreferenceMatching.Repetition.IndexRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM
def setNetwork : Com :=
.seq (.assign "phaseLimit" (.sub (.var "count") (.lit 1)))
(.seq (.assign "stateBoundary" (.add (.var "widthX") (.mul (.var "count") (.var "widthY"))))
(.seq (.assign "plainBoundary" (.add (.var "widthX") (.var "widthY")))
(.seq (.assign "length" (.add (.var "stateBoundary") (.var "widthZ")))
(.seq (.assign "choiceCount" (.add (.var "plainBoundary") (.var "widthZ")))
(.assign "edgeCount" (.mul (.var "length") (.var "choiceCount")))))))
structure NetworkLimits {q : ℕ} (B d : ℕ) (x y z : Reg q) : Prop where
count : d+1 < B
two : 2 < B
x2 : (positions x).length*(positions x).length < B
y2 : (positions y).length*(positions y).length < B
z2 : (positions z).length*(positions z).length < B
states : stateCount x y z d < B
candidates : candidateCount x y z < B
cells : stateCount x y z d*candidateCount x y z < B
end BackreferenceMatching.Repetition.IndexRAM
end
-- BackreferenceMatching.MatchContext
section
namespace BackreferenceMatching.Repetition.IndexRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open BackreferenceMatching.Automata BackreferenceMatching.Automata.MatrixRAM
structure MatchLimits {q : ℕ} (B C d : ℕ) (x y z : Reg q) (n : ℕ) : Prop where
first : TableLimits B n (positions x).length
middle : TableLimits B n (positions y).length
last : TableLimits B n (positions z).length
net : NetworkLimits B d x y z
xRoom : (positions x).length*(positions x).length ≤ C
yRoom : (positions y).length*(positions y).length ≤ C
zRoom : (positions z).length*(positions z).length ≤ C
stateRoom : stateCount x y z d+stateCount x y z d*candidateCount x y z ≤ C
end BackreferenceMatching.Repetition.IndexRAM
end
-- BackreferenceMatching.TerminalImageMachine
section
namespace BackreferenceMatching.Automata.MatrixRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
def terminalBit (matrix finals : String) : Lax808846Proofs.Imp.Expr :=
.and (.get matrix (.add (.mul (.var "imageIndex") (.var "dim")) (.var "testIndex"))) (.get finals (.var "testIndex"))
def imageBody (matrix finals dst : String) := Com.seq (anyCode "dim" (terminalBit matrix finals))
(.store dst (.var "imageIndex") (.var "accepted"))
def imageCode (matrix finals dst : String) := forRange "imageIndex" "dim" (imageBody matrix finals dst)
end BackreferenceMatching.Automata.MatrixRAM
end
-- BackreferenceMatching.EmptySplitMachine
section
namespace BackreferenceMatching.Repetition.IndexRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open BackreferenceMatching.Automata BackreferenceMatching.Automata.MatrixRAM
def testInterval (p : PatternPort) (a b : String) : Com :=
.seq (fetchInterval p a b "splitMatrix") (.seq (.assign "imageIndex" (.lit 0))
(.seq (.assign "dim" (.var p.width)) (anyCode "dim" (terminalBit "splitMatrix" p.nulls))))
def splitBody : Com :=
.seq (testInterval xPort "origin" "splitIndex") (.seq (.assign "leftMatch" (.var "accepted"))
(.seq (testInterval zPort "splitIndex" "textSize") (.assign "accepted" (.and (.var "leftMatch") (.var "accepted")))))
def splitTime (a b : ℕ) := queryTime a+21*a+queryTime b+21*b+54
end BackreferenceMatching.Repetition.IndexRAM
end
-- BackreferenceMatching.WeightedDisjunction
section
namespace BackreferenceMatching.ArrayRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning
def collectAnswer (idx limit acc output : String) (body : Com) :=
forRange idx limit (.seq body (.assign acc (.or (.var acc) (.var output))))
end BackreferenceMatching.ArrayRAM
end
-- BackreferenceMatching.EmptyRepeatMachine
section
namespace BackreferenceMatching.Repetition.IndexRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open BackreferenceMatching.Automata BackreferenceMatching.Automata.MatrixRAM
def nullDecision : Com := .assign "decision" (.and (.get "nullY" (.lit 0)) (.var "decision"))
def emptyScan : Com := .seq (.assign "splitCount" (.add (.var "textSize") (.lit 1)))
(.seq (.assign "decision" (.lit 0)) (.seq (collectAnswer "splitIndex" "splitCount" "decision" "accepted" splitBody) nullDecision))
def emptyTime (sx sz n : ℕ) := (splitTime sx sz+12)*(n+1)+19
end BackreferenceMatching.Repetition.IndexRAM
end
-- BackreferenceMatching.RecordLocations
section
namespace BackreferenceMatching.Repetition.IndexRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
def loadLocation : Com :=
.seq (.assign "recordStart" (.get "savedStart" (.var "recordIndex")))
(.seq (.assign "period" (.get "savedPeriod" (.var "recordIndex")))
(.seq (.assign "exponent" (.get "savedExponent" (.var "recordIndex")))
(.seq (.assign "rootEnd" (.add (.var "recordStart") (.var "period")))
(.assign "recordEnd" (.add (.var "recordStart") (.mul (.var "exponent") (.var "period")))))))
end BackreferenceMatching.Repetition.IndexRAM
end
-- BackreferenceMatching.RecordQueries
section
namespace BackreferenceMatching.Repetition.IndexRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open BackreferenceMatching.Automata BackreferenceMatching.Automata.MatrixRAM
variable {q : ℕ}
def fetchP := fetchInterval xPort "origin" "recordStart" "prefixX"
def fetchX := fetchInterval xPort "recordStart" "rootEnd" "rootX"
def fetchY := fetchInterval yPort "recordStart" "rootEnd" "rootY"
def fetchZ := fetchInterval zPort "recordStart" "rootEnd" "rootZ"
def fetchT := fetchInterval zPort "recordEnd" "textSize" "suffixMatrix"
def recordQueries := Com.seq fetchP (.seq fetchX (.seq fetchY (.seq fetchZ fetchT)))
def queryCost (a b c : ℕ) := 2*queryTime a+queryTime b+2*queryTime c+60
end BackreferenceMatching.Repetition.IndexRAM
end
-- BackreferenceMatching.DestinationMachine
section
namespace BackreferenceMatching.Repetition.IndexRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM
def slotChoice := tagChoice "fromTag" (.value (.lit 1))
(.branch (.eq (.var "fromPhase") (.var "phaseLimit")) (.value (.lit 0)) (.value (.add (.var "fromPhase") (.lit 1))))
(.value (.lit 1))
def destChoice := tagChoice "decodedTag" (.value (.var "decodedPos"))
(.value (.add (.var "widthX") (.add (.var "decodedPos") (.mul (.var "widthY") (.var "slotNumber")))))
(.value (.add (.var "stateBoundary") (.var "decodedPos")))
def destinationCode : Com := .seq (slotChoice.write "slotNumber") (destChoice.write "destinationNo")
variable {q B d : ℕ} {x y z : Reg q} {s : Env}
end BackreferenceMatching.Repetition.IndexRAM
end
-- BackreferenceMatching.CompactFlags
section
namespace BackreferenceMatching.Repetition.IndexRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.Automata.MatrixRAM
def startChoice := tagChoice "fromTag" (.value (vec "prefixX" "fromPos")) falseBit falseBit
def finalChoice := tagChoice "fromTag"
(.value (.and (vec "nullX" "fromPos") (.and (headBit "nullY") (headBit "suffixZ"))))
(.value (.and (.and (isZero "fromPhase") (vec "nullY" "fromPos")) (headBit "suffixZ")))
(.value (vec "suffixZ" "fromPos"))
def xTargets := tagChoice "decodedTag"
(.value (mat "rootX" "widthX"))
(.value (.and (vec "nullX" "fromPos") (isZero "decodedPos")))
(.value (.and (vec "nullX" "fromPos") (.and (headBit "nullY") (vec "rootZ" "decodedPos"))))
def yTargets := tagChoice "decodedTag" falseBit
(.branch (.eq (.var "fromPhase") (.var "phaseLimit")) (.value (mat "rootY" "widthY")) (.value samePos))
(.value (.and (.and (isZero "fromPhase") (vec "nullY" "fromPos")) (vec "rootZ" "decodedPos")))
def zTargets := tagChoice "decodedTag" falseBit falseBit (.value (mat "rootZ" "widthZ"))
def gateChoice := tagChoice "fromTag" xTargets yTargets zTargets
variable {q B d : ℕ} {x y z : Reg q} {s : Env}
end BackreferenceMatching.Repetition.IndexRAM
end
-- BackreferenceMatching.RecordEdgeCoordinates
section
namespace BackreferenceMatching.Repetition.IndexRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM
def flatCode : Com := .seq (.assign "sourceNo" (.div (.var "itemIndex") (.var "choiceCount")))
(.assign "candidateNo" (.sub (.var "itemIndex") (.mul (.var "sourceNo") (.var "choiceCount"))))
variable {q B d : ℕ} {x y z : Reg q}
def decodePair : Com := .seq flatCode (.seq (decodeSource "sourceNo") (decodeFrom "candidateNo" "plainBoundary"))
end BackreferenceMatching.Repetition.IndexRAM
end
-- BackreferenceMatching.RecordColumns
section
namespace BackreferenceMatching.Repetition.IndexRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
def stateKernel (final : Bool) := Com.seq (decodeSource "itemIndex") ((if final then finalChoice else startChoice).write "emitWord")
def stateBank (final : Bool) := if final then "final" else "active"
def stateProgram (final : Bool) := computedMap (stateKernel final) (stateBank final) "length" "emitWord"
def edgeKernel (destination : Bool) := Com.seq decodePair (if destination then destinationCode else gateChoice.write "edgeOn")
def edgeBank (destination : Bool) := if destination then "destination" else "enabled"
def edgeField (destination : Bool) := if destination then "destinationNo" else "edgeOn"
def edgeProgram (destination : Bool) := computedMap (edgeKernel destination) (edgeBank destination) "edgeCount" (edgeField destination)
def sourceProgram := computedMap flatCode "source" "edgeCount" "sourceNo"
variable {q B d : ℕ} {x y z : Reg q}
end BackreferenceMatching.Repetition.IndexRAM
end
-- BackreferenceMatching.FrontierScatter
section
namespace BackreferenceMatching.Repetition.FrontierRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM
open BackreferenceMatching.SubstringIndex.RadixMachine
def scatterBody : Com :=
let idx := Lax808846Proofs.Imp.Expr.var "edgeIndex"
let src := Lax808846Proofs.Imp.Expr.get "source" idx
let target := Lax808846Proofs.Imp.Expr.get "destination" idx
let bit := Lax808846Proofs.Imp.Expr.and (.get "active" src) (.get "enabled" idx)
.store "marked" target (.or (.get "marked" target) bit)
def scatterCode := forRange "edgeIndex" "edgeCount" scatterBody
end BackreferenceMatching.Repetition.FrontierRAM
end
-- BackreferenceMatching.FrontierMachine
section
namespace BackreferenceMatching.Repetition.FrontierRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
def clearMarked := tabulate "marked" (.var "index") (.lit 0)
def advanceCode := Com.seq clearMarked (.seq scatterCode (copyRange "marked" "active"))
def repeatCode := forRange "round" "exponent" advanceCode
end BackreferenceMatching.Repetition.FrontierRAM
end
-- BackreferenceMatching.RecordFrontierMachine
section
namespace BackreferenceMatching.Repetition.FrontierRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
def readFinal := Lax808846Proofs.Imp.Expr.and (.get "active" (.var "testIndex")) (.get "final" (.var "testIndex"))
def runMachine := Com.seq repeatCode (anyCode "length" readFinal)
end BackreferenceMatching.Repetition.FrontierRAM
end
-- BackreferenceMatching.CompactNetworkMachine
section
namespace BackreferenceMatching.Repetition.IndexRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine FrontierRAM
variable {q B d : ℕ} {x y z : Reg q}
def networkCode := Com.seq (stateProgram false) (.seq (stateProgram true) (.seq sourceProgram (.seq (edgeProgram true) (edgeProgram false))))
def networkTime (n m : ℕ) := 242*n+443*m+30
end BackreferenceMatching.Repetition.IndexRAM
end
-- BackreferenceMatching.EvaluateRecord
section
namespace BackreferenceMatching.Repetition.IndexRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open BackreferenceMatching.Automata BackreferenceMatching.Automata.MatrixRAM FrontierRAM
variable {q : ℕ}
def makeSuffix : Com := .seq (.assign "dim" (.var "widthZ")) (imageCode "suffixMatrix" "nullZ" "suffixZ")
def evaluateRecord := Com.seq recordQueries (.seq makeSuffix (.seq setNetwork (.seq networkCode runMachine)))
def evaluateTime (sx sy sz n k e : ℕ) := queryCost sx sy sz+((21*sz+19)*sz+8)+28+
networkTime n (n*k)+((23*n+22*(n*k)+26)*e+16*n+14)
end BackreferenceMatching.Repetition.IndexRAM
end
-- BackreferenceMatching.RecordedDisjunction
section
namespace BackreferenceMatching.Repetition.IndexRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open BackreferenceMatching.Automata BackreferenceMatching.Automata.MatrixRAM
def recordBody := Com.seq loadLocation evaluateRecord
def testRecords := collectAnswer "recordIndex" "numRecords" "decision" "accepted" recordBody
def recordLimit (n : ℕ) := 4*(n+1)*(n.log2+1)
def testTime (sx sy sz n k len : ℕ) :=
(32+evaluateTime sx sy sz n k 0+(23*n+22*(n*k)+26))*recordLimit len+6
end BackreferenceMatching.Repetition.IndexRAM
end
-- BackreferenceMatching.AdjacentCopyMachine
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Repetition Repetition.IndexRAM
variable {q : ℕ}
def adjacentCode := Com.seq emptyScan testRecords
def adjacentTime {q : ℕ} (A E D : Reg q) (n : ℕ) :=
emptyTime (positions A).length (positions D).length n+testTime (positions A).length (positions E).length (positions D).length
(stateCount A E D 1) (candidateCount A E D) n
noncomputable def adjacentBit (A E D : Reg q) (w : Word q) := decideRecords A E D 1 w (suffixPowerIndex w)
(directIndex A w) (directIndex E w) (directIndex D w)
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.BoundaryHistories
section
namespace BackreferenceMatching.SubstringIndex.BoundaryHistory
variable {α σ : Type}
/-- Read a block from right to left starting in its terminal state. -/
def back (δ : α → σ → σ) : List α → σ → σ
| [],z => z
| c::w,z => δ c (back δ w z)
variable {m : ℕ}
end BackreferenceMatching.SubstringIndex.BoundaryHistory
end
-- BackreferenceMatching.DecoratedSuffixes
section
namespace BackreferenceMatching.SubstringIndex.BoundaryHistory
variable {m q : ℕ}
/-- The boundary state comes before the next base letter. State and letter
slots alternate, including one final state even for the empty string. -/
def weave (δ : Fin q → Fin m → Fin m) : Word q → Fin m → List ℕ
| [],z => [z.val]
| a::w,z => (δ a (back δ w z)).val::(m+a.val)::weave δ w z
end BackreferenceMatching.SubstringIndex.BoundaryHistory
end
-- BackreferenceMatching.DecoratedOccurrences
section
namespace BackreferenceMatching.SubstringIndex.BoundaryHistory
variable {q m : ℕ}
def colour (c : Fin m) : Fin (m+q) := ⟨c.val,by have := c.isLt; omega⟩
def letter (a : Fin q) : Fin (m+q) := ⟨m+a.val,Nat.add_lt_add_left a.isLt _⟩
def decorate (δ : Fin q → Fin m → Fin m) : Word q → Fin m → Word (m+q)
| [],z => [colour z]
| a::w,z => colour (δ a (back δ w z))::letter a::decorate δ w z
end BackreferenceMatching.SubstringIndex.BoundaryHistory
end
-- BackreferenceMatching.OrderedPrefixRange
section
namespace BackreferenceMatching.SubstringIndex.LabelSearch
/-- The count of entries in an initial segment of a sorted array. -/
def boundary (ok : ℕ → Bool) : ℕ → ℕ
| 0 => 0
| n+1 => if ok n then n+1 else boundary ok n
variable {α : Type} [LinearOrder α]
def Bounds (N : ℕ) (suffixes : ℕ → List α) (pat : List α) :=
(boundary (fun j => decide ((suffixes j).take pat.length < pat)) N,
boundary (fun j => decide ((suffixes j).take pat.length ≤ pat)) N)
end BackreferenceMatching.SubstringIndex.LabelSearch
end
-- BackreferenceMatching.WaveletRanges
section
namespace BackreferenceMatching.SubstringIndex.Wavelet
def low (p : ℕ) (w : List ℕ) := w.filter (· < p)
def high (p : ℕ) (w : List ℕ) := (w.filter (p ≤ ·)).map (·-p)
def rearrange (p : ℕ) (w : List ℕ) := low p w++high p w
def zeros (p : ℕ) (w : List ℕ) (i : ℕ) := (low p (w.take i)).length
/-- At a level only two prefix counts and a row offset are looked up. -/
def below : ℕ → List ℕ → ℕ → ℕ → ℕ → ℕ
| 0,_,a,b,y => if y=0 then 0 else b-a
| h+1,w,a,b,y =>
let p := 2^h
let za := zeros p w a
let zb := zeros p w b
if y < p then below h (rearrange p w) za zb y
else
let start := (low p w).length
zb-za+below h (rearrange p w) (start+(a-za)) (start+(b-zb)) (y-p)
end BackreferenceMatching.SubstringIndex.Wavelet
end
-- BackreferenceMatching.RectangleQueries
section
namespace BackreferenceMatching.SubstringIndex.Wavelet
def rectangle (h : ℕ) (w : List ℕ) (a b lo hi : ℕ) :=
decide (below h w a b lo < below h w a b hi)
end BackreferenceMatching.SubstringIndex.Wavelet
end
-- BackreferenceMatching.WeightedGroups
section
namespace BackreferenceMatching.SubstringIndex
/-- Sizes and offsets of pieces sent to the same parent context. Pieces of zero size consume no leaf ranks. -/
def groupMass (key size : ℕ → ℕ) (endPos color : ℕ) :=
∑ j ∈ Finset.range endPos, if key j=color then size j else 0
end BackreferenceMatching.SubstringIndex
end
-- BackreferenceMatching.LayerGapIntervals
section
namespace BackreferenceMatching.SubstringIndex.LayerGap
open BoundaryHistory
variable {α : Type}
def pointWeight (terminal c : ℕ) := if c=terminal then 1 else 0
/-- Number of legal gap ends below this state in the layered backward automaton. -/
def weight (δ : α → ℕ → ℕ) (m terminal : ℕ) : List α → ℕ → ℕ
| [],c => pointWeight terminal c
| a::w,c => pointWeight terminal c+groupMass (δ a) (weight δ m terminal w) m c
def descend (δ : α → ℕ → ℕ) (m terminal : ℕ) (a : α) (w : List α) (atRank : ℕ → ℕ) (v : ℕ) :=
atRank (δ a v)+pointWeight terminal (δ a v)+groupMass (δ a) (weight δ m terminal w) v (δ a v)
end BackreferenceMatching.SubstringIndex.LayerGap
end
-- BackreferenceMatching.LayerGapRanks
section
namespace BackreferenceMatching.SubstringIndex.LayerGap
variable {α : Type}
def rootOffset (size : ℕ → ℕ) (c : ℕ) := ∑ u∈Finset.range c,size u
end BackreferenceMatching.SubstringIndex.LayerGap
end
-- BackreferenceMatching.LayerGapTables
section
namespace BackreferenceMatching.SubstringIndex.LayerGap
variable {α : Type}
def positionsAt (δ : α → ℕ → ℕ) (m terminal : ℕ) : List α → (ℕ → ℕ) → ℕ → (ℕ → ℕ)
| _,pos,0 => pos
| [],pos,_+1 => pos
| a::w,pos,x+1 => positionsAt δ m terminal w (descend δ m terminal a w pos) x
def widths (δ : α → ℕ → ℕ) (m terminal : ℕ) (w : List α) (x : ℕ) := weight δ m terminal (w.drop x)
def startsAt (δ : α → ℕ → ℕ) (m terminal : ℕ) (w : List α) :=
positionsAt δ m terminal w (rootOffset (weight δ m terminal w))
end BackreferenceMatching.SubstringIndex.LayerGap
end
-- BackreferenceMatching.SuffixRectangles
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries
open BoundaryHistory
variable {q m : ℕ}
noncomputable def label {Q : ℕ} (w : Word Q) (k : ℕ) := (w.drop (startAt w k)).map Fin.val
def gapCoordinate (n : ℕ) (pos : ℕ → ℕ) (raw : ℕ) := if raw%2=0 then pos (raw/2) else n+1
noncomputable def pointRow {Q : ℕ} (w : Word Q) (n : ℕ) (pos : ℕ → ℕ) : List ℕ :=
List.ofFn (fun k : Fin (w.length+1) => gapCoordinate n pos (startAt w k.val))
noncomputable def hitRectangle (δ : Fin q → Fin m → Fin m) (z : Fin m) (C : Fin q → ℕ → ℕ) (M f : ℕ)
(w t : Word q) (x c : ℕ) (u : Fin m) : Bool :=
let a := decorate δ w z
let order := LabelSearch.Bounds (a.length+1) (label a) (weave δ t u)
let coords := pointRow a w.length (fun j => LayerGap.startsAt C M f w j f)
let lower := LayerGap.startsAt C M f w x c
Wavelet.rectangle ((w.length+1).log2+1) coords order.1 order.2 lower (lower+LayerGap.widths C M f w x c)
end BackreferenceMatching.SubstringIndex.ContextQueries
end
-- BackreferenceMatching.ResidualMasks
section
namespace BackreferenceMatching.Automata.ResidualMask
open SubstringIndex.BoundaryHistory
def pack : ℕ → (ℕ → Bool) → ℕ
| 0,_ => 0
| n+1,f => Nat.bit (f 0) (pack n (fun i => f (i+1)))
theorem pack_bound (n : ℕ) (f : ℕ → Bool) : pack n f < 2^n := by
induction n generalizing f with
| zero => exact Nat.zero_lt_one
| succ n ih =>
have smaller := ih (fun i => f (i+1))
cases h : f 0 <;> simp [pack,h,Nat.bit,pow_succ] <;> omega
def encode {n : ℕ} (f : Fin n → Bool) : Fin (2^n) :=
⟨pack n (fun i => if h : i < n then f ⟨i,h⟩ else false),pack_bound ..⟩
def preimage {n : ℕ} (A : BitMatrix n) (z : ℕ) : Fin (2^n) :=
encode (fun i => (List.finRange n).any (fun j => A.bit i j && z.testBit j.val))
def finalMask {q : ℕ} (r : Reg q) := encode (fun i : Position r => (continuation r i).matchEpsilon)
def letterMask {q : ℕ} (r : Reg q) (a : Fin q) (u : Fin (2^(positions r).length)) := preimage (BitMatrix.letterBits r a) u.val
end BackreferenceMatching.Automata.ResidualMask
end
-- BackreferenceMatching.RegexRectangles
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries
open BoundaryHistory Automata.ResidualMask
variable {q : ℕ}
def maskCount (r : Reg q) := 2^(positions r).length
def natStep (r : Reg q) (a : Fin q) (v : ℕ) := (preimage (Automata.BitMatrix.letterBits r a) v).val
noncomputable def regRectangle (C D : Reg q) (w t : Word q) (x : ℕ) : Bool :=
(List.finRange (maskCount C)).any fun c => c.val.testBit (startPosition C).val &&
(List.finRange (maskCount D)).any fun u => u.val.testBit (startPosition D).val &&
hitRectangle (letterMask D) (finalMask D) (natStep C) (maskCount C) (finalMask C).val w t x c.val u
end BackreferenceMatching.SubstringIndex.ContextQueries
end
-- BackreferenceMatching.BranchShortMatcher
section
namespace BackreferenceMatching.SubstringIndex
open Repetition
variable {q : ℕ}
structure BranchIndices (p : Branch q) (w : Word q) where
first : MatrixRangeIndex p.first w
copy : MatrixRangeIndex p.copy w
middle : MatrixRangeIndex p.middle w
last : MatrixRangeIndex p.last w
def segmentBit {w : Word q} {r : Reg q} (idx : MatrixRangeIndex r w) (i m : ℕ) := MatrixRangeIndex.accepts r (idx.fetch i m)
noncomputable def shortCandidate {p : Branch q} {w : Word q} (X : BranchIndices p w) (i j l : ℕ) : Bool :=
decide (i+l ≤ j ∧ j+l ≤ w.length ∧ l ≤ rankLCE w i j) &&
segmentBit X.first 0 i && segmentBit X.copy i l && segmentBit X.middle (i+l) (j-(i+l)) && segmentBit X.last (j+l) w.length
noncomputable def shortMatcher {p : Branch q} {w : Word q} (X : BranchIndices p w) :=
let coordinates := List.range (w.length+1)
coordinates.any fun i => coordinates.any fun j => coordinates.any fun l => shortCandidate X i j l
end BackreferenceMatching.SubstringIndex
end
-- BackreferenceMatching.CartesianGeometry
section
namespace BackreferenceMatching.SubstringIndex
noncomputable section
def cutLow (v : ℕ → ℕ) (n k : ℕ) := k-leftReach v n k
def lightStart (v : ℕ → ℕ) (n k : ℕ) := if leftReach v n k ≤ rightReach v n k then cutLow v n k else k+1
def lightCount (v : ℕ → ℕ) (n k : ℕ) := min (leftReach v n k+1) (rightReach v n k+1)
def lightRanks (v : ℕ → ℕ) (n k : ℕ) := List.range' (lightStart v n k) (lightCount v n k)
end
end BackreferenceMatching.SubstringIndex
end
-- BackreferenceMatching.BranchCutDecision
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries
variable {q : ℕ}
noncomputable def cutScan (w : Word q) (accept : ℕ → ℕ → Bool) : Bool :=
(List.range w.length).any fun k => (lightRanks (heightAt w) w.length k).any fun r => accept (startAt w r) (heightAt w k)
noncomputable def candidate (A B C D : Reg q) (w : Word q) (i l : ℕ) : Bool :=
decide (i+l ≤ w.length) && A.rmatch (w.take i) && B.rmatch (slice w i l) && regRectangle C D w (slice w i l) (i+l)
noncomputable def scanOriented (backwards : Bool) (A B C D : Reg q) (w : Word q) :=
cutScan w fun h l =>
if backwards then decide (h+l ≤ w.length) && candidate A B C D w.reverse (w.length-(h+l)) l
else candidate A B C D w h l
end BackreferenceMatching.SubstringIndex.ContextQueries
end
-- BackreferenceMatching.PatternPacketProgram
section
namespace BackreferenceMatching.Functional
open Lax689794Proofs.Fun ToVal
def packetWords {q : ℕ} (dir keep : ℕ) (A E D C : Reg q) :=
let a := patternWords A
let e := patternWords E
let d := patternWords D
let c := patternWords C
[dir,keep,a.length,e.length,d.length,c.length]++(a++(e++(d++c)))
end BackreferenceMatching.Functional
end
-- BackreferenceMatching.BranchPlan
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Functional
variable {q : ℕ}
structure BranchJob (q : ℕ) where
backwards : Bool
adjacent : Bool
first : Reg q
copy : Reg q
middle : Reg q
last : Reg q
def BranchJob.words (j : BranchJob q) := packetWords j.backwards.toNat j.adjacent.toNat j.first j.copy j.last j.middle
noncomputable def BranchJob.check (j : BranchJob q) (w : Word q) :=
(j.adjacent && adjacentBit j.first j.copy j.last w) || scanOriented j.backwards j.first j.copy j.middle j.last w
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.JobPacketAccess
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata.MatrixRAM Functional
variable {q : ℕ}
def firstOffset (base : ℕ) := base+6
def copyOffset (base : ℕ) (j : BranchJob q) := firstOffset base+(patternWords j.first).length
def lastOffset (base : ℕ) (j : BranchJob q) := copyOffset base j+(patternWords j.copy).length
def middleOffset (base : ℕ) (j : BranchJob q) := lastOffset base j+(patternWords j.last).length
def nextOffset (base : ℕ) (j : BranchJob q) := middleOffset base j+(patternWords j.middle).length
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.ScalarAssignments
section
namespace BackreferenceMatching.ArrayRAM.ScalarAssignments
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning
abbrev Term := Lax808846Proofs.Imp.Expr
abbrev Assignment := String × Term
def command : List Assignment → Com
| [] => .skip
| (name,e)::rest => .seq (.assign name e) (command rest)
def cost : List Assignment → ℕ
| [] => 1
| (_,e)::rest => 1+e.size+cost rest
end BackreferenceMatching.ArrayRAM.ScalarAssignments
end
-- BackreferenceMatching.JobPacketMachine
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Functional Repetition.IndexRAM
variable {q : ℕ}
abbrev headerRead (k : ℕ) := Lax808846Proofs.Imp.Expr.get "returnWords" (.add (.var "jobCursor") (.lit k))
def payloadAddress : ℕ → Lax808846Proofs.Imp.Expr
| 0 => .add (.var "jobCursor") (.lit 6)
| k+1 => .add (payloadAddress k) (headerRead (2+k))
def packetSlots : List ScalarAssignments.Assignment := [
("jobBack",(headerRead 0)),
("jobSquare",(headerRead 1)),
("patternPtr",(payloadAddress 0)),
("offsetD",(payloadAddress 2)),
("offsetC",(payloadAddress 3)),
("nextJob",(payloadAddress 4))]
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.BranchFrontMachine
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Repetition Repetition.IndexRAM
variable {q : ℕ}
def frontCode := Com.seq (testInterval xPort "origin" "cmpI") (.seq (.assign "frontOK" (.var "accepted"))
(.seq (testInterval yPort "cmpI" "gapX") (.assign "frontOK" (.and (.var "frontOK") (.var "accepted")))))
def frontTime (a b : ℕ) := queryTime a+21*a+queryTime b+21*b+54
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.CutRowAccess
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Repetition.IndexRAM
variable {q : ℕ}
def edge (right : Bool) := Lax808846Proofs.Imp.Expr.get (if right then "cutRight" else "cutLeft") (.var "cutRow")
def rowSlots (right : Bool) : List ScalarAssignments.Assignment := [
("candBase",if right then .add (.var "cutRow") (.lit 1) else .sub (.var "cutRow") (edge false)),
("candCount",.add (edge right) (.lit 1)),
("candHeight",.get "cutHeights" (.var "cutRow"))]
def readLight := Com.ite (.lt (edge true) (edge false)) (ScalarAssignments.command (rowSlots true)) (ScalarAssignments.command (rowSlots false))
def rawAtOffset := Com.assign "candRaw" (.get "cutStarts" (.add (.var "candBase") (.var "cutOffset")))
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.ShortMatchContext
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Repetition Repetition.IndexRAM
variable {q : ℕ}
def cPort : PatternPort := ⟨⟨"matrixLettersC","rangeLeftC","rangeRightC","unitC"⟩,"widthC","nullC"⟩
structure ShortLimits (B cap : ℕ) (p : Branch q) (w : Word q) : Prop where
front : MatchLimits B cap 1 p.first p.copy p.last w.length
gap : TableLimits B w.length (positions p.middle).length
matrix : (positions p.middle).length*(positions p.middle).length ≤ cap
text : 2*w.length+3 < B
levels : w.length.log2+1 < B
sparse : (w.length.log2+1)*(w.length+1) < B
def shortSlots : List ScalarAssignments.Assignment := [
("cmpI",.var "firstPos"),
("gapX",.add (.var "firstPos") (.var "copyLen")),
("afterSecond",.add (.var "secondPos") (.var "copyLen")),
("queryI",.var "firstPos"),
("queryJ",.var "secondPos"),
("length",.var "textSize"),
("stride",.var "shortN")]
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.InstallJobPatterns
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Functional Repetition.IndexRAM
variable {q : ℕ}
def JobTableLimit (B cap n : ℕ) (r : Reg q) := TableLimits B n (positions r).length ∧ patternCapacity n (positions r).length ≤ cap
def installJob (q : ℕ) := Com.seq (installPort q xPort) (.seq (installPort q yPort) (installPort q zPort))
def installJobTime (j : BranchJob q) (n : ℕ) := installationTime (positions j.first).length n+installationTime (positions j.copy).length n+
installationTime (positions j.last).length n
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.ShortIntervalMachine
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Repetition Repetition.IndexRAM
variable {q : ℕ}
def tailCode := Com.seq (testInterval cPort "gapX" "secondPos") (.seq (.assign "tailOK" (.var "accepted"))
(.seq (testInterval zPort "afterSecond" "textSize") (.assign "tailOK" (.and (.var "tailOK") (.var "accepted")))))
def shortTerms := Com.seq frontCode (.seq tailCode (.assign "shortOK" (.and (.var "frontOK") (.var "tailOK"))))
def termsTime (p : Branch q) := frontTime (positions p.first).length (positions p.copy).length +
frontTime (positions p.middle).length (positions p.last).length+4
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.RegisterComparisons
section
namespace BackreferenceMatching.ArrayRAM.RegisterComparisons
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.Automata.MatrixRAM
inductive Test where
| lt (a b : String)
| eq (a b : String)
| both (a b : Test)
| either (a b : Test)
| neg (a : Test)
def Test.truth (s : Env) : Test → Bool
| .lt a b => decide (s.vars a < s.vars b)
| .eq a b => decide (s.vars a=s.vars b)
| .both a b => a.truth s && b.truth s
| .either a b => a.truth s || b.truth s
| .neg a => !(a.truth s)
def lessBit (a b : Lax808846Proofs.Imp.Expr) := Lax808846Proofs.Imp.Expr.sub (.lit 1) (.sub (.lit 1) (.sub b a))
def Test.compile : Test → Lax808846Proofs.Imp.Expr
| .lt a b => lessBit (.var a) (.var b)
| .eq a b => equalBit (.var a) (.var b)
| .both a b => .and a.compile b.compile
| .either a b => .or a.compile b.compile
| .neg a => .sub (.lit 1) a.compile
end BackreferenceMatching.ArrayRAM.RegisterComparisons
end
-- BackreferenceMatching.ShortCandidateMachine
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Repetition Repetition.IndexRAM RegisterComparisons
variable {q : ℕ}
def outsideCopies : Test := .either (.lt "secondPos" "gapX") (.either (.lt "textSize" "afterSecond") (.lt "minimum" "copyLen"))
def rejectShort := Com.assign "shortOK" (.lit 0)
def testCopies := Com.ite (.eq outsideCopies.compile (.lit 0)) shortTerms rejectShort
def shortItem := Com.seq (ScalarAssignments.command shortSlots) (.seq (lceLookup nativeNames) testCopies)
def shortTime (p : Branch q) := termsTime p+105
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.DisjunctionScan
section
namespace BackreferenceMatching.ArrayRAM
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning
def scanAnswers (idx limit acc output : String) (body : Com) :=
Com.seq (.assign acc (.lit 0)) (collectAnswer idx limit acc output body)
end BackreferenceMatching.ArrayRAM
end
-- BackreferenceMatching.ShortBranchScan
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Repetition.IndexRAM
variable {q : ℕ}
def lengthScan := scanAnswers "copyLen" "shortN" "lengthHit" "shortOK" shortItem
def lengthTime (p : Branch q) (n : ℕ) := (shortTime p+12)*(n+1)+8
def secondScan := scanAnswers "secondPos" "shortN" "secondHit" "lengthHit" lengthScan
def secondTime (p : Branch q) (n : ℕ) := (lengthTime p n+12)*(n+1)+8
def shortScan := scanAnswers "firstPos" "shortN" "shortDecision" "secondHit" secondScan
def shortScanTime (p : Branch q) (n : ℕ) := (secondTime p n+12)*(n+1)+8
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.ShortJobMachine
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Functional Repetition.IndexRAM
variable {q : ℕ}
def shortJob (p : Branch q) : BranchJob q := ⟨false,false,p.first,p.copy,p.middle,p.last⟩
def shortInit := Com.seq (.assign "origin" (.lit 0)) (.seq (.assign "count" (.lit 2)) (.assign "shortN" (.add (.var "textSize") (.lit 1))))
def shortPrepare (q : ℕ) := Com.seq (installJob q) (.seq (installPort q cPort) shortInit)
def shortPrepareTime (p : Branch q) (n : ℕ) := installJobTime (shortJob p) n+installationTime (positions p.middle).length n+8
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.MirrorTextIndex
section
namespace BackreferenceMatching.SubstringIndex.RadixMachine
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM Automata.MatrixRAM
def mirrorText (q : ℕ) := Com.seq (.assign "alphabetPlusOne" (.lit (q+1)))
(.seq (copyRange "gapText" "mirrorLetters") (Rename.code mirrorBank prepareIndex))
end BackreferenceMatching.SubstringIndex.RadixMachine
end
-- BackreferenceMatching.BitMaskMachine
section
namespace BackreferenceMatching.Automata.ResidualMask.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine MatrixRAM
def readBit (word index : Lax808846Proofs.Imp.Expr) := Lax808846Proofs.Imp.Expr.and (.shiftr word index) (.lit 1)
def unpack := tabulate "maskDigits" (.var "index") (readBit (.var "maskIn") (.var "index"))
def packIndex := Lax808846Proofs.Imp.Expr.sub (.var "dim") (.add (.var "packStep") (.lit 1))
def packItem (bank : String) := Com.assign "maskOut" (.add (.add (.var "maskOut") (.var "maskOut")) (.get bank packIndex))
def packCode (bank : String) := Com.seq (.assign "maskOut" (.lit 0)) (forRange "packStep" "dim" (packItem bank))
end BackreferenceMatching.Automata.ResidualMask.Native
end
-- BackreferenceMatching.PreimageMachine
section
namespace BackreferenceMatching.Automata.ResidualMask.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine MatrixRAM
def applyMask (bank : String) := Com.seq (.assign "length" (.var "dim"))
(.seq unpack (.seq (imageCode bank "maskDigits" "imageDigits") (packCode "imageDigits")))
end BackreferenceMatching.Automata.ResidualMask.Native
end
-- BackreferenceMatching.SegmentMaskMachine
section
namespace BackreferenceMatching.Automata.ResidualMask.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine MatrixRAM
open SubstringIndex SubstringIndex.BoundaryHistory
variable {q : ℕ}
def segmentMask := Com.seq (fetchInterval zPort "maskA" "maskB" "maskMatrix")
(.seq (.assign "dim" (.var "widthZ")) (applyMask "maskMatrix"))
def segmentTime (d : ℕ) := queryTime d+(21*d+54)*d+38
end BackreferenceMatching.Automata.ResidualMask.Native
end
-- BackreferenceMatching.ProbeLetters
section
namespace BackreferenceMatching.SubstringIndex.BoundaryHistory.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
variable {q : ℕ}
def fillChars := tabulate "cmpLetters" (.var "index") (.add (.get "gapText" (.var "index")) (.lit 1))
def paddedChars := Com.seq fillChars (.store "cmpLetters" (.var "length") (.lit 0))
end BackreferenceMatching.SubstringIndex.BoundaryHistory.Native
end
-- BackreferenceMatching.OrdinalHistogramMachine
section
namespace BackreferenceMatching.SubstringIndex.RadixMachine
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM
def readOrdinal := tabulate "prNext" (.var "index") (.add (.get "hist" (.get "tag" (.var "index"))) (.lit 1))
def histogramOrdinals := Com.seq clearCode (.seq countCode (.seq offsetsCode readOrdinal))
end BackreferenceMatching.SubstringIndex.RadixMachine
end
-- BackreferenceMatching.WeightedGroupMachine
section
namespace BackreferenceMatching.SubstringIndex.RadixMachine
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM
def addPiece := Com.seq (.assign "pieceColor" (.get "groupKeys" (.var "pieceIndex")))
(.seq (.assign "pieceOffset" (.get "groupEnds" (.var "pieceColor")))
(.seq (.store "relative" (.var "pieceIndex") (.var "pieceOffset"))
(.store "groupEnds" (.var "pieceColor") (.add (.var "pieceOffset") (.get "pieceSize" (.var "pieceIndex"))))))
def addGroups := forRange "pieceIndex" "pieces" addPiece
end BackreferenceMatching.SubstringIndex.RadixMachine
end
-- BackreferenceMatching.GapRowKernel
section
namespace BackreferenceMatching.SubstringIndex.LayerGap.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
def gatherParents := tabulate "groupKeys" (.var "index") (.get "gapParents" (.add (.var "gpParentBase") (.var "index")))
def clearMass := tabulate "groupEnds" (.var "index") (.lit 0)
def setMarker := Com.seq clearMass (.store "groupEnds" (.var "gpFinal") (.lit 1))
def routeWeights := Com.seq gatherParents (.seq (copyRange "groupEnds" "pieceSize") (.seq setMarker addGroups))
end BackreferenceMatching.SubstringIndex.LayerGap.Native
end
-- BackreferenceMatching.GapSweepLayout
section
namespace BackreferenceMatching.SubstringIndex.LayerGap.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
variable {q : ℕ}
structure Limits (B q n m : ℕ) : Prop where
text : n+1 < B
alphabet : q < B
table : (n+1)*m < B
lookup : (q+1)*m < B
def rowBase := Com.assign "rowStart" (.mul (.var "gpLayer") (.var "length"))
def textSlot (backwards : Bool) : Lax808846Proofs.Imp.Expr :=
if backwards then .sub (.var "gpN") (.add (.var "gpLayer") (.lit 1)) else .var "gpLayer"
def chooseParents (backwards : Bool) := Com.assign "gpParentBase" (.mul (.get "gapText" (textSlot backwards)) (.var "length"))
end BackreferenceMatching.SubstringIndex.LayerGap.Native
end
-- BackreferenceMatching.GapBottomStep
section
namespace BackreferenceMatching.SubstringIndex.LayerGap.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
variable {q : ℕ}
def saveLevel (src dst : String) := Com.seq rowBase (copyRow src dst)
def bottomLevel := Com.seq (saveLevel "groupEnds" "gapWeights")
(.seq (chooseParents true) (.seq routeWeights (copyRow "relative" "gapLinks")))
end BackreferenceMatching.SubstringIndex.LayerGap.Native
end
-- BackreferenceMatching.HistoryPriorityMachine
section
namespace BackreferenceMatching.SubstringIndex.BoundaryHistory.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine LayerGap.Native
variable {q m : ℕ}
def alphabetRange (m : ℕ) := m*m+m+1
def parentTerm := Lax808846Proofs.Imp.Expr.get "gapParents" (.add (.var "gpParentBase") (.var "index"))
def priorityKey := Lax808846Proofs.Imp.Expr.add (.mul (.get "prCurrent" parentTerm) (.var "length")) (.var "index")
def makeTags := tabulate "tag" (.var "index") priorityKey
def initialPriorities := tabulate "prCurrent" (.var "index") (.add (.var "index") (.lit 1))
def priorityLevel := Com.seq (saveLevel "prCurrent" "prRows") (.seq (chooseParents false)
(.seq makeTags (.seq histogramOrdinals (copyRange "prNext" "prCurrent"))))
end BackreferenceMatching.SubstringIndex.BoundaryHistory.Native
end
-- BackreferenceMatching.SuffixHistoryMachine
section
namespace BackreferenceMatching.SubstringIndex.BoundaryHistory.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine LayerGap.Native
variable {q m : ℕ}
def commitState := Com.store "suffixStates" (.var "gpLayer") (.var "decState")
def stepState := Com.seq (chooseParents true)
(.assign "decState" (.get "gapParents" (.add (.var "gpParentBase") (.var "decState"))))
def stateBody := Com.seq commitState stepState
def buildStates := Com.seq (.assign "decState" (.var "gpFinal")) (.seq (forRange "gpLayer" "gpN" stateBody) commitState)
end BackreferenceMatching.SubstringIndex.BoundaryHistory.Native
end
-- BackreferenceMatching.ProbeLayout
section
namespace BackreferenceMatching.SubstringIndex.BoundaryHistory.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Automata.ResidualMask Automata.ResidualMask.Native Repetition.IndexRAM
variable {q : ℕ}
structure ProbeLimits (B : ℕ) (r : Reg q) (n : ℕ) : Prop where
matrix : TableLimits B n (positions r).length
masks : 2^(positions r).length < B
width : 2*n+3 < B
levels : n.log2+1 < B
sparse : (n.log2+1)*(n+1) < B
addresses : (n+1)*2^(positions r).length < B
alphabet : q+1 < B
end BackreferenceMatching.SubstringIndex.BoundaryHistory.Native
end
-- BackreferenceMatching.ProbeCoordinates
section
namespace BackreferenceMatching.SubstringIndex.BoundaryHistory.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Automata.ResidualMask Automata.ResidualMask.Native Repetition.IndexRAM
variable {q : ℕ}
def locateSlots : List ScalarAssignments.Assignment := [
("length",.var "textSize"),
("stride",.add (.var "textSize") (.lit 1)),
("queryI",.var "cmpI"),
("queryJ",.var "cmpJ")]
def clipped := Com.assign "cmpK" (smaller (.var "cmpLen") (.var "minimum"))
def locateCommon := Com.seq (ScalarAssignments.command locateSlots) (.seq (lceLookup mirrorNames) clipped)
def probeSlots : List ScalarAssignments.Assignment := [
("cmpIK",.add (.var "cmpI") (.var "cmpK")),
("cmpJK",.add (.var "cmpJ") (.var "cmpK")),
("cmpEndJ",.add (.var "cmpJ") (.var "cmpLen")),
("maskA",.add (.var "cmpI") (.var "cmpK")),
("maskB",.add (.var "cmpI") (.var "cmpLen")),
("maskIn",.var "cmpMask")]
def middleState := Com.seq locateCommon (.seq (ScalarAssignments.command probeSlots) segmentMask)
end BackreferenceMatching.SubstringIndex.BoundaryHistory.Native
end
-- BackreferenceMatching.ProbeObservations
section
namespace BackreferenceMatching.SubstringIndex.BoundaryHistory.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Automata.ResidualMask Automata.ResidualMask.Native Repetition.IndexRAM
variable {q : ℕ}
def stateExpr (index : Lax808846Proofs.Imp.Expr) := Lax808846Proofs.Imp.Expr.get "suffixStates" (.sub (.var "textSize") index)
def priorityExpr (terminal : Lax808846Proofs.Imp.Expr) := Lax808846Proofs.Imp.Expr.get "prRows" (.add (.mul (.var "cmpIK") (.var "cmpM")) terminal)
def observeSlots : List ScalarAssignments.Assignment := [
("cmpActual",stateExpr (.var "cmpJ")),
("cmpOther",stateExpr (.var "cmpJK")),
("cmpAfter",stateExpr (.var "cmpEndJ")),
("cmpPrV",priorityExpr (.var "maskOut")),
("cmpPrW",priorityExpr (stateExpr (.var "cmpJK"))),
("cmpCharA",.get "cmpLetters" (.var "cmpIK")),
("cmpCharB",.get "cmpLetters" (.var "cmpJK"))]
end BackreferenceMatching.SubstringIndex.BoundaryHistory.Native
end
-- BackreferenceMatching.ProbeComparisonMachine
section
namespace BackreferenceMatching.SubstringIndex.BoundaryHistory.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Automata.ResidualMask Automata.ResidualMask.Native Repetition.IndexRAM RegisterComparisons
variable {q : ℕ}
def smallerTest : Test := .either (.lt "cmpStart" "cmpActual") (.either
(.both (.eq "cmpStart" "cmpActual") (.lt "cmpPrV" "cmpPrW"))
(.both (.eq "maskOut" "cmpOther") (.both (.lt "cmpK" "cmpLen") (.lt "cmpCharA" "cmpCharB"))))
def sameTest : Test := .both (.eq "cmpK" "cmpLen") (.eq "cmpAfter" "cmpMask")
def answerSlots : List ScalarAssignments.Assignment := [("probePatLess",smallerTest.compile),("probePatEqual",sameTest.compile)]
def compareEven := Com.seq middleState (.seq (ScalarAssignments.command observeSlots) (ScalarAssignments.command answerSlots))
def compareTime (d : ℕ) := 69+23+segmentTime d+55+155
end BackreferenceMatching.SubstringIndex.BoundaryHistory.Native
end
-- BackreferenceMatching.PrimarySearchContext
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Automata.ResidualMask Automata.ResidualMask.Native BoundaryHistory BoundaryHistory.Native Repetition.IndexRAM
variable {q : ℕ}
abbrev coloured (r : Reg q) (w : Word q) := decorate (letterMask r) w (finalMask r)
def chooseFlag (closed : Bool) := Com.assign "probeOk" (.sub (.lit 1)
(if closed then .var "probePatLess" else .or (.var "probePatLess") (.var "probePatEqual")))
def setCandidate := Com.assign "cmpJ" (.div (.var "rawProbe") (.lit 2))
def onEven (closed : Bool) := Com.seq setCandidate (.seq compareEven (chooseFlag closed))
def rawOrder (closed : Bool) := Com.ite (.eq (.var "rawProbe") (.var "primaryLast")) (probeBit 1)
(.ite (.eq (.and (.var "rawProbe") (.lit 1)) (.lit 0)) (onEven closed) (probeBit 0))
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.PrimaryBoundaryMachine
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Automata.ResidualMask Automata.ResidualMask.Native BoundaryHistory BoundaryHistory.Native Repetition.IndexRAM
variable {q : ℕ}
def rankLookup := Com.assign "rawProbe" (.get "starts" (.sub (.var "probeLength") (.lit 1)))
def readRank (closed : Bool) := Com.seq rankLookup (rawOrder closed)
def primaryTest (closed : Bool) := Com.ite (.lt (.var "primarySize") (.var "probeLength")) (probeBit 0)
(.ite (.eq (.var "probeLength") (.lit 0)) (probeBit 1) (readRank closed))
def primaryTime (d : ℕ) := compareTime d+40
def boundTime (d R : ℕ) := (primaryTime d+22)*R+10
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.GapBottomMachine
section
namespace BackreferenceMatching.SubstringIndex.LayerGap.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
variable {q : ℕ}
def bottomPass := Com.seq setMarker (.seq (forRange "gpLayer" "gpN" bottomLevel) (saveLevel "groupEnds" "gapWeights"))
end BackreferenceMatching.SubstringIndex.LayerGap.Native
end
-- BackreferenceMatching.GapRootMachine
section
namespace BackreferenceMatching.SubstringIndex.LayerGap.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
def rootBody := Com.seq (.store "gapCurrent" (.var "gpC") (.var "gpSum"))
(.assign "gpSum" (.add (.var "gpSum") (.get "groupEnds" (.var "gpC"))))
def makeRoot := Com.seq (.assign "gpSum" (.lit 0)) (forRange "gpC" "length" rootBody)
end BackreferenceMatching.SubstringIndex.LayerGap.Native
end
-- BackreferenceMatching.GapTopStep
section
namespace BackreferenceMatching.SubstringIndex.LayerGap.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
variable {q : ℕ}
def setLinkBase := Com.assign "gpLinkBase" (.mul (textSlot true) (.var "length"))
def childValue : Lax808846Proofs.Imp.Expr := .add
(.get "gapCurrent" (.get "gapParents" (.add (.var "gpParentBase") (.var "index"))))
(.get "gapLinks" (.add (.var "gpLinkBase") (.var "index")))
def moveChildren := tabulate "gapNext" (.var "index") childValue
def topLevel := Com.seq (saveLevel "gapCurrent" "gapStart") (.seq (chooseParents false) (.seq setLinkBase
(.seq moveChildren (copyRange "gapNext" "gapCurrent"))))
end BackreferenceMatching.SubstringIndex.LayerGap.Native
end
-- BackreferenceMatching.GapIndexMachine
section
namespace BackreferenceMatching.SubstringIndex.LayerGap.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
variable {q : ℕ}
def topPass := Com.seq makeRoot (.seq (forRange "gpLayer" "gpN" topLevel) (saveLevel "gapCurrent" "gapStart"))
def buildGap := Com.seq bottomPass topPass
end BackreferenceMatching.SubstringIndex.LayerGap.Native
end
-- BackreferenceMatching.WaveletReadMachine
section
namespace BackreferenceMatching.SubstringIndex.Wavelet.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
def zeroAt (key : String) := Lax808846Proofs.Imp.Expr.get "wvRows" (.add (.var "wvRow") (.var key))
def loadRow := Com.seq (.assign "wvP" (.get "powers" (.sub (.var "wvHeight") (.add (.var "wvLevel") (.lit 1)))))
(.seq (.assign "wvRow" (.mul (.var "wvLevel") (.var "wvWidth")))
(.seq (.assign "wvLowZeros" (zeroAt "wvLo")) (.seq (.assign "wvHighZeros" (zeroAt "wvHi")) (.assign "wvZeroEnd" (zeroAt "wvLen")))))
end BackreferenceMatching.SubstringIndex.Wavelet.Native
end
-- BackreferenceMatching.WaveletMoveMachine
section
namespace BackreferenceMatching.SubstringIndex.Wavelet.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM
def lowerHalf := Com.seq (.assign "wvLo" (.var "wvLowZeros")) (.assign "wvHi" (.var "wvHighZeros"))
def positionInOnes (atKey before : String) := Lax808846Proofs.Imp.Expr.add (.var "wvZeroEnd") (.sub (.var atKey) (.var before))
def upperHalf := Com.seq (.assign "wvCount" (.add (.var "wvCount") (.sub (.var "wvHighZeros") (.var "wvLowZeros"))))
(.seq (.assign "wvLo" (positionInOnes "wvLo" "wvLowZeros"))
(.seq (.assign "wvHi" (positionInOnes "wvHi" "wvHighZeros")) (.assign "wvKey" (.sub (.var "wvKey") (.var "wvP")))))
def moveCode := Com.ite (.lt (.var "wvKey") (.var "wvP")) lowerHalf upperHalf
end BackreferenceMatching.SubstringIndex.Wavelet.Native
end
-- BackreferenceMatching.WaveletQueryMachine
section
namespace BackreferenceMatching.SubstringIndex.Wavelet.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM
def levelCode := Com.seq loadRow moveCode
def finishCode := Com.ite (.eq (.var "wvKey") (.lit 0)) .skip
(.assign "wvCount" (.add (.var "wvCount") (.sub (.var "wvHi") (.var "wvLo"))))
def queryCode := Com.seq (forRange "wvLevel" "wvHeight" levelCode) finishCode
end BackreferenceMatching.SubstringIndex.Wavelet.Native
end
-- BackreferenceMatching.WaveletPrefixMachine
section
namespace BackreferenceMatching.SubstringIndex.Wavelet.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
def prefixBody := Com.seq (.store "wvCounts" (.var "wvScan") (.var "wvSum"))
(.ite (.lt (.get "wvValues" (.var "wvScan")) (.var "wvP")) (next "wvSum") .skip)
def makePrefix := Com.seq (.assign "wvSum" (.lit 0))
(.seq (forRange "wvScan" "wvLen" prefixBody) (.store "wvCounts" (.var "wvLen") (.var "wvSum")))
end BackreferenceMatching.SubstringIndex.Wavelet.Native
end
-- BackreferenceMatching.WaveletScatterMachine
section
namespace BackreferenceMatching.SubstringIndex.Wavelet.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
abbrev E := Lax808846Proofs.Imp.Expr
def atValue : E := .get "wvValues" (.var "index")
def atZeros : E := .get "wvCounts" (.var "index")
def highBit : E := .div atValue (.var "wvP")
def atSlot : E := .add (.mul (.sub (.lit 1) highBit) atZeros)
(.mul highBit (.add (.var "wvSum") (.sub (.var "index") atZeros)))
def atResidual : E := .sub atValue (.mul highBit (.var "wvP"))
def scatterRow := tabulate "wvNext" atSlot atResidual
end BackreferenceMatching.SubstringIndex.Wavelet.Native
end
-- BackreferenceMatching.WaveletArchiveMachine
section
namespace BackreferenceMatching.SubstringIndex.Wavelet.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
def levelSetup := Com.seq (.assign "wvP" (.get "powers" (.sub (.var "wvHeight") (.add (.var "wvLevel") (.lit 1)))))
(.seq (.assign "rowStart" (.mul (.var "wvLevel") (.var "wvWidth"))) (.assign "length" (.var "wvWidth")))
def archive := Com.seq levelSetup (.seq makePrefix (copyRow "wvCounts" "wvRows"))
end BackreferenceMatching.SubstringIndex.Wavelet.Native
end
-- BackreferenceMatching.WaveletBuildMachine
section
namespace BackreferenceMatching.SubstringIndex.Wavelet.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
def scatterSetup := Com.seq (.assign "length" (.var "wvLen")) (.assign "wvSum" (.get "wvCounts" (.var "wvLen")))
def buildLevel := Com.seq archive (.seq scatterSetup (.seq scatterRow (copyRange "wvNext" "wvValues")))
def buildWavelet := forRange "wvLevel" "wvHeight" buildLevel
end BackreferenceMatching.SubstringIndex.Wavelet.Native
end
-- BackreferenceMatching.RectanglePointMachine
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine LayerGap.Native
open Wavelet.Native
variable {q Q : ℕ}
def rawStart (bank : String) := Lax808846Proofs.Imp.Expr.get bank (.var "index")
def parity (bank : String) := Lax808846Proofs.Imp.Expr.and (rawStart bank) (.lit 1)
def endAddress (bank : String) := Lax808846Proofs.Imp.Expr.add (.mul (.div (rawStart bank) (.lit 2)) (.var "gapM")) (.var "gapSeed")
def pointExpr (bank : String) := Lax808846Proofs.Imp.Expr.add
(.mul (.sub (.lit 1) (parity bank)) (.get "gapStart" (endAddress bank)))
(.mul (parity bank) (.add (.var "textSize") (.lit 1)))
def createPoints (bank : String) := tabulate "wvValues" (.var "index") (pointExpr bank)
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.WaveletRectangleMachine
section
namespace BackreferenceMatching.SubstringIndex.Wavelet.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
def countSlots (hi : Bool) : List ScalarAssignments.Assignment :=
[("wvLo",.var "rxLo"),("wvHi",.var "rxHi"),("wvKey",.var (if hi then "rxTop" else "rxBottom")),("wvCount",.lit 0)]
def boxCount (hi : Bool) := Com.seq (ScalarAssignments.command (countSlots hi)) queryCode
def compareCounts := Com.assign "rxHit" (RegisterComparisons.lessBit (.var "rxBefore") (.var "wvCount"))
def boxCode := Com.seq (boxCount false) (.seq (.assign "rxBefore" (.var "wvCount")) (.seq (boxCount true) compareCounts))
end BackreferenceMatching.SubstringIndex.Wavelet.Native
end
-- BackreferenceMatching.RectangleBoundsMachine
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Automata.ResidualMask Automata.ResidualMask.Native BoundaryHistory BoundaryHistory.Native Repetition.IndexRAM
variable {q : ℕ}
def searchInterval := Com.seq (boundaryCode (primaryTest false)) (.seq (.assign "rxLo" (.var "searchBest"))
(.seq (boundaryCode (primaryTest true)) (.assign "rxHi" (.var "searchBest"))))
def startAddr := Lax808846Proofs.Imp.Expr.add (.mul (.var "gapX") (.var "gapM")) (.var "gapColour")
def widthAddr := Lax808846Proofs.Imp.Expr.add (.mul (.sub (.var "textSize") (.var "gapX")) (.var "gapM")) (.var "gapColour")
def gapSlots : List ScalarAssignments.Assignment := [("rxBottom",.get "gapStart" startAddr),
("rxTop",.add (.get "gapStart" startAddr) (.get "gapWeights" widthAddr))]
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.RectangleMatchMachine
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Automata.ResidualMask Automata.ResidualMask.Native BoundaryHistory BoundaryHistory.Native Repetition.IndexRAM
variable {q : ℕ}
noncomputable abbrev gapPoints (C D : Reg q) (w : Word q) :=
pointRow (coloured D w) w.length (fun j => LayerGap.startsAt (natStep C) (maskCount C) (finalMask C).val w j (finalMask C).val)
structure BoxLimits (B : ℕ) (C D : Reg q) (w : Word q) (R : ℕ) : Prop where
rounds : R < B
range : (coloured D w).length+1 < 2^R
stride : (coloured D w).length+1+2^R < B
gap : (w.length+1)*maskCount C < B
levels : (w.length+1).log2+1 < B
power : 2^((w.length+1).log2+1) < B
capacity : ((w.length+1).log2+1+1)*((gapPoints C D w).length+1) < B
def hitCode := Com.seq searchInterval (.seq (ScalarAssignments.command gapSlots) Wavelet.Native.boxCode)
def hitTime (d R H : ℕ) := 2*boundTime d R+136*H+90
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.RectangleArguments
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Automata.ResidualMask Automata.ResidualMask.Native BoundaryHistory BoundaryHistory.Native Repetition.IndexRAM
variable {q : ℕ}
def patternSlots : List ScalarAssignments.Assignment := [
("maskA",.var "cmpI"),
("maskB",.add (.var "cmpI") (.var "cmpLen")),
("maskIn",.var "cmpMask")]
def startPattern := Com.seq (ScalarAssignments.command patternSlots) (.seq segmentMask (.assign "cmpStart" (.var "maskOut")))
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.RectangleMaskScan
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Automata.ResidualMask Automata.ResidualMask.Native BoundaryHistory BoundaryHistory.Native Repetition.IndexRAM
variable {q : ℕ}
def filterMask (mask flag : String) := Com.assign flag (.and (readBit (.var mask) (.lit 0)) (.var flag))
def maskCandidate := Com.seq startPattern (.seq hitCode (filterMask "cmpMask" "rxHit"))
def suffixScan := scanAnswers "cmpMask" "cmpM" "suffixHit" "rxHit" maskCandidate
def gapCandidate := Com.seq suffixScan (filterMask "gapColour" "suffixHit")
def regexQuery := scanAnswers "gapColour" "gapM" "regexHit" "suffixHit" gapCandidate
def maskTime (d R H : ℕ) := segmentTime d+hitTime d R H+19
def suffixTime (d R H : ℕ) := (maskTime d R H+12)*2^d+8
def regexTime (c d R H : ℕ) := (suffixTime d R H+20)*2^c+8
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.OrientedCandidateMachine
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Automata.ResidualMask BoundaryHistory BoundaryHistory.Native Repetition.IndexRAM
variable {q : ℕ}
def joinHits := Com.assign "candidateOK" (.and (.var "frontOK") (.var "regexHit"))
def preparedCandidate := Com.seq frontCode (.seq regexQuery joinHits)
def preparedTime (a b c d R H : ℕ) := frontTime a b+regexTime c d R H+4
def positionExpr (back : Bool) : Lax808846Proofs.Imp.Expr :=
if back then .sub (.var "textSize") (.add (.var "candRaw") (.var "candHeight")) else .var "candRaw"
def candidateSlots (back : Bool) : List ScalarAssignments.Assignment := [
("cmpI",positionExpr back),
("cmpLen",.var "candHeight"),
("gapX",.add (positionExpr back) (.var "candHeight"))]
def orientedItem (back : Bool) := Com.ite (.lt (.var "textSize") (.add (.var "candRaw") (.var "candHeight")))
(.assign "candidateOK" (.lit 0)) (.seq (ScalarAssignments.command (candidateSlots back)) preparedCandidate)
def itemTime (a b c d R H : ℕ) := preparedTime a b c d R H+31
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.CutScanCost
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open BoundaryHistory
variable {q : ℕ}
def orientedText (back : Bool) (w : Word q) := if back then w.reverse else w
def cutScanTime (work n : ℕ) := (work+17)*((n+1)*(n+1).log2)+46*n+8
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.CutRowScan
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Automata.ResidualMask BoundaryHistory BoundaryHistory.Native Repetition.IndexRAM
variable {q : ℕ}
structure ScanLimits (B cap R : ℕ) (A E C D : Reg q) (v : Word q) : Prop where
front : MatchLimits B cap 1 A E D v.length
probe : ProbeLimits B D v.length
box : BoxLimits B C D v R
def offsetItem (back : Bool) := Com.seq rawAtOffset (orientedItem back)
def probeCut (back : Bool) := scanAnswers "cutOffset" "candCount" "rowHit" "candidateOK" (offsetItem back)
def rowItem (back : Bool) := Com.seq readLight (probeCut back)
abbrev workPerCandidate (A E C D : Reg q) (R n : ℕ) :=
itemTime (positions A).length (positions E).length (positions C).length (positions D).length R ((n+1).log2+1)
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.OrientedCutMachine
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Automata.ResidualMask BoundaryHistory BoundaryHistory.Native Repetition.IndexRAM
variable {q : ℕ}
def orientedScan (back : Bool) := Com.seq (.assign "orientationHit" (.lit 0))
(collectAnswer "cutRow" "textSize" "orientationHit" "rowHit" (rowItem back))
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.RunShortJob
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Repetition.IndexRAM
variable {q : ℕ}
structure ShortJobLimits (B cap base : ℕ) (p : Branch q) (w : Word q) : Prop where
lookup : ShortLimits B cap p w
tables : ∀ r∈[p.first,p.copy,p.last,p.middle],JobTableLimit B cap w.length r
alphabet : q < B
bound : nextOffset base (shortJob p) < B
textRoom : w.length ≤ cap
def runShortJob (q : ℕ) := Com.seq (orientText false) (.seq (shortPrepare q) (.seq shortScan (.assign "jobHit" (.var "shortDecision"))))
def runShortTime (p : Branch q) (n : ℕ) := (24*n+16)+shortPrepareTime p n+shortScanTime p n+2
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.HistoryPriorityTables
section
namespace BackreferenceMatching.SubstringIndex.BoundaryHistory.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine LayerGap.Native
variable {q m : ℕ}
def buildPriorities := Com.seq initialPriorities (.seq (forRange "gpLayer" "gpN" priorityLevel) (saveLevel "prCurrent" "prRows"))
end BackreferenceMatching.SubstringIndex.BoundaryHistory.Native
end
-- BackreferenceMatching.WeaveTableMachine
section
namespace BackreferenceMatching.SubstringIndex.BoundaryHistory.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine LayerGap.Native
variable {q m : ℕ}
def twiceIndex := Lax808846Proofs.Imp.Expr.mul (.lit 2) (.var "index")
def evenRow := tabulate "decValues" twiceIndex (.get "suffixStates" (.sub (.var "gpN") (.var "index")))
def oddRow := tabulate "decValues" (.add twiceIndex (.lit 1)) (.add (.var "pieces") (.get "gapText" (.var "index")))
def makeWeave := Com.seq (.assign "length" (.add (.var "gpN") (.lit 1)))
(.seq evenRow (.seq (.assign "length" (.var "gpN")) oddRow))
end BackreferenceMatching.SubstringIndex.BoundaryHistory.Native
end
-- BackreferenceMatching.MaskTransitionCell
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Automata.ResidualMask Automata.ResidualMask.Native Functional
variable {q : ℕ}
def letterQuotient := Lax808846Proofs.Imp.Expr.div (.var "itemIndex") (.var "parentM")
def parentRemainder := Lax808846Proofs.Imp.Expr.sub (.var "itemIndex") (.mul letterQuotient (.var "parentM"))
def parentSlots : List ScalarAssignments.Assignment := [
("sourcePtr",.add (.var "transBase") (.mul letterQuotient (.var "cells"))),
("targetPtr",.lit 0),
("length",.var "cells"),
("maskIn",parentRemainder)]
structure ParentLimits (B off : ℕ) (r : Reg q) : Prop where
packed : off+(patternWords r).length < B
states : maskCount r < B
pairs : q*maskCount r < B
cells : (positions r).length*(positions r).length < B
width : (positions r).length < B
def parentCell := Com.seq (ScalarAssignments.command parentSlots) (.seq (moveBlock "returnWords" "maskMatrix") (applyMask "maskMatrix"))
def parentTime (d : ℕ) := 16*(d*d)+(21*d+54)*d+54
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.MaskTransitionTable
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Automata.ResidualMask Automata.ResidualMask.Native Functional
variable {q : ℕ}
def tabParents := computedMap parentCell "gapParents" "parentCells" "maskOut"
def maskWidthExpr := Lax808846Proofs.Imp.Expr.shiftl (.lit 1) (.var "dim")
def startParents (q : ℕ) := Com.seq (readHeader q) (.seq (.assign "parentM" maskWidthExpr)
(.assign "parentCells" (.mul (.lit q) (.var "parentM"))))
def readFinalMask := Com.seq (copyNullable "terminalDigits") (packCode "terminalDigits")
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.MaskLayerInput
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Automata.ResidualMask Automata.ResidualMask.Native Functional BoundaryHistory BoundaryHistory.Native LayerGap.Native Repetition.IndexRAM
variable {q : ℕ}
def layerSlots : List ScalarAssignments.Assignment := [
("length",.var "parentM"),
("pieces",.var "parentM"),
("gpFinal",.var "maskOut"),
("gpN",.var "textSize")]
def prepareMasks (q : ℕ) := Com.seq (startParents q) (.seq tabParents (.seq readFinalMask (ScalarAssignments.command layerSlots)))
def maskTableTime (q d : ℕ) := (parentTime d+11)*(q*2^d)+36*d+66
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.BoundaryHistoryIndex
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Automata.ResidualMask BoundaryHistory BoundaryHistory.Native LayerGap.Native
variable {q : ℕ}
def historySeed := Com.seq (.assign "cmpM" (.var "pieces")) (.assign "radix"
(.add (.add (.mul (.var "pieces") (.var "pieces")) (.var "pieces")) (.lit 1)))
def buildHistory := Com.seq historySeed (.seq buildPriorities (.seq buildStates (.seq makeWeave
(.seq (.assign "length" (.var "gpN")) paddedChars))))
def historyTime (m n : ℕ) := (29*alphabetRange m+77*m+68)*n+27*m+22+(27*n+11)+(38*(n+1)+20)+(14*n+9)+13
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.DecoratedIndexBuild
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Automata.ResidualMask BoundaryHistory BoundaryHistory.Native Repetition.IndexRAM
variable {q : ℕ}
def textSlots (q : ℕ) : List ScalarAssignments.Assignment := [
("length",.add (.mul (.lit 2) (.var "gpN")) (.lit 1)),
("alphabetPlusOne",.add (.add (.var "cmpM") (.lit q)) (.lit 1))]
def decoratedIndex (q : ℕ) := Com.seq (ScalarAssignments.command (textSlots q)) (.seq (copyRange "decValues" "letters") prepareIndex)
def decoratedTime (q m n : ℕ) := 13+(12*(2*n+1)+6)+indexCost (m+q) (2*n+1)
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.BoxIndexBuild
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Automata.ResidualMask BoundaryHistory BoundaryHistory.Native Repetition.IndexRAM
variable {q : ℕ}
abbrev queryHeight (n : ℕ) := (n+1).log2+1
abbrev queryRounds (n : ℕ) := queryHeight n+1
def levelExpr := Lax808846Proofs.Imp.Expr.get "logs" (.add (.var "gpN") (.lit 1))
def boxSlots : List ScalarAssignments.Assignment := [
("wvHeight",.add levelExpr (.lit 1)),
("wvWidth",.add (.var "stride") (.lit 1)),
("wvLen",.var "stride"),
("searchRounds",.add levelExpr (.lit 2)),
("primaryLast",.var "length"),
("primarySize",.var "stride"),
("textSize",.var "gpN")]
def setBox := Com.seq (ScalarAssignments.command boxSlots) (.seq (.assign "initialStride" (.shiftl (.lit 1) (.var "searchRounds")))
(.assign "length" (.var "primarySize")))
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.LongJobDecision
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Repetition Repetition.IndexRAM
variable {q : ℕ}
def noSquare := Com.assign "decision" (.lit 0)
def maybeSquare := Com.ite (.eq (.var "jobSquare") (.lit 1)) adjacentCode noSquare
def jobDecision (back : Bool) := Com.seq (orientedScan back) (.seq (if back then noSquare else maybeSquare)
(.assign "jobHit" (.or (.var "decision") (.var "orientationHit"))))
def jobDecisionTime (j : BranchJob q) (n : ℕ) := cutScanTime (workPerCandidate j.first j.copy j.middle j.last (queryRounds n) n) n+
adjacentTime j.first j.copy j.last n+10
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.RectangleIndexMachine
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Automata.ResidualMask BoundaryHistory BoundaryHistory.Native Repetition.IndexRAM
variable {q : ℕ}
def buildRectangles := Com.seq setBox (.seq (createPoints "starts") Wavelet.Native.buildWavelet)
def rectangleIndexTime (n : ℕ) := 46+(42*(2*n+2)+6)+((130*(2*n+3)+68)*queryHeight n+6)
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.QueryIndexAssembly
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Automata.ResidualMask BoundaryHistory BoundaryHistory.Native Repetition.IndexRAM
variable {q : ℕ}
def finalizePorts := Com.seq (.assign "count" (.lit 2)) (.assign "origin" (.lit 0))
def completeIndex (q : ℕ) := Com.seq (decoratedIndex q) (.seq buildRectangles finalizePorts)
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.RegularGapPreparation
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Automata.ResidualMask Functional BoundaryHistory BoundaryHistory.Native LayerGap.Native
variable {q : ℕ}
def maskSpace (q n d : ℕ) := (n+1)*2^d+q*2^d+d*d+d
def selectPattern (offset : String) (q : ℕ) := Com.seq (.assign "patternPtr" (.var offset)) (prepareMasks q)
def gapSeedCode := Com.seq (.assign "gapM" (.var "pieces")) (.assign "gapSeed" (.var "gpFinal"))
def prepareGap (q : ℕ) := Com.seq (selectPattern "offsetC" q) (.seq gapSeedCode buildGap)
def prepareGapTime (q d n : ℕ) := 2+maskTableTime q d+4+((138*2^d+118)*n+57*2^d+50)
def prepareHistory (q : ℕ) := Com.seq (selectPattern "offsetD" q) buildHistory
def prepareHistoryTime (q d n : ℕ) := 2+maskTableTime q d+historyTime (2^d) n
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.PatternQueryPreparation
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Automata.ResidualMask BoundaryHistory BoundaryHistory.Native Repetition.IndexRAM LayerGap.Native
variable {q : ℕ}
structure GapGeometry (B cap off : ℕ) (r : Reg q) (n : ℕ) : Prop where
parent : ParentLimits B off r
layer : Limits B q n (maskCount r)
storage : maskSpace q n (positions r).length ≤ cap
structure RectangleGeometry (B cap : ℕ) (C D : Reg q) (w : Word q) : Prop where
radix : alphabetRange (maskCount D) < B
text : 2*w.length+2 < B
alphabet : maskCount D+q < B
history : alphabetRange (maskCount D)+(2*w.length+2) ≤ cap
index : IndexLimits B (maskCount D+q) (coloured D w).length
box : BoxLimits B C D w (queryRounds w.length)
matrix : (positions D).length*(positions D).length+(positions D).length ≤ cap
suffix : indexSpace (maskCount D+q) (coloured D w).length ≤ cap
points : (queryHeight w.length+1)*((gapPoints C D w).length+1) ≤ cap
def prepareQuery (q : ℕ) := Com.seq (prepareGap q) (.seq (prepareHistory q) (completeIndex q))
def prepareQueryTime (C D : Reg q) (n : ℕ) := prepareGapTime q (positions C).length n+
prepareHistoryTime q (positions D).length n+(decoratedTime q (maskCount D) n+rectangleIndexTime n+4)
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.LongJobMachine
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Automata.ResidualMask Functional Repetition Repetition.IndexRAM
variable {q : ℕ}
structure LongJobLimits (B cap base : ℕ) (j : BranchJob q) (v : Word q) : Prop where
textIndex : IndexLimits B q v.length
textRoom : indexSpace q v.length ≤ cap
packed : nextOffset base j < B
install : ∀ r∈[j.first,j.copy,j.last],JobTableLimit B cap v.length r
gap : GapGeometry B cap (middleOffset base j) j.middle v.length
history : GapGeometry B cap (lastOffset base j) j.last v.length
rectangles : RectangleGeometry B cap j.middle j.last v
scan : ScanLimits B cap (queryRounds v.length) j.first j.copy j.middle j.last v
records : recordLimit v.length < B
def mirrorForJob (q : ℕ) := Com.seq (mirrorText q) (.assign "textSize" (.var "length"))
def prepareLongJob (q : ℕ) (back : Bool) := Com.seq (orientText back) (.seq (mirrorForJob q) (.seq (installJob q) (prepareQuery q)))
def longSetupTime (j : BranchJob q) (n : ℕ) := (24*n+16)+(12*n+10+indexCost q n)+installJobTime j n+prepareQueryTime j.middle j.last n
def runLongJob (q : ℕ) (back : Bool) := Com.seq (prepareLongJob q back) (jobDecision back)
def longJobTime (j : BranchJob q) (n : ℕ) := longSetupTime j n+jobDecisionTime j n
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.MatchingPlan
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Functional
variable {q : ℕ}
def BranchJob.branch (j : BranchJob q) : Branch q := ⟨j.first,j.copy,j.middle,j.last⟩
noncomputable def plannedBit (short : Bool) (j : BranchJob q) (w : Word q) :=
if short then shortMatcher (BranchIndices.mk (Automata.MatrixRAM.directIndex j.first w) (Automata.MatrixRAM.directIndex j.copy w)
(Automata.MatrixRAM.directIndex j.middle w) (Automata.MatrixRAM.directIndex j.last w) : BranchIndices j.branch w)
else j.check w
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.MatchingJobKernel
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata Automata.MatrixRAM Repetition.IndexRAM
variable {q : ℕ}
def selectLong (q : ℕ) := Com.ite (.eq (.var "jobBack") (.lit 1)) (runLongJob q true) (runLongJob q false)
def matchingKernel (q : ℕ) (short : Bool) := Com.seq (ScalarAssignments.command packetSlots) (if short then runShortJob q else selectLong q)
def kernelTime (short : Bool) (j : BranchJob q) (n : ℕ) := ScalarAssignments.cost packetSlots+
(if short then runShortTime j.branch n else longJobTime j n+4)
def Feasible (B cap base : ℕ) (short : Bool) (j : BranchJob q) (w : Word q) : Prop :=
if short then ∃ p,j=shortJob p ∧ ShortJobLimits B cap base p w
else (j.backwards=true → j.adjacent=false) ∧ LongJobLimits B cap base j (orientedText j.backwards w)
structure JobWorkspace (s : Env) (short : Bool) (cap : ℕ) (w : Word q) (stream : List ℕ) : Prop where
base : BaseText s w
suffix : short=true → OriginalSuffix s w
count : s.vars "returnCount"=stream.length
words : Window s "returnWords" stream.length (fun i => stream[i.val])
space : ∀ k,cap ≤ (s.arrs k).length
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.VariablePacketLoop
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata.MatrixRAM Repetition.IndexRAM
variable {q : ℕ}
def advancePacket := Com.seq (.assign "allHits" (.or (.var "allHits") (.var "jobHit"))) (.assign "jobCursor" (.var "nextJob"))
def packetLoop (kernel : Com) := Com.while (.lt (.var "jobCursor") (.var "returnCount")) (.seq kernel advancePacket)
def packetLoopCost (time : BranchJob q → ℕ) (js : List (BranchJob q)) := (js.map (fun j => time j+10)).sum+4
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
-- BackreferenceMatching.MatchingPlanMachine
section
namespace BackreferenceMatching.SubstringIndex.ContextQueries.Native
open Lax808846Proofs.Imp Lax808846Proofs.Reasoning BackreferenceMatching.ArrayRAM BackreferenceMatching.SubstringIndex.RadixMachine
open Automata.MatrixRAM Repetition.IndexRAM
variable {q : ℕ}
def runPlan (q : ℕ) (short : Bool) := Com.seq (.assign "jobCursor" (.lit 0))
(.seq (.assign "allHits" (.lit 0)) (packetLoop (matchingKernel q short)))
end BackreferenceMatching.SubstringIndex.ContextQueries.Native
end
end
Source
S. Kumabe and Y. Uezato, On the Complexity of the Matching Problem of Regular Expressions with Backreferences, arXiv:2605.07289. https://arxiv.org/abs/2605.07289