Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ lake build --wfail Complexitylib \
```

Always verify the library, all five executable validation roots, and the
seven isolated `ApiChecks` modules pass before considering a change complete.
nine isolated `ApiChecks` modules pass before considering a change complete.
One invocation shares Lake's dependency-graph work across the targets and
builds the upstream `runLinter` executable needed below. Validation and API
regressions remain outside the public import graph.
Expand Down
4 changes: 2 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ lake env lean scripts/BlueprintCheck.lean

All commands must pass before submitting changes; CI runs them on every push.
The build checks the complete library, all five executable regression suites,
and the seven separate API-check modules, treating warnings (including proof
and the nine separate API-check modules, treating warnings (including proof
placeholders) as failures. Both kinds of regressions remain outside the public
import graph. One Lake invocation shares dependency-graph setup; unchanged
API checks reuse normal Lake traces instead of re-elaborating every time.
Expand Down Expand Up @@ -237,7 +237,7 @@ on every contributor.

For an isolated API regression, use `lake build --wfail VerifierApiCheck`
(or the corresponding module name). `lake build --wfail ApiChecks` runs all
seven as separate modules, preserving each file's public-only or compatibility
nine as separate modules, preserving each file's public-only or compatibility
imports. Lake rebuilds relevant changed imports before reusing a test artifact.
The axiom and blueprint scripts are still executed on every full verification;
they are deliberately excluded from the cached API target.
Expand Down
72 changes: 72 additions & 0 deletions Complexitylib/Encoding/FiniteAlphabet.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/-
Copyright (c) 2026 Erik Demaine. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Erik Demaine
-/

module
public import Complexitylib.Encoding.FiniteAlphabet.Defs
import Complexitylib.Encoding.FiniteAlphabet.Internal

/-!
# Exact binary coding of finite alphabets

An explicit enumeration gives a delimited, palindromic unary code for each
letter. Encodings are injective, have linear length bounds, commute with word
reversal, and are exactly the strings accepted by the partial decoder. Empty
alphabets are supported, and only the empty word then has a valid encoding.
-/

public section

namespace Complexity.FiniteAlphabetCode

variable {α β : Type} (c : FiniteAlphabetCode α)

/-- Every encoded word is decoded exactly. -/
@[simp] theorem decode_encode (w : List α) : c.decode (c.encode w) = some w :=
decode_encode_proof c w

/-- The decoder accepts precisely the chosen encodings. -/
theorem decode_eq_some_iff {bits : List Bool} {w : List α} :
c.decode bits = some w ↔ c.encode w = bits := by
constructor
· exact encode_decode_proof c
· rintro rfl
exact c.decode_encode w

/-- Encoding distinct words gives distinct binary strings. -/
theorem encode_injective : Function.Injective c.encode := by
intro xs ys h
have he := congrArg c.decode h
simpa only [decode_encode, Option.some.injEq] using he

/-- Encoded size is at least the source word length. -/
theorem length_le_encode (w : List α) : w.length ≤ (c.encode w).length :=
encode_length_lower c w

/-- The alphabet enumeration determines a constant linear size bound. -/
theorem length_encode_le (w : List α) :
(c.encode w).length ≤ (c.size + 1) * w.length :=
encode_length_upper c w

/-- Palindromic symbol codes commute with reversal of the whole word. -/
theorem encode_reverse_eq (w : List α) : c.encode w.reverse = (c.encode w).reverse :=
encode_reverse c w

/-- Reversal preserves validity and reverses the decoded letters. -/
theorem decode_reverse_eq (bits : List Bool) :
c.decode bits.reverse = (c.decode bits).map List.reverse :=
decode_reverse c bits

/-- A coded function has exactly its specified output on every encoded input. -/
@[simp] theorem map_encode (output : FiniteAlphabetCode β) (f : List α → List β) (w : List α) :
c.map output f (c.encode w) = output.encode (f w) := by
simp [map]

/-- A coded function returns empty output on every invalid code. -/
theorem map_invalid (output : FiniteAlphabetCode β) (f : List α → List β)
{bits : List Bool} (h : c.decode bits = none) : c.map output f bits = [] := by
simp [map, h]

end Complexity.FiniteAlphabetCode
70 changes: 70 additions & 0 deletions Complexitylib/Encoding/FiniteAlphabet/Defs.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/-
Copyright (c) 2026 Erik Demaine. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Erik Demaine
-/

module
public import Mathlib.Data.Fintype.EquivFin
public import Mathlib.Data.List.Basic

/-!
# Explicit binary codes for finite alphabets

An enumeration assigns index `i` to the palindromic codeword `false, true^i,
false`. Concatenation encodes words, including the empty word. Decoding rejects
missing delimiters and indices outside the enumeration. Reversing an encoding
therefore reverses its letters without changing their codes.
-/

@[expose] public section

namespace Complexity

/-- An explicit enumeration of an alphabet, including an empty alphabet. -/
structure FiniteAlphabetCode (α : Type) where
/-- Number of letters. -/
size : ℕ
/-- Chosen numbering of the letters. -/
index : α ≃ Fin size

namespace FiniteAlphabetCode

/-- Choose a code from a finite-alphabet instance. -/
noncomputable def ofFintype (α : Type) [Fintype α] : FiniteAlphabetCode α :=
⟨Fintype.card α, Fintype.equivFin α⟩

/-- A delimited unary symbol code, identical to its reversal. -/
def symbol {α : Type} (c : FiniteAlphabetCode α) (a : α) : List Bool :=
false :: List.replicate (c.index a).val true ++ [false]

/-- Concatenate the symbol codes of a word. -/
def encode {α : Type} (c : FiniteAlphabetCode α) (w : List α) : List Bool :=
w.flatMap c.symbol

/-- Decode a suffix while waiting for an opening delimiter or counting an open codeword. -/
def decodeFrom {α : Type} (c : FiniteAlphabetCode α) : Option ℕ → List Bool → Option (List α)
| none, [] => some []
| some _, [] => none
| none, false :: bs => c.decodeFrom (some 0) bs
| none, true :: _ => none
| some i, true :: bs =>
if i + 1 < c.size then c.decodeFrom (some (i + 1)) bs else none
| some i, false :: bs =>
if h : i < c.size then
(c.decodeFrom none bs).map (c.index.symm ⟨i, h⟩ :: ·)
else none

/-- Decode an entire word, rejecting every malformed code. -/
def decode {α : Type} (c : FiniteAlphabetCode α) (bits : List Bool) : Option (List α) :=
c.decodeFrom none bits

/-- Encode a function's result on valid inputs and return empty output on invalid codes. -/
def map {α β : Type} (input : FiniteAlphabetCode α) (output : FiniteAlphabetCode β)
(f : List α → List β) (bits : List Bool) : List Bool :=
match input.decode bits with
| none => []
| some w => output.encode (f w)

end FiniteAlphabetCode
end Complexity
153 changes: 153 additions & 0 deletions Complexitylib/Encoding/FiniteAlphabet/Internal.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
/-
Copyright (c) 2026 Erik Demaine. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Erik Demaine
-/

module
public import Complexitylib.Encoding.FiniteAlphabet.Defs
import Mathlib.Tactic.Linarith

/-!
# Correctness and size of finite-alphabet codes

Delimited unary parsing is exact. Its codeword lengths are bounded by an
alphabet-dependent constant and its palindromic framing commutes with reversal.
-/

@[expose] public section

namespace Complexity.FiniteAlphabetCode

variable {α : Type} (c : FiniteAlphabetCode α)

lemma encode_nil : c.encode [] = [] := rfl

lemma encode_cons (a : α) (w : List α) : c.encode (a :: w) = c.symbol a ++ c.encode w := rfl

lemma symbol_length (a : α) : (c.symbol a).length = (c.index a).val + 2 := by
simp [symbol, Nat.add_assoc]

lemma decodeFrom_trues (i k : ℕ) (h : i + k < c.size) (rest : List Bool) :
c.decodeFrom (some i) (List.replicate k true ++ rest) =
c.decodeFrom (some (i + k)) rest := by
induction k generalizing i with
| zero => simp
| succ k ih =>
rw [List.replicate_succ, List.cons_append, decodeFrom, ite_eq_left (by omega)]
simpa [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using ih (i + 1) (by omega)

lemma decodeFrom_symbol (a : α) (rest : List Bool) :
c.decodeFrom none (c.symbol a ++ rest) =
(c.decodeFrom none rest).map (a :: ·) := by
simp only [symbol, List.cons_append, decodeFrom, List.append_assoc]
rw [decodeFrom_trues c 0 (c.index a).val (by omega)]
simp [decodeFrom]

lemma decode_encode_proof (w : List α) : c.decode (c.encode w) = some w := by
change c.decodeFrom none (c.encode w) = some w
induction w with
| nil => rfl
| cons a w ih =>
rw [encode_cons, decodeFrom_symbol, ih]
rfl

lemma encode_length_lower (w : List α) : w.length ≤ (c.encode w).length := by
induction w with
| nil => simp [encode]
| cons a w ih =>
rw [encode_cons, List.length_append, symbol_length]
simp only [List.length_cons]
omega

lemma encode_length_upper (w : List α) :
(c.encode w).length ≤ (c.size + 1) * w.length := by
induction w with
| nil => simp [encode]
| cons a w ih =>
have ha := (c.index a).isLt
rw [encode_cons, List.length_append, symbol_length]
simp only [List.length_cons, Nat.mul_add, Nat.mul_one]
omega

lemma symbol_reverse (a : α) : (c.symbol a).reverse = c.symbol a := by
simp [symbol, List.reverse_append, List.reverse_replicate]

lemma encode_append (xs ys : List α) : c.encode (xs ++ ys) = c.encode xs ++ c.encode ys := by
simp [encode]

lemma encode_reverse (w : List α) : c.encode w.reverse = (c.encode w).reverse := by
induction w with
| nil => rfl
| cons a w ih =>
simp only [List.reverse_cons, encode_append, encode_cons, encode_nil,
List.append_nil, ih, List.reverse_append, symbol_reverse]

lemma encode_count_false (w : List α) : (c.encode w).count false = 2 * w.length := by
induction w with
| nil => simp [encode]
| cons a w ih =>
have hz : (List.replicate (c.index a).val true).count false = 0 :=
List.count_eq_zero_of_not_mem (by simp)
rw [encode_cons, List.count_append, ih]
simp [symbol, List.count_append, hz, Nat.mul_add, Nat.add_comm]

/-- Prefix already consumed when the parser is inside a codeword. -/
def pendingPrefix : Option ℕ → List Bool
| none => []
| some i => false :: List.replicate i true

lemma decodeFrom_exact (bits : List Bool) (pending : Option ℕ) (w : List α)
(h : c.decodeFrom pending bits = some w) :
pendingPrefix pending ++ bits = c.encode w := by
induction bits generalizing pending w with
| nil =>
cases pending with
| none => simp only [decodeFrom, Option.some.injEq] at h; subst w; rfl
| some i => simp [decodeFrom] at h
| cons b bits ih =>
cases pending with
| none =>
cases b with
| true => simp [decodeFrom] at h
| false => simpa [pendingPrefix] using ih (some 0) w h
| some i =>
cases b with
| true =>
simp only [decodeFrom] at h
split_ifs at h with hi
· simpa [pendingPrefix, List.replicate_add, List.append_assoc] using
ih (some (i + 1)) w h
| false =>
simp only [decodeFrom] at h
split_ifs at h with hi
· cases hr : c.decodeFrom none bits with
| none => simp [hr] at h
| some rest =>
simp only [hr, Option.map_some, Option.some.injEq] at h
subst w
have he := ih none rest hr
simpa [pendingPrefix, encode, symbol, List.append_assoc] using
congrArg (fun bs => (false :: List.replicate i true) ++ false :: bs) he

lemma encode_decode_proof {bits : List Bool} {w : List α}
(h : c.decode bits = some w) : c.encode w = bits :=
(decodeFrom_exact c bits none w h).symm

lemma decode_reverse (bits : List Bool) :
c.decode bits.reverse = (c.decode bits).map List.reverse := by
cases hw : c.decode bits with
| some w =>
rw [← encode_decode_proof c hw, ← encode_reverse, decode_encode_proof]
rfl
| none =>
cases hr : c.decode bits.reverse with
| none => rfl
| some w =>
have he : c.encode w.reverse = bits := by
rw [encode_reverse, encode_decode_proof c hr, List.reverse_reverse]
have hc := decode_encode_proof c w.reverse
rw [he, hw] at hc
contradiction

end Complexity.FiniteAlphabetCode
21 changes: 21 additions & 0 deletions Complexitylib/Interop.lean
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,13 @@ public import Complexitylib.Interop.Cslib.FromMultiTape.PEquiv
public import Complexitylib.Interop.Cslib.Circuit
public import Complexitylib.Interop.Cslib.CircuitClasses
public import Complexitylib.Interop.Cslib.CircuitDepth
public import Complexitylib.Interop.Cslib.Guard
public import Complexitylib.Interop.Mathlib.TM0
public import Complexitylib.Interop.Mathlib.TM0.Guard
public import Complexitylib.Interop.Mathlib.TM0.Marked
public import Complexitylib.Interop.Mathlib.TM0.Alphabet
public import Complexitylib.Interop.Mathlib.TM2
public import Complexitylib.Interop.Mathlib.TM2.FP

/-!
# Interoperability
Expand Down Expand Up @@ -42,4 +47,20 @@ Aggregation module for bridges to CSLib and Mathlib.
output length on every input imply canonical `FP` membership.
Its `Guard` interface validates regular input formats and returns empty
output on malformed strings, extending source bounds on valid inputs to `FP`.
- `Complexitylib.Interop.Mathlib.TM2` proves quadratic transition overhead for
Mathlib's existing stack-to-tape compiler, preserving the complete stack-track
input and output tapes of bundled `FinTM2` computations.
- `Complexitylib.Interop.Mathlib.TM2.FP` transfers total binary-string TM2
certificates with finite working alphabets to canonical `FP`, including the
marked empty-input representation and both reversals of stack order.
Its DFA-guarded theorem requires source bounds only on valid strings and
returns empty output on malformed strings.
Its encoded interface supports independent finite input and output alphabets,
including empty alphabets, through explicit palindromic symbol codes.
- `Complexitylib.Interop.Mathlib.TM0.Marked` handles distinct input and output
formats, including first-cell and empty-input markers.
- `Complexitylib.Interop.Mathlib.TM0.Alphabet` parses and emits codes for finite
source alphabets, rejecting invalid symbol codes before source execution.
- `Complexitylib.Interop.Cslib.Guard` validates regular input domains before
starting an arbitrary binary CSLib machine.
-/
Loading