Research | Knitting | Functor draw𝒦: Knitout drawing

Functor draw𝒦: Knitout drawing

draw𝒦 draws each knitout program as a tangle. A state goes to its number of strands. A program goes to its drawing. The drawing does not depend on the window that holds the machine. It depends only on the number of loops on each needle.

Drawings with boxes

Definitions only. A box has a label, strands in at the bottom, strands out at the top, and a plain drawing inside. A machine operation (tuck, split, knit) is a box. The theorems are BoxSame.plainSame, BoxSame.labels_perm, PlainSame.subst.

Declaration Content
BoxSig L For each label: strands in, strands out, the inside. The inside is well formed between them
BEv, BWord A drawing with boxes: events bottom to top. An event is a plain event (Gen) or a box at a position
btopWidth, BWF The top width and well-formedness of a drawing with boxes
expand Open each box: put its inside in its place
PlainSame Iso on the drawings with each box opened
Translates Two drawings with different signatures are Iso with each box opened
BRule, BStep, BoxSame The moves that do not look inside a box, one move, a chain of moves
Turn, Turn.none An optional family of extra moves with boxes, and the empty family
boxLabels The labels of the boxes, bottom to top

Box signatures

structure BoxSig (L : Type) where
  ins : L → Nat
  outs : L → Nat
  interior : L → MWord
  interior_wf : ∀ l, WF (ins l) (outs l) (interior l)

Drawings with boxes

inductive BEv (L : Type) where
  | gen (g : Gen)
  | box (l : L) (i : Nat)
  deriving DecidableEq, Repr

abbrev BWord (L : Type) := List (BEv L)

namespace BEv
variable {L : Type} (S : BoxSig L)
def fits : BEv L → Nat → Bool
  | gen g, w => g.fits w
  | box l i, w => decide (i + S.ins l ≤ w)

def widthAfter : BEv L → Nat → Nat
  | gen g, w => g.widthAfter w
  | box l _, w => w - S.ins l + S.outs l

def lo : BEv L → Nat
  | gen g => g.lo
  | box _ i => i

def ins : BEv L → Nat
  | gen g => g.ins
  | box l _ => S.ins l

def outs : BEv L → Nat
  | gen g => g.outs
  | box l _ => S.outs l

def withLo : BEv L → Nat → BEv L
  | gen g, j => gen (g.withLo j)
  | box l _, j => box l j

def inside : BEv L → MWord
  | gen g => [g]
  | box l i => shiftW i (S.interior l)
end BEv

def btopWidth {L : Type} (S : BoxSig L) : Nat → BWord L → Option Nat
  | w, [] => some w
  | w, e :: es => if e.fits S w then btopWidth S (e.widthAfter S w) es else none

def BWF {L : Type} (S : BoxSig L) (b t : Nat) (u : BWord L) : Prop := btopWidth S b u = some t

def plainB {L : Type} (u : MWord) : BWord L := u.map BEv.gen

Opening the boxes

def expand {L : Type} (S : BoxSig L) (u : BWord L) : MWord := u.flatMap (BEv.inside S)

The same without boxes

def PlainSame {L : Type} (S : BoxSig L) (b : Nat) (u v : BWord L) : Prop := Iso b (expand S u) (expand S v)

def Translates {L₁ L₂ : Type} (S₁ : BoxSig L₁) (S₂ : BoxSig L₂) (b : Nat) (H : BWord L₁) (P : BWord L₂) : Prop :=
  Iso b (expand S₁ H) (expand S₂ P)

The same with boxes

structure Turn {L : Type} (S : BoxSig L) where
  rel : BWord L → BWord L → Prop
  sound : ∀ b u v, rel u v → (btopWidth S b u).isSome → (btopWidth S b v).isSome → PlainSame S b u v

def Turn.none {L : Type} (S : BoxSig L) : Turn S where
  rel _ _ := False
  sound _ _ _ h := h.elim

inductive BRule {L : Type} (S : BoxSig L) (T : Turn S) : BWord L → BWord L → Prop
  | plain (m : Mv) : m.ok = true → BRule S T (plainB m.lhs) (plainB m.rhs)
  | far (e f : BEv L) : e.lo + e.outs S ≤ f.lo →
      BRule S T [e, f] [f.withLo (f.lo - e.outs S + e.ins S), e]
  | passL (l : L) (i : Nat) (s : Bool) :
      BRule S T (plainB (swapBlocks i 1 (S.ins l) s) ++ [.box l i])
        ([.box l (i + 1)] ++ plainB (swapBlocks i 1 (S.outs l) s))
  | passR (l : L) (i : Nat) (s : Bool) :
      BRule S T (plainB (swapBlocks i (S.ins l) 1 s) ++ [.box l (i + 1)])
        ([.box l i] ++ plainB (swapBlocks i (S.outs l) 1 s))
  | turn (u v : BWord L) : T.rel u v → BRule S T u v

def BStep {L : Type} (S : BoxSig L) (T : Turn S) (b : Nat) (u v : BWord L) : Prop :=
  (btopWidth S b u).isSome ∧ (btopWidth S b v).isSome ∧
  ∃ (p q l r : BWord L), BRule S T l r ∧ u = p ++ l ++ q ∧ v = p ++ r ++ q

def BoxSame {L : Type} (S : BoxSig L) (T : Turn S) (b : Nat) : BWord L → BWord L → Prop :=
  Relation.EqvGen (BStep S T b)

def boxLabels {L : Type} : BWord L → List L
  | [] => []
  | .gen _ :: es => boxLabels es
  | .box l _ :: es => l :: boxLabels es

Theorems on drawings with boxes

Opening boxes keeps well-formedness. The moves with boxes are sound, keep the box labels, and allow substitution.

Theorem Statement
expand_wf, expand_BWF Opening the boxes of a well-formed drawing gives a well-formed plain drawing with the same top width
far_pass, far_passL A plain drawing passes a plain drawing that shares no strand with it (plain form of L2, M1)
passL_word, passL_at, passR_at A strand that crosses each bottom strand of a drawing, with one sign, slides to its top (plain form of L1)
BRule.sound Each move with boxes is PlainSame where both sides are well formed
BoxSame.plainSame BoxSame implies PlainSame
BoxSame.labels_perm BoxSame keeps the multiset of box labels, also after a map κ that T respects
BoxSame.labels_perm_none, BoxSame.length_eq The labels without T; the number of boxes when T keeps it
PlainSame.subst, PlainSame.subst_shift A part replaced by a PlainSame part gives a PlainSame whole

PlainSame.subst is Lin et al. 2023, Lemma B.1, for drawings with boxes.

Generators: positions

theorem Gen.lo_withLo (g : Gen) (j : Nat) : (g.withLo j).lo = j
Proof
:= by cases g <;> rfl
theorem Gen.withLo_withLo (g : Gen) (j k : Nat) : (g.withLo j).withLo k = g.withLo k
Proof
:= by cases g <;> rfl
theorem Gen.ins_withLo (g : Gen) (j : Nat) : (g.withLo j).ins = g.ins
Proof
:= by cases g <;> rfl
theorem Gen.outs_withLo (g : Gen) (j : Nat) : (g.withLo j).outs = g.outs
Proof
:= by cases g <;> rfl
theorem Gen.withLo_add (g : Gen) (k : Nat) : g.withLo (g.lo + k) = g.shift k
Proof
:= by cases g <;> rfl
theorem Gen.fits_iff (g : Gen) (w : Nat) : g.fits w = true ↔ g.lo + g.ins ≤ w
Proof
:= by
  cases g <;> simp only [Gen.fits, Gen.lo, Gen.ins, decide_eq_true_eq] <;> omega
theorem Gen.widthAfter_eq {g : Gen} {w : Nat} (h : g.fits w = true) : g.widthAfter w = w - g.ins + g.outs
Proof
:= by
  rw [Gen.fits_iff] at h
  cases g <;> simp_all [Gen.widthAfter, Gen.ins, Gen.outs, Gen.lo]; omega
theorem topWidth_single {w : Nat} {g : Gen} (h : g.fits w = true) : topWidth w [g] = some (g.widthAfter w)
Proof
:= by
  simp [topWidth, h]
theorem topWidth_isSome_left {b : Nat} {u v : MWord} (h : (topWidth b (u ++ v)).isSome) : (topWidth b u).isSome
Proof
:= by
  rw [topWidth_append] at h
  cases hu : topWidth b u <;> simp_all
theorem topWidth_isSome_right {b c : Nat} {u v : MWord} (hu : topWidth b u = some c)
    (h : (topWidth b (u ++ v)).isSome) : (topWidth c v).isSome
Proof
:= by
  rw [topWidth_append, hu] at h; simpa using h
theorem isSome_of_iso {b : Nat} {u v : MWord} (h : Iso b u v) (hu : (topWidth b u).isSome) :
    (topWidth b v).isSome
Proof
:= by
  rw [← Iso.topWidth_eq h]; exact hu

Far commutation of plain drawings

theorem far_pass1 {i : Nat} (h : Gen) : ∀ {Y : MWord} {a c b : Nat}, topWidth a Y = some c → i + c ≤ h.lo →
    (topWidth b (shiftW i Y ++ [h])).isSome →
    Iso b (shiftW i Y ++ [h]) (h.withLo (h.lo - c + a) :: shiftW i Y)
Proof
  | [], a, c, b, hY, hl, _ => by
    simp only [topWidth, Option.some.injEq] at hY
    subst hY
    rw [show h.lo - a + a = h.lo by omega, Gen.withLo_lo]
    exact Iso.refl _ _
  | y :: Ys, a, c, b, hY, hl, hw => by
    obtain ⟨hf, hrest⟩ := fits_of_topWidth hY
    obtain ⟨cw, hcw⟩ := Option.isSome_iff_exists.mp hw
    have hcw' : topWidth b (y.shift i :: (shiftW i Ys ++ [h])) = some cw := by simpa [shiftW] using hcw
    obtain ⟨hf', hrest'⟩ := fits_of_topWidth hcw'
    have ih := far_pass1 (i := i) h hrest hl (b := (y.shift i).widthAfter b) (by rw [hrest']; rfl)
    have hpre : Iso b ([y.shift i] ++ (shiftW i Ys ++ [h]))
        ([y.shift i] ++ (h.withLo (h.lo - c + y.widthAfter a) :: shiftW i Ys)) :=
      Iso.prefix (by simp [topWidth, hf']) ih
    have hya := Gen.widthAfter_eq hf
    have hyf := (Gen.fits_iff y a).mp hf
    have hok : (Mv.farR (y.shift i) (h.withLo (h.lo - c + y.widthAfter a))).ok = true := by
      simp only [Mv.ok, Gen.shift_lo, Gen.shift_outs, Gen.lo_withLo, decide_eq_true_eq]
      omega
    have hw2 : topWidth b ([] ++ (Mv.farR (y.shift i) (h.withLo (h.lo - c + y.widthAfter a))).lhs ++ shiftW i Ys)
        = some cw := by
      have e := Iso.topWidth_eq hpre
      simp only [Mv.lhs, List.nil_append, List.cons_append]
      simp only [List.singleton_append] at e
      rw [← e]; exact hcw'
    have hstep := Step1.of_wf hok hw2
    simp only [Mv.lhs, Mv.rhs, Gen.lo_withLo, Gen.withLo_withLo, Gen.shift_outs, Gen.shift_ins, List.nil_append,
      List.cons_append] at hstep
    rw [show h.lo - c + y.widthAfter a - y.outs + y.ins = h.lo - c + a by omega] at hstep
    have e1 : shiftW i (y :: Ys) ++ [h] = [y.shift i] ++ (shiftW i Ys ++ [h]) := by simp [shiftW]
    have e2 : h.withLo (h.lo - c + a) :: shiftW i (y :: Ys) = h.withLo (h.lo - c + a) :: y.shift i :: shiftW i Ys := by
      simp [shiftW]
    rw [e1, e2]
    have hs : Iso b (y.shift i :: h.withLo (h.lo - c + y.widthAfter a) :: shiftW i Ys)
        (h.withLo (h.lo - c + a) :: y.shift i :: shiftW i Ys) := Relation.EqvGen.rel _ _ hstep
    exact hpre.trans hs
theorem far_pass {i a c : Nat} {Y : MWord} (hY : topWidth a Y = some c) : ∀ {Z : MWord} {b : Nat},
    (∀ g ∈ Z, i + c ≤ g.lo) → (topWidth b (shiftW i Y ++ Z)).isSome →
    Iso b (shiftW i Y ++ Z) (Z.map (fun g => g.withLo (g.lo - c + a)) ++ shiftW i Y)
Proof
  | [], b, _, _ => by simpa using Iso.refl b (shiftW i Y)
  | h :: Zs, b, hZ, hw => by
    have hw1 : (topWidth b (shiftW i Y ++ [h])).isSome :=
      topWidth_isSome_left (v := Zs) (by simpa using hw)
    have h1 := far_pass1 h hY (hZ h (by simp)) hw1
    have h2 : Iso b (shiftW i Y ++ [h] ++ Zs) ((h.withLo (h.lo - c + a) :: shiftW i Y) ++ Zs) :=
      Iso.suffix Zs h1 (by simpa using hw)
    have hw2 := isSome_of_iso h2 (by simpa using hw)
    obtain ⟨cw, hcw⟩ := Option.isSome_iff_exists.mp hw2
    obtain ⟨hf, hrest⟩ := fits_of_topWidth (by simpa using hcw)
    have ih := far_pass hY (Z := Zs) (b := (h.withLo (h.lo - c + a)).widthAfter b)
      (fun g hg => hZ g (by simp [hg])) (by rw [hrest]; rfl)
    have hpre := Iso.prefix (P := [h.withLo (h.lo - c + a)]) (topWidth_single hf) ih
    have := h2.trans (by simpa using hpre)
    simpa using this
theorem far_passL (h : Gen) : ∀ {X : MWord} {b : Nat}, (∀ g ∈ X, h.lo + h.ins ≤ g.lo) →
    (topWidth b (X ++ [h])).isSome →
    Iso b (X ++ [h]) (h :: X.map (fun g => g.withLo (g.lo + h.outs - h.ins)))
Proof
  | [], _, _, _ => by simpa using Iso.refl _ [h]
  | g :: Xs, b, hX, hw => by
    obtain ⟨cw, hcw⟩ := Option.isSome_iff_exists.mp hw
    obtain ⟨hf, hrest⟩ := fits_of_topWidth (by simpa using hcw)
    have ih := far_passL h (X := Xs) (b := g.widthAfter b) (fun g' hg' => hX g' (by simp [hg']))
      (by rw [hrest]; rfl)
    have hpre := Iso.prefix (P := [g]) (topWidth_single hf) ih
    have hok : (Mv.farL g h).ok = true := by
      simp only [Mv.ok, decide_eq_true_eq]; exact hX g (by simp)
    have hw2 : topWidth b ([] ++ (Mv.farL g h).lhs ++ Xs.map (fun g => g.withLo (g.lo + h.outs - h.ins)))
        = some cw := by
      have e := Iso.topWidth_eq hpre
      simp only [Mv.lhs, List.nil_append, List.cons_append]
      simp only [List.singleton_append] at e
      rw [← e]; simpa using hcw
    have hstep := Step1.of_wf hok hw2
    simp only [Mv.lhs, Mv.rhs, List.nil_append, List.cons_append] at hstep
    have hs : Iso b (g :: h :: Xs.map (fun g => g.withLo (g.lo + h.outs - h.ins)))
        (h :: g.withLo (g.lo + h.outs - h.ins) :: Xs.map (fun g => g.withLo (g.lo + h.outs - h.ins))) :=
      Relation.EqvGen.rel _ _ hstep
    have := hpre.trans hs
    simpa using this

Runs of crossings

def crossRun (st n : Nat) (s : Bool) : MWord := (List.range n).map fun k => Gen.cross (st + k) s
theorem swapBlocks_one_left (i n : Nat) (s : Bool) : swapBlocks i 1 n s = crossRun i n s
Proof
:= by
  simp only [swapBlocks, crossRun, List.range_one, List.map_cons, List.map_nil]
  induction List.range n <;> simp_all
theorem crossRun_add (st n m : Nat) (s : Bool) :
    crossRun st (n + m) s = crossRun st n s ++ crossRun (st + n) m s
Proof
:= by
  simp only [crossRun, List.range_add, List.map_append, List.map_map]
  congr 1
  apply List.map_congr_left
  intro k _
  simp only [Function.comp]
  congr 1; omega
theorem crossRun_two (st : Nat) (s : Bool) : crossRun st 2 s = [Gen.cross st s, Gen.cross (st + 1) s]
Proof
:= by
  simp [crossRun, List.range_succ]
theorem crossRun_zero (st : Nat) (s : Bool) : crossRun st 0 s = []
Proof
:= rfl
theorem mem_crossRun {st n : Nat} {s : Bool} {g : Gen} (h : g ∈ crossRun st n s) :
    ∃ k, g = Gen.cross k s ∧ st ≤ k ∧ k < st + n
Proof
:= by
  simp only [crossRun, List.mem_map, List.mem_range] at h
  obtain ⟨k, hk, rfl⟩ := h
  exact ⟨st + k, rfl, by omega, by omega⟩
theorem crossRun_wf {st n w : Nat} (s : Bool) (h : st + n + 1 ≤ w) : topWidth w (crossRun st n s) = some w
Proof
:= by
  apply topWidth_crosses
  intro g hg
  obtain ⟨k, rfl, -, hk⟩ := mem_crossRun hg
  exact ⟨k, s, rfl, by omega⟩
theorem crossRun_map_add (st n p q : Nat) (s : Bool) (hq : q ≤ st) :
    (crossRun st n s).map (fun g => g.withLo (g.lo + p - q)) = crossRun (st + p - q) n s
Proof
:= by
  simp only [crossRun, List.map_map]
  apply List.map_congr_left
  intro k _
  simp only [Function.comp, Gen.withLo, Gen.lo]
  congr 1; omega
theorem shiftW_crossRun (k st n : Nat) (s : Bool) : shiftW k (crossRun st n s) = crossRun (st + k) n s
Proof
:= by
  simp only [shiftW, crossRun, List.map_map]
  apply List.map_congr_left
  intro j _
  simp only [Function.comp, Gen.shift]
  congr 1; omega
def crossRunR (st n : Nat) (s : Bool) : MWord := (List.range n).map fun k => Gen.cross (st + n - 1 - k) s
theorem swapBlocks_one_right (i n : Nat) (s : Bool) : swapBlocks i n 1 s = crossRunR i n s
Proof
:= by
  simp [swapBlocks, crossRunR]
theorem crossRunR_succ (st n : Nat) (s : Bool) :
    crossRunR st (n + 1) s = Gen.cross (st + n) s :: crossRunR st n s
Proof
:= by
  simp only [crossRunR, List.range_succ_eq_map, List.map_cons, List.map_map, List.cons.injEq, Gen.cross.injEq]
  refine ⟨⟨by omega, trivial⟩, ?_⟩
  apply List.map_congr_left; intro k _; simp only [Function.comp, Gen.cross.injEq]; exact ⟨by omega, trivial⟩
theorem crossRun_succ (st n : Nat) (s : Bool) : crossRun st (n + 1) s = crossRun st n s ++ [Gen.cross (st + n) s]
Proof
:= by
  rw [crossRun_add]; simp [crossRun]
theorem crossRunR_wf {st n w : Nat} (s : Bool) (h : st + n + 1 ≤ w) : topWidth w (crossRunR st n s) = some w
Proof
:= by
  apply topWidth_crosses
  intro g hg
  simp only [crossRunR, List.mem_map, List.mem_range] at hg
  obtain ⟨k, hk, rfl⟩ := hg
  exact ⟨_, s, rfl, by omega⟩
theorem topWidth_cross_cons {b k : Nat} {t : Bool} {u : MWord} (hk : k + 1 < b) :
    topWidth b (Gen.cross k t :: u) = topWidth b u
Proof
:= by
  simp [topWidth, Gen.fits, Gen.widthAfter, hk]
theorem topWidth_cup_cons {b k : Nat} {u : MWord} (hk : k ≤ b) :
    topWidth b (Gen.cup k :: u) = topWidth (b + 2) u
Proof
:= by
  simp [topWidth, Gen.fits, Gen.widthAfter, hk]
theorem topWidth_cap_cons {b k : Nat} {u : MWord} (hk : k + 1 < b) :
    topWidth b (Gen.cap k :: u) = topWidth (b - 2) u
Proof
:= by
  simp [topWidth, Gen.fits, Gen.widthAfter, hk]
theorem topWidth_nil' (b : Nat) : topWidth b [] = some b
Proof
:= rfl
syntax "wf_tac" ("[" Lean.Parser.Tactic.simpLemma,* "]")? : tactic

macro_rules
  | `(tactic| wf_tac) => `(tactic| wf_tac [])
  | `(tactic| wf_tac [$ts,*]) => `(tactic| (
    simp (disch := omega) only [List.append_assoc, List.cons_append, List.nil_append, List.singleton_append,
      topWidth_append, Option.bind_some, topWidth_cross_cons, topWidth_cup_cons, topWidth_cap_cons, topWidth_nil',
      crossRun_wf, crossRunR_wf, Option.isSome_some, Option.some.injEq, $ts,*] <;> omega))

A strand passes a whole drawing (the plain form of L1)

theorem passL_gen (s : Bool) {g : Gen} {a b : Nat} (hg : g.fits a = true) (hb : a + 1 ≤ b) :
    Iso b (crossRun 0 a s ++ [g]) ([g.shift 1] ++ crossRun 0 (g.widthAfter a) s)
Proof
:= by
  cases g with
  | cross j t =>
    simp only [Gen.fits, decide_eq_true_eq] at hg
    obtain ⟨m, rfl⟩ : ∃ m, a = j + 2 + m := ⟨a - j - 2, by omega⟩
    have hrun : crossRun 0 (j + 2 + m) s =
        crossRun 0 j s ++ (Gen.cross j s :: Gen.cross (j + 1) s :: crossRun (j + 2) m s) := by
      rw [crossRun_add, crossRun_add, crossRun_two]; simp
    simp only [Gen.widthAfter, Gen.shift, hrun]
    have s1 : Iso b (crossRun (j + 2) m s ++ [Gen.cross j t]) (Gen.cross j t :: crossRun (j + 2) m s) := by
      have := far_passL (Gen.cross j t) (X := crossRun (j + 2) m s) (b := b)
        (fun g hg => by obtain ⟨k, rfl, hk, -⟩ := mem_crossRun hg; simp only [Gen.lo, Gen.ins]; omega)
        (by wf_tac)
      simp only [Gen.outs, Gen.ins] at this
      rwa [crossRun_map_add _ _ _ _ _ (by omega), show j + 2 + 2 - 2 = j + 2 by omega] at this
    have s2 : Iso b ([Gen.cross j s, Gen.cross (j + 1) s, Gen.cross j t] ++ crossRun (j + 2) m s)
        ([Gen.cross (j + 1) t, Gen.cross j s, Gen.cross (j + 1) s] ++ crossRun (j + 2) m s) :=
      Iso.suffix _ (r3Mixed s s t (by cases s <;> cases t <;> simp) (by omega)) (by wf_tac)
    have s3 : Iso b (crossRun 0 j s ++ [Gen.cross (j + 1) t]) ([Gen.cross (j + 1) t] ++ crossRun 0 j s) := by
      have := far_pass (i := 0) (a := j + 1) (c := j + 1)
        (crossRun_wf s (by omega) : topWidth (j + 1) (crossRun 0 j s) = some (j + 1))
        (Z := [Gen.cross (j + 1) t]) (b := b) (fun g hg => by simp at hg; subst hg; simp [Gen.lo])
        (by rw [shiftW_zero]; wf_tac)
      simpa [shiftW_zero, Gen.withLo, Gen.lo] using this
    have T1 := Iso.prefix (P := crossRun 0 j s ++ [Gen.cross j s, Gen.cross (j + 1) s])
      (b := b) (c := b) (by wf_tac) s1
    have T2 := Iso.prefix (P := crossRun 0 j s) (b := b) (c := b) (crossRun_wf s (by omega)) s2
    have T3 := Iso.suffix ([Gen.cross j s, Gen.cross (j + 1) s] ++ crossRun (j + 2) m s) s3 (by wf_tac)
    simp only [List.append_assoc, List.cons_append, List.nil_append] at T1 T2 T3 ⊢
    exact T1.trans (T2.trans T3)
  | cup j =>
    simp only [Gen.fits, decide_eq_true_eq] at hg
    obtain ⟨m, rfl⟩ : ∃ m, a = j + m := ⟨a - j, by omega⟩
    have hrun : crossRun 0 (j + m) s = crossRun 0 j s ++ crossRun j m s := by
      rw [crossRun_add]; simp
    have hrun2 : crossRun 0 (j + m + 2) s =
        crossRun 0 j s ++ (Gen.cross j s :: Gen.cross (j + 1) s :: crossRun (j + 2) m s) := by
      rw [show j + m + 2 = j + (2 + m) by omega, crossRun_add, crossRun_add, crossRun_two]; simp
    simp only [Gen.widthAfter, Gen.shift, hrun, hrun2]
    have s1 : Iso b (crossRun j m s ++ [Gen.cup j]) (Gen.cup j :: crossRun (j + 2) m s) := by
      have := far_passL (Gen.cup j) (X := crossRun j m s) (b := b)
        (fun g hg => by obtain ⟨k, rfl, hk, -⟩ := mem_crossRun hg; simp only [Gen.lo, Gen.ins]; omega)
        (by wf_tac)
      simp only [Gen.outs, Gen.ins] at this
      rwa [crossRun_map_add _ _ _ _ _ (by omega), show j + 2 - 0 = j + 2 by omega] at this
    have hwf2 : topWidth b (crossRun 0 j s ++ [Gen.cup (j + 1), Gen.cross j s, Gen.cross (j + 1) s] ++
        crossRun (j + 2) m s) = some (b + 2) := by wf_tac
    have s2 : Iso b (crossRun 0 j s ++ [Gen.cup (j + 1), Gen.cross j s, Gen.cross (j + 1) s] ++ crossRun (j + 2) m s)
        (crossRun 0 j s ++ [Gen.cup j] ++ crossRun (j + 2) m s) := by
      have := Step1.of_wf (p := crossRun 0 j s) (q := crossRun (j + 2) m s) (m := Mv.cupSlideR j s) rfl
        (by simpa [Mv.lhs] using hwf2)
      exact Relation.EqvGen.rel _ _ (by simpa [Mv.lhs, Mv.rhs] using this)
    have s3 : Iso b (crossRun 0 j s ++ [Gen.cup (j + 1)]) (Gen.cup (j + 1) :: crossRun 0 j s) :=
      cup_pass_left (fun g hg => by obtain ⟨k, rfl, -, hk⟩ := mem_crossRun hg; exact ⟨k, s, rfl, by omega⟩)
        (by wf_tac)
    have T1 := Iso.prefix (P := crossRun 0 j s) (b := b) (c := b) (crossRun_wf s (by omega)) s1
    have T3 := Iso.suffix ([Gen.cross j s, Gen.cross (j + 1) s] ++ crossRun (j + 2) m s) s3 (by wf_tac)
    simp only [List.append_assoc, List.cons_append, List.nil_append] at T1 s2 T3 ⊢
    exact T1.trans (s2.symm.trans T3)
  | cap j =>
    simp only [Gen.fits, decide_eq_true_eq] at hg
    obtain ⟨m, rfl⟩ : ∃ m, a = j + 2 + m := ⟨a - j - 2, by omega⟩
    have hrun : crossRun 0 (j + 2 + m) s =
        crossRun 0 j s ++ (Gen.cross j s :: Gen.cross (j + 1) s :: crossRun (j + 2) m s) := by
      rw [crossRun_add, crossRun_add, crossRun_two]; simp
    have hrun2 : crossRun 0 (j + 2 + m - 2) s = crossRun 0 j s ++ crossRun j m s := by
      rw [show j + 2 + m - 2 = j + m by omega, crossRun_add]; simp
    simp only [Gen.widthAfter, Gen.shift, hrun, hrun2]
    have s1 : Iso b (crossRun (j + 2) m s ++ [Gen.cap j]) (Gen.cap j :: crossRun j m s) := by
      have := far_passL (Gen.cap j) (X := crossRun (j + 2) m s) (b := b)
        (fun g hg => by obtain ⟨k, rfl, hk, -⟩ := mem_crossRun hg; simp only [Gen.lo, Gen.ins]; omega)
        (by wf_tac)
      simp only [Gen.outs, Gen.ins] at this
      rwa [crossRun_map_add _ _ _ _ _ (by omega), show j + 2 + 0 - 2 = j by omega] at this
    have T1 := Iso.prefix (P := crossRun 0 j s ++ [Gen.cross j s, Gen.cross (j + 1) s]) (b := b) (c := b)
      (by wf_tac) s1
    have hwf2 : topWidth b (crossRun 0 j s ++ [Gen.cross j s, Gen.cross (j + 1) s, Gen.cap j] ++
        crossRun j m s) = some (b - 2) := by wf_tac
    have s2 : Step1 b (crossRun 0 j s ++ (Mv.capSlideR j s).lhs ++ crossRun j m s)
        (crossRun 0 j s ++ (Mv.capSlideR j s).rhs ++ crossRun j m s) :=
      Step1.of_wf rfl (by simpa [Mv.lhs] using hwf2)
    simp only [Mv.lhs, Mv.rhs] at s2
    have S2 : Iso b _ _ := Relation.EqvGen.rel _ _ s2
    have s3 : Iso b (crossRun 0 j s ++ [Gen.cap (j + 1)]) ([Gen.cap (j + 1)] ++ crossRun 0 j s) := by
      have := far_pass (i := 0) (a := j + 1) (c := j + 1)
        (crossRun_wf s (by omega) : topWidth (j + 1) (crossRun 0 j s) = some (j + 1))
        (Z := [Gen.cap (j + 1)]) (b := b) (fun g hg => by simp at hg; subst hg; simp [Gen.lo])
        (by rw [shiftW_zero]; wf_tac)
      simpa [shiftW_zero, Gen.withLo, Gen.lo] using this
    have T3 := Iso.suffix (crossRun j m s) s3 (by wf_tac)
    simp only [List.append_assoc, List.cons_append, List.nil_append] at T1 S2 T3 ⊢
    exact T1.trans (S2.trans T3)
theorem passL_word (s : Bool) : ∀ {Y : MWord} {a c b : Nat}, topWidth a Y = some c → a + 1 ≤ b →
    Iso b (crossRun 0 a s ++ Y) (shiftW 1 Y ++ crossRun 0 c s)
Proof
  | [], a, c, b, hY, _ => by
    simp only [topWidth, Option.some.injEq] at hY; subst hY
    simpa [shiftW] using Iso.refl b (crossRun 0 a s)
  | g :: Ys, a, c, b, hY, hb => by
    obtain ⟨hf, hrest⟩ := fits_of_topWidth hY
    have h1 := passL_gen s hf hb
    have hw : (topWidth b (crossRun 0 a s ++ [g] ++ Ys)).isSome := by
      have := topWidth_shift hY 0 (b - a)
      rw [shiftW_zero, show 0 + a + (b - a) = b by omega] at this
      rw [List.append_assoc, topWidth_append, crossRun_wf s (by omega)]
      simp [this]
    have h2 := Iso.suffix Ys h1 hw
    have hgf := (Gen.fits_iff g a).mp hf
    have hf1 : (g.shift 1).fits b = true := by rw [Gen.fits_iff, Gen.shift_lo, Gen.shift_ins]; omega
    have ha' := Gen.widthAfter_eq hf
    have hb' := Gen.widthAfter_eq hf1
    rw [Gen.shift_ins, Gen.shift_outs] at hb'
    have ih := passL_word s hrest (b := (g.shift 1).widthAfter b) (by omega)
    have h3 := Iso.prefix (P := [g.shift 1]) (topWidth_single hf1) ih
    have e : shiftW 1 (g :: Ys) = g.shift 1 :: shiftW 1 Ys := rfl
    rw [e]
    simp only [List.append_assoc, List.cons_append, List.nil_append] at h2 h3 ⊢
    exact h2.trans h3
theorem passL_at (s : Bool) {Y : MWord} {a c i w : Nat} (hY : topWidth a Y = some c) (hw : i + 1 + a ≤ w) :
    Iso w (crossRun i a s ++ shiftW i Y) (shiftW (i + 1) Y ++ crossRun i c s)
Proof
:= by
  have := (passL_word s hY (le_refl (a + 1))).shift i (w - i - (a + 1))
  rw [show i + (a + 1) + (w - i - (a + 1)) = w by omega, shiftW_append, shiftW_append, shiftW_crossRun,
    shiftW_crossRun, shiftW_shiftW, Nat.zero_add, Nat.add_comm 1 i] at this
  exact this
theorem inv_RL (s : Bool) : ∀ {st n w : Nat}, st + n + 1 ≤ w → Iso w (crossRunR st n s ++ crossRun st n (!s)) []
Proof
  | _, 0, _, _ => Iso.refl _ _
  | st, n + 1, w, h => by
    rw [crossRunR_succ, crossRun_succ]
    have ih := inv_RL s (st := st) (n := n) (w := w) (by omega)
    have h1 := Iso.prefix (P := [Gen.cross (st + n) s]) (b := w) (c := w) (by wf_tac) ih
    have h2 := Iso.suffix [Gen.cross (st + n) (!s)] h1 (by wf_tac)
    have hw3 : topWidth w ([] ++ (Mv.r2 (st + n) s).lhs ++ []) = some w := by simp only [Mv.lhs]; wf_tac
    have h3 : Iso w [Gen.cross (st + n) s, Gen.cross (st + n) (!s)] [] :=
      Relation.EqvGen.rel _ _ (by simpa [Mv.lhs, Mv.rhs] using Step1.of_wf rfl hw3)
    simp only [List.append_assoc, List.cons_append, List.nil_append,
      List.append_nil] at h2 h3 ⊢
    exact h2.trans h3
theorem inv_LR (s : Bool) : ∀ {st n w : Nat}, st + n + 1 ≤ w → Iso w (crossRun st n (!s) ++ crossRunR st n s) []
Proof
  | _, 0, _, _ => Iso.refl _ _
  | st, n + 1, w, h => by
    rw [crossRunR_succ, crossRun_succ]
    have ih := inv_LR s (st := st) (n := n) (w := w) (by omega)
    have hw3 : topWidth w ([] ++ (Mv.r2 (st + n) (!s)).lhs ++ []) = some w := by simp only [Mv.lhs]; wf_tac
    have h3 : Iso w [Gen.cross (st + n) (!s), Gen.cross (st + n) s] [] :=
      Relation.EqvGen.rel _ _ (by simpa [Mv.lhs, Mv.rhs] using Step1.of_wf rfl hw3)
    have h2 := Iso.prefix (P := crossRun st n (!s)) (b := w) (c := w) (by wf_tac)
      (Iso.suffix (crossRunR st n s) h3 (by wf_tac))
    simp only [List.append_assoc, List.cons_append, List.nil_append,
      ] at h2 ih ⊢
    exact h2.trans ih
theorem passR_at (s : Bool) {Y : MWord} {a c i w : Nat} (hY : topWidth a Y = some c) (hw : i + 1 + a ≤ w) :
    Iso w (crossRunR i a s ++ shiftW (i + 1) Y) (shiftW i Y ++ crossRunR i c s)
Proof
:= by
  have hX : topWidth w (shiftW (i + 1) Y) = some (w - a + c) := by
    have := topWidth_shift hY (i + 1) (w - (i + 1) - a)
    rwa [show i + 1 + a + (w - (i + 1) - a) = w by omega,
      show i + 1 + c + (w - (i + 1) - a) = w - a + c by omega] at this
  have hY0 : topWidth w (shiftW i Y) = some (w - a + c) := by
    have := topWidth_shift hY i (w - i - a)
    rwa [show i + a + (w - i - a) = w by omega, show i + c + (w - i - a) = w - a + c by omega] at this
  have A := Iso.prefix (P := crossRunR i a s ++ shiftW (i + 1) Y) (b := w) (c := w - a + c) (by wf_tac [hX])
    (inv_LR s (st := i) (n := c) (w := w - a + c) (by omega)).symm
  have B := Iso.prefix (P := crossRunR i a s) (b := w) (c := w) (by wf_tac)
    (Iso.suffix (crossRunR i c s) (passL_at (!s) hY hw).symm (by wf_tac [hX]))
  have C := Iso.suffix (shiftW i Y ++ crossRunR i c s) (inv_RL s (st := i) (n := a) (w := w) (by omega))
    (by wf_tac [hY0])
  simp only [List.append_assoc, List.append_nil, List.nil_append] at A B C ⊢
  exact A.trans (B.trans C)

Opening boxes

section Generic
variable {L : Type} (S : BoxSig L)
def BEv.core : BEv L → MWord
  | .gen g => [g.withLo 0]
  | .box l _ => S.interior l
theorem BEv.inside_eq (e : BEv L) : e.inside S = shiftW e.lo (e.core S)
Proof
:= by
  cases e with
  | gen g => cases g <;> simp [BEv.inside, BEv.core, BEv.lo, shiftW, Gen.shift, Gen.withLo, Gen.lo]
  | box l i => rfl
theorem BEv.core_wf (e : BEv L) : topWidth (e.ins S) (e.core S) = some (e.outs S)
Proof
:= by
  cases e with
  | gen g => cases g <;> rfl
  | box l _ => exact S.interior_wf l
theorem BEv.lo_withLo (e : BEv L) (j : Nat) : (e.withLo j).lo = j
Proof
:= by
  cases e with
  | gen g => exact Gen.lo_withLo g j
  | box l _ => rfl
theorem BEv.core_withLo (e : BEv L) (j : Nat) : (e.withLo j).core S = e.core S
Proof
:= by
  cases e with
  | gen g => simp [BEv.withLo, BEv.core, Gen.withLo_withLo]
  | box l _ => rfl
theorem expand_nil : expand S ([] : BWord L) = []
Proof
:= rfl
theorem expand_cons (e : BEv L) (u : BWord L) : expand S (e :: u) = e.inside S ++ expand S u
Proof
:= by
  simp [expand]
theorem expand_append (u v : BWord L) : expand S (u ++ v) = expand S u ++ expand S v
Proof
:= by
  simp [expand]
theorem expand_plainB (u : MWord) : expand S (plainB u : BWord L) = u
Proof
:= by
  induction u with
  | nil => rfl
  | cons g gs ih => simp only [plainB, List.map_cons] at ih ⊢; rw [expand_cons, ih]; rfl
theorem btopWidth_append (a : Nat) (u v : BWord L) :
    btopWidth S a (u ++ v) = (btopWidth S a u).bind (fun c => btopWidth S c v)
Proof
:= by
  induction u generalizing a with
  | nil => simp [btopWidth]
  | cons g gs ih =>
    simp only [List.cons_append, btopWidth]
    split <;> simp_all
theorem btopWidth_plainB (w : Nat) (u : MWord) : btopWidth S w (plainB u : BWord L) = topWidth w u
Proof
:= by
  induction u generalizing w with
  | nil => rfl
  | cons g gs ih =>
    simp only [plainB, List.map_cons, btopWidth, topWidth, BEv.fits, BEv.widthAfter] at ih ⊢
    split <;> simp_all
theorem btopWidth_cons_fits {w : Nat} {e : BEv L} {u : BWord L} (h : (btopWidth S w (e :: u)).isSome) :
    e.fits S w = true
Proof
:= by
  simp only [btopWidth] at h
  split at h
  · assumption
  · simp at h
theorem BEv.inside_wf {e : BEv L} {w : Nat} (h : e.fits S w = true) :
    topWidth w (e.inside S) = some (e.widthAfter S w)
Proof
:= by
  cases e with
  | gen g => exact topWidth_single h
  | box l i =>
    simp only [BEv.fits, decide_eq_true_eq] at h
    have := topWidth_shift (S.interior_wf l) i (w - i - S.ins l)
    simp only [BEv.inside, BEv.widthAfter]
    rwa [show i + S.ins l + (w - i - S.ins l) = w by omega,
      show i + S.outs l + (w - i - S.ins l) = w - S.ins l + S.outs l by omega] at this
theorem expand_wf : ∀ {b t : Nat} {u : BWord L}, btopWidth S b u = some t → topWidth b (expand S u) = some t
Proof
  | b, t, [], h => by simp only [btopWidth, Option.some.injEq] at h; subst h; rfl
  | b, t, e :: es, h => by
    simp only [btopWidth] at h
    split at h
    · rename_i hf
      rw [expand_cons]
      exact topWidth_append_of (BEv.inside_wf S hf) (expand_wf h)
    · exact absurd h (by simp)
theorem expand_BWF {b t : Nat} {u : BWord L} (h : BWF S b t u) : WF b t (expand S u)
Proof
:= expand_wf S h
theorem btopWidth_split {b t : Nat} {p l q : BWord L} (h : btopWidth S b (p ++ l ++ q) = some t) :
    ∃ w x, btopWidth S b p = some w ∧ btopWidth S w l = some x ∧ btopWidth S x q = some t
Proof
:= by
  rw [btopWidth_append, btopWidth_append] at h
  cases hp : btopWidth S b p with
  | none => simp [hp] at h
  | some w =>
    cases hl : btopWidth S w l with
    | none => simp [hp, hl] at h
    | some x => exact ⟨w, x, rfl, hl, by simpa [hp, hl] using h⟩
theorem map_relo_shiftW (k c a : Nat) (U : MWord) (h : c ≤ k) :
    (shiftW k U).map (fun g => g.withLo (g.lo - c + a)) = shiftW (k - c + a) U
Proof
:= by
  simp only [shiftW, List.map_map]
  apply List.map_congr_left
  intro g _
  simp only [Function.comp, Gen.shift_lo, Gen.withLo_shift]
  rw [show g.lo + k - c + a = g.lo + (k - c + a) by omega, Gen.withLo_add]
theorem BRule.sound {T : Turn S} {l r : BWord L} (h : BRule S T l r) {w : Nat}
    (hl : (btopWidth S w l).isSome) (hr : (btopWidth S w r).isSome) : PlainSame S w l r
Proof
:= by
  unfold PlainSame
  cases h with
  | plain m hok =>
    rw [expand_plainB, expand_plainB]
    rw [btopWidth_plainB] at hl
    obtain ⟨c, hc⟩ := Option.isSome_iff_exists.mp hl
    have := Step1.of_wf (p := []) (q := []) hok (by simpa using hc)
    have h2 : Iso w ([] ++ m.lhs ++ []) ([] ++ m.rhs ++ []) := Relation.EqvGen.rel _ _ this
    simpa using h2
  | far e f hef =>
    obtain ⟨c, hc⟩ := Option.isSome_iff_exists.mp hl
    have hwf := expand_wf S hc
    simp only [expand_cons, expand_nil, List.append_nil] at hwf ⊢
    rw [BEv.inside_eq S e, BEv.inside_eq S f] at hwf
    rw [BEv.inside_eq S e, BEv.inside_eq S f, BEv.inside_eq S (f.withLo _), BEv.lo_withLo, BEv.core_withLo]
    have := far_pass (BEv.core_wf S e) (Z := shiftW f.lo (f.core S)) (b := w)
      (fun g hg => le_trans hef (shiftW_lo_ge g hg)) (by rw [hwf]; rfl)
    rwa [map_relo_shiftW f.lo (e.outs S) (e.ins S) (f.core S) (by omega)] at this
  | passL l i s =>
    have hf := btopWidth_cons_fits S (by simpa using hr)
    simp only [BEv.fits, decide_eq_true_eq] at hf
    simp only [expand_append, expand_plainB, expand_cons, expand_nil, List.append_nil, BEv.inside,
      swapBlocks_one_left]
    exact passL_at s (S.interior_wf l) (by omega)
  | passR l i s =>
    have hf : i + 1 + S.ins l ≤ w := by
      rcases Nat.eq_zero_or_pos (S.ins l) with h0 | hpos
      · rw [h0] at hl ⊢
        have := btopWidth_cons_fits S (by simpa [swapBlocks, plainB] using hl)
        simpa [BEv.fits, h0] using this
      · obtain ⟨n, hn⟩ : ∃ n, S.ins l = n + 1 := ⟨S.ins l - 1, by omega⟩
        rw [hn] at hl ⊢
        rw [swapBlocks_one_right, crossRunR_succ] at hl
        have := btopWidth_cons_fits S (by simpa [plainB] using hl)
        simp [BEv.fits, Gen.fits] at this
        omega
    simp only [expand_append, expand_plainB, expand_cons, expand_nil, List.append_nil, BEv.inside,
      swapBlocks_one_right]
    exact passR_at s (S.interior_wf l) (by omega)
  | turn _ _ ht => exact T.sound w l r ht hl hr
theorem BStep.plainSame {T : Turn S} {b : Nat} {u v : BWord L} (h : BStep S T b u v) : PlainSame S b u v
Proof
:= by
  obtain ⟨hu, hv, p, q, l, r, hr, rfl, rfl⟩ := h
  obtain ⟨tu, htu⟩ := Option.isSome_iff_exists.mp hu
  obtain ⟨tv, htv⟩ := Option.isSome_iff_exists.mp hv
  obtain ⟨w, x, hp, hl, hq⟩ := btopWidth_split S htu
  obtain ⟨w', x', hp', hr', -⟩ := btopWidth_split S htv
  rw [hp, Option.some.injEq] at hp'
  subst hp'
  have hs := hr.sound S (by rw [hl]; rfl) (by rw [hr']; rfl)
  unfold PlainSame at hs ⊢
  have hlq : (topWidth w (expand S l ++ expand S q)).isSome := by
    rw [← expand_append, expand_wf S (t := tu) (by rw [btopWidth_append, hl]; simpa using hq)]; rfl
  simp only [expand_append, List.append_assoc]
  exact Iso.prefix (expand_wf S hp) (Iso.suffix _ hs hlq)
theorem BoxSame.plainSame {T : Turn S} {b : Nat} {u v : BWord L} (h : BoxSame S T b u v) : PlainSame S b u v
Proof
:= by
  induction h with
  | rel _ _ h => exact h.plainSame S
  | refl => exact Iso.refl _ _
  | symm _ _ _ ih => exact Iso.symm ih
  | trans _ _ _ _ _ ih1 ih2 => exact Iso.trans ih1 ih2

The moves with boxes keep the boxes

theorem boxLabels_append (u v : BWord L) : boxLabels (u ++ v) = boxLabels u ++ boxLabels v
Proof
:= by
  induction u with
  | nil => rfl
  | cons e es ih => cases e <;> simp [boxLabels, ih]
theorem boxLabels_plainB (u : MWord) : boxLabels (plainB u : BWord L) = []
Proof
:= by
  induction u with
  | nil => rfl
  | cons g gs ih => simpa [plainB, boxLabels] using ih
theorem BRule.labels_perm {M : Type} (κ : L → M) {T : Turn S}
    (hT : ∀ u v, T.rel u v → ((boxLabels u).map κ).Perm ((boxLabels v).map κ)) {l r : BWord L}
    (h : BRule S T l r) : ((boxLabels l).map κ).Perm ((boxLabels r).map κ)
Proof
:= by
  cases h with
  | plain => simp [boxLabels_plainB]
  | far e f _ => cases e <;> cases f <;> simp [boxLabels, BEv.withLo]; exact List.Perm.swap _ _ _
  | passL => simp [boxLabels_append, boxLabels_plainB, boxLabels]
  | passR => simp [boxLabels_append, boxLabels_plainB, boxLabels]
  | turn _ _ ht => exact hT l r ht
theorem BoxSame.labels_perm {M : Type} (κ : L → M) {T : Turn S}
    (hT : ∀ u v, T.rel u v → ((boxLabels u).map κ).Perm ((boxLabels v).map κ)) {b : Nat} {u v : BWord L}
    (h : BoxSame S T b u v) : ((boxLabels u).map κ).Perm ((boxLabels v).map κ)
Proof
:= by
  induction h with
  | rel _ _ h =>
    obtain ⟨-, -, p, q, l, r, hr, rfl, rfl⟩ := h
    simp only [boxLabels_append, List.map_append]
    exact ((hr.labels_perm S κ hT).append_left _).append_right _
  | refl => exact List.Perm.refl _
  | symm _ _ _ ih => exact ih.symm
  | trans _ _ _ _ _ ih1 ih2 => exact ih1.trans ih2
theorem BoxSame.labels_perm_none {b : Nat} {u v : BWord L} (h : BoxSame S (Turn.none S) b u v) :
    (boxLabels u).Perm (boxLabels v)
Proof
:= by
  simpa using h.labels_perm S id (fun _ _ h => False.elim h)
theorem BoxSame.length_eq {T : Turn S}
    (hT : ∀ u v, T.rel u v → (boxLabels u).length = (boxLabels v).length) {b : Nat} {u v : BWord L}
    (h : BoxSame S T b u v) : (boxLabels u).length = (boxLabels v).length
Proof
:= by
  have := h.labels_perm S (fun _ => ()) (fun u v huv => by
    rw [List.perm_iff_count]; intro a; simp [List.count_eq_length.mpr, hT u v huv])
  simpa using this.length_eq

Substitution

theorem PlainSame.subst {b w : Nat} {A B h p : BWord L} (hA : btopWidth S b A = some w)
    (hhp : PlainSame S w h p) (hwf : (btopWidth S b (A ++ h ++ B)).isSome) :
    PlainSame S b (A ++ h ++ B) (A ++ p ++ B)
Proof
:= by
  obtain ⟨t, ht⟩ := Option.isSome_iff_exists.mp hwf
  obtain ⟨w', x, hA', hh, hB⟩ := btopWidth_split S ht
  rw [hA, Option.some.injEq] at hA'
  subst hA'
  unfold PlainSame at hhp ⊢
  have hhB : (topWidth w (expand S h ++ expand S B)).isSome := by
    rw [← expand_append, expand_wf S (t := t) (by rw [btopWidth_append, hh]; simpa using hB)]; rfl
  simp only [expand_append, List.append_assoc]
  exact Iso.prefix (expand_wf S hA) (Iso.suffix _ hhp hhB)
theorem subst_btopWidth {b w : Nat} {A B h p : BWord L} (hA : btopWidth S b A = some w)
    (htop : btopWidth S w h = btopWidth S w p) :
    btopWidth S b (A ++ p ++ B) = btopWidth S b (A ++ h ++ B)
Proof
:= by
  simp [btopWidth_append, hA, htop]
def BEv.shift {L : Type} (k : Nat) : BEv L → BEv L
  | .gen g => .gen (g.shift k)
  | .box l i => .box l (i + k)

def shiftB {L : Type} (k : Nat) (u : BWord L) : BWord L := u.map (BEv.shift k)
theorem expand_shiftB (k : Nat) (u : BWord L) : expand S (shiftB k u) = shiftW k (expand S u)
Proof
:= by
  induction u with
  | nil => rfl
  | cons e es ih =>
    simp only [shiftB, List.map_cons] at ih ⊢
    rw [expand_cons, expand_cons, ih, shiftW_append]
    cases e with
    | gen g => rfl
    | box l i => simp only [BEv.shift, BEv.inside, shiftW_shiftW]
theorem PlainSame.shift {w : Nat} {h p : BWord L} (hhp : PlainSame S w h p) (k e : Nat) :
    PlainSame S (k + w + e) (shiftB k h) (shiftB k p)
Proof
:= by
  unfold PlainSame at hhp ⊢
  rw [expand_shiftB, expand_shiftB]
  exact hhp.shift k e
theorem PlainSame.subst_shift {b w k e : Nat} {A B h p : BWord L} (hA : btopWidth S b A = some (k + w + e))
    (hhp : PlainSame S w h p) (hwf : (btopWidth S b (A ++ shiftB k h ++ B)).isSome) :
    PlainSame S b (A ++ shiftB k h ++ B) (A ++ shiftB k p ++ B)
Proof
:=
  PlainSame.subst S hA (hhp.shift S k e) hwf

The box labels of the knitout drawing denoteOp1

The tuck, the split through one loop, and the knit through k loops, as boxes.

  • PlainLabel: the labels.
  • plainSig: the signature. The insides are tuckInterior, splitInterior, knitInterior.
  • denoteOp1 draws knitout with these boxes. denote1 refuses a split of a needle with more than one loop.
  • PlainLabel.toLabel and liftB take these labels to the shorthand signature sig.
inductive PlainLabel where
  | tuck (d : Dir)
  | split (d : Dir) (bd : Bed)
  | knit (d : Dir) (bd : Bed) (k : Nat)
  deriving DecidableEq, Repr

namespace PlainLabel
def ins : PlainLabel → Nat
  | tuck _ => 1
  | split .. => 3
  | knit _ _ k => 2 * k + 1

def outs : PlainLabel → Nat
  | tuck _ => 3
  | split .. => 5
  | knit .. => 3

def interior : PlainLabel → MWord
  | tuck d => tuckInterior d
  | split d bd => splitInterior d bd
  | knit d bd k => knitInterior d bd k
end PlainLabel

def plainSig : BoxSig PlainLabel where
  ins := PlainLabel.ins
  outs := PlainLabel.outs
  interior := PlainLabel.interior
  interior_wf l := by
    cases l with
    | tuck d => exact tuckInterior_wf d
    | split d bd => exact splitInterior_wf d bd
    | knit d bd k => exact knitInterior_wf d bd k

The drawing of the split-free machine

denote1 draws a program that the split-free machine step1 runs. The proofs use it as a tool. The knitout drawing is denote. denote is denote1 except on a split of a needle with two or more loops.

Declaration Content
Window A finite stretch of physical positions lo, …, lo + w - 1
strandsBefore, yarnAt, frontAt, backAt Strand counts at a physical position
rackBraid The drawing of a rack
denoteOp1 The drawing with boxes of one instruction
windowOk The window refusals: each named needle is strictly inside the window
denote1, denotePlain1 The drawing with boxes of a program, and the plain drawing
initState, spanning, denoteCrate1, denotePlainCrate1 A starting machine from a list of loops, its window, and its drawings
windowWidth The number of strands across the window
  • Each instruction draws a short piece, bottom to top. The pieces are stacked in program order.
  • The strands are the points of the machine left to right (Lin Def. 5.5, points). For each position: the carrier, the loops of the front needle, the loops of the back needle across from it.
  • Strand positions are counted from the left edge of the window (strandsBefore).
  • A rack draws one braid at each position of the window (rackBraid).
  • The drawing uses only the number of loops on each needle, the rack and the carrier. It does not use the loop identities.
namespace Knitout
structure Window where
  lo : Int
  w : Nat
  deriving DecidableEq, Repr

def strandsBefore (win : Window) (s : State) (i : Int) : Nat := cellRowWidth (rowOf1 s win.lo (i - win.lo).toNat)

def yarnAt (s : State) (i : Int) : Nat := if s.carrier = i then 1 else 0

def frontAt (s : State) (i : Int) : Nat := 2 * (s.stk ⟨.f, i⟩).length

def backAt (s : State) (i : Int) : Nat := 2 * (s.stk ⟨.b, i - s.rack⟩).length

def swapB (at_ left right : Nat) (lo : Bool) : BWord PlainLabel := plainB (swapBlocks at_ left right lo)

def rackBraid (win : Window) (s : State) (r : Int) : BWord PlainLabel :=
  (List.range win.w).flatMap fun k =>
    let i := win.lo + k
    let fixed := yarnAt s i + frontAt s i
    if r < s.rack then
      swapB (strandsBefore win s i) fixed (backAt s i) true
    else
      let behind := 2 * (s.stk ⟨.b, i - 1 - s.rack⟩).length
      swapB (strandsBefore win s i - behind) behind fixed false
denoteOp1: 45 lines of Lean
def denoteOp1 (win : Window) (s : State) : Op → BWord PlainLabel
  | .xfer _ _ => []
  | .rack r => rackBraid win s r
  | .miss d n =>
    let z := slot s.rack n
    let F := frontAt s z
    let K := backAt s z
    let y := strandsBefore win s (arrivesFrom d z)
    match d with
    | .R => swapB y 1 F false ++ swapB (y + F) 1 K true
    | .L => swapB (y - K) K 1 false ++ swapB (y - K - F) F 1 true
  | .knit d n =>
    let z := slot s.rack n
    let F := frontAt s z
    let K := backAt s z
    let y := strandsBefore win s (arrivesFrom d z)
    let l := PlainLabel.knit d n.bed (s.stk n).length
    match d, n.bed with
    | .R, .f => [.box l y] ++ swapB (y + 2) 1 K true
    | .R, .b => swapB y 1 F false ++ [.box l (y + F)]
    | .L, .f => swapB (y - K) K 1 false ++ [.box l (y - K - F)]
    | .L, .b => [.box l (y - K)] ++ swapB (y - K - F) F 1 true
  | .tuck d n =>
    let z := slot s.rack n
    let F := frontAt s z
    let K := backAt s z
    let y := strandsBefore win s (arrivesFrom d z)
    match d with
    | .R => swapB y 1 F false ++ [.box (.tuck .R) (y + F)] ++ swapB (y + F + 2) 1 K true
    | .L => swapB (y - K) K 1 false ++ [.box (.tuck .L) (y - K)] ++ swapB (y - K - F) F 1 true
  | .split d n _ =>
    let z := slot s.rack n
    let F := frontAt s z
    let K := backAt s z
    let y := strandsBefore win s (arrivesFrom d z)
    let l := PlainLabel.split d n.bed
    match d, n.bed with
    | .R, .f => [.box l y] ++ swapB (y + 4) 1 K true
    | .R, .b => swapB y 1 F false ++ [.box l (y + F)]
    | .L, .f => swapB (y - K) K 1 false ++ [.box l (y - K - F)]
    | .L, .b => [.box l (y - K)] ++ swapB (y - K - F) F 1 true
  | .drop n =>
    let z := slot s.rack n
    let first := strandsBefore win s z + yarnAt s z + (if n.bed = .b then frontAt s z else 0)
    (List.replicate (s.stk n).length (Gen.cap first)).map BEv.gen
def Window.inside (win : Window) (z : Int) : Bool := decide (win.lo < z ∧ z < win.lo + win.w - 1)

def windowOk (win : Window) (s : State) : Op → Bool
  | .xfer a b => win.inside (slot s.rack a) && win.inside (slot s.rack b)
  | .rack r => (List.range win.w).all fun k => (s.stk ⟨.b, win.lo + k⟩).isEmpty || win.inside (win.lo + k + r)
  | .knit _ n | .tuck _ n | .miss _ n | .drop n => win.inside (slot s.rack n)
  | .split _ n m => win.inside (slot s.rack n) && win.inside (slot s.rack m)

def denote1 (win : Window) : State → List Op → Option (State × BWord PlainLabel)
  | s, [] => some (s, [])
  | s, op :: ops =>
    match step1 s op with
    | .error _ => none
    | .ok s' =>
      if windowOk win s op then
        match denote1 win s' ops with
        | none => none
        | some (t, u) => some (t, denoteOp1 win s op ++ u)
      else none

def denotePlain1 (win : Window) (s : State) (ops : List Op) : Option (State × MWord) :=
  (denote1 win s ops).map fun p => (p.1, expand plainSig p.2)

A starting machine and its window

def pushFresh (s : State) (n : Needle) : Nat → State
  | 0 => s
  | k + 1 => pushFresh { s with stk := Function.update s.stk n (s.fresh :: s.stk n), fresh := s.fresh + 1 } n k

def place (s : State) : List (Needle × Nat) → State
  | [] => s
  | (n, k) :: rest => place (pushFresh s n k) rest

def initState (loops : List (Needle × Nat)) (yarnAt : Int) : State := place ⟨0, fun _ => [], yarnAt, 0⟩ loops

def Op.named : Op → List Int
  | .xfer a b => [a.idx, b.idx]
  | .split _ a b => [a.idx, b.idx]
  | .knit _ n | .tuck _ n | .miss _ n | .drop n => [n.idx]
  | .rack _ => []

def rackReach : Int := 12

def spanning (loops : List (Needle × Nat)) (yarnAt : Int) (ops : List Op) : Window :=
  let reach := loops.map (·.1.idx) ++ ops.flatMap Op.named
  let lo := reach.foldl min yarnAt - rackReach
  let hi := reach.foldl max yarnAt + rackReach
  ⟨lo, (hi - lo + 1).toNat⟩

def denoteCrate1 (loops : List (Needle × Nat)) (yarnAt : Int) (ops : List Op) : Option (State × BWord PlainLabel) :=
  denote1 (spanning loops yarnAt ops) (initState loops yarnAt) ops

def denotePlainCrate1 (loops : List (Needle × Nat)) (yarnAt : Int) (ops : List Op) : Option (State × MWord) :=
  (denoteCrate1 loops yarnAt ops).map fun p => (p.1, expand plainSig p.2)

def windowWidth (win : Window) (s : State) : Nat := cellRowWidth (rowOf1 s win.lo win.w)
end Knitout

Well-formed drawings of transfers and tucks

Lin Def. 5.6: the drawing of a valid instruction goes from the points of s to the points of s'. This file states it as OpWF and proves it for xfer and tuck.

Declaration Content
W, segW, width_split Strand counts over the window, and their split around positions z, z + 1
seg1_far An instruction other than a rack changes no position other than z, z + 1
btop_swapB, btop_box, btop_caps Each event of a drawing fits, by arithmetic
denoteOp1_wf_xfer, denoteOp1_wf_tuck The drawing of xfer and of tuck is well formed
OpWF op If step1 s op = .ok s' and windowOk win s op, then denoteOp1 win s op is BWF plainSig from windowWidth win s to windowWidth win s'
DropWF, KnitWF, SplitWF, MissWF, RackWF OpWF for each instruction of one kind
opWF_all, denote1_wf OpWF for each instruction, and for programs, from the five hypotheses
denote1_wf_xfer_tuck denote1 is well formed for a program of transfers and tucks

Status of the five statements:

Statement Status
DropWF, KnitWF, SplitWF, MissWF Proved: dropWF, knitWF, splitWF, missWF
RackWF False: not_rackWF
  • RackWF is false. So the hypotheses of opWF_all and denote1_wf cannot all hold.
  • The true rack statement adds the hypothesis BackIn: denoteOp1_wf_rack.
  • The program statements that hold are denote1_wf' and denoteCrate1_wf.

Strand counts over the window

def W (s : State) (lo : Int) (w : Nat) : Nat := cellRowWidth (rowOf1 s lo w)

def segW (s : State) (i : Int) : Nat := cellRowWidth ((seg1 s i).map Pt.obj)
theorem cellRowWidth_map_loop (l : List Nat) : cellRowWidth ((l.map Pt.loop).map Pt.obj) = 2 * l.length
Proof
:= by
  induction l with
  | nil => rfl
  | cons x xs ih =>
    simp only [List.map_cons, cellRowWidth_cons, Pt.obj, CellObj.width, List.length_cons] at ih ⊢
    omega
theorem segW_eq (s : State) (i : Int) : segW s i = yarnAt s i + frontAt s i + backAt s i
Proof
:= by
  unfold segW seg1 yarnAt frontAt backAt
  simp only [List.map_append, cellRowWidth_append, cellRowWidth_map_loop, leftToRight, List.length_reverse]
  by_cases h : s.carrier = i <;> simp [h, cellRowWidth, Pt.obj, CellObj.width]
theorem W_zero (s : State) (lo : Int) : W s lo 0 = 0
Proof
:= rfl
theorem W_succ (s : State) (lo : Int) (w : Nat) : W s lo (w + 1) = W s lo w + segW s (lo + w)
Proof
:= by
  unfold W rowOf1 points segW
  simp [List.range_succ, List.flatMap_append, List.map_append, cellRowWidth_append]
theorem W_add (s : State) (lo : Int) (a b : Nat) : W s lo (a + b) = W s lo a + W s (lo + a) b
Proof
:= by
  induction b with
  | zero => rfl
  | succ b ih =>
    rw [← Nat.add_assoc, W_succ, ih, W_succ]
    have : lo + ((a + b : Nat) : Int) = lo + a + b := by push_cast; omega
    rw [this]; omega
theorem W_congr {s t : State} {lo : Int} {w : Nat} (h : ∀ k : Nat, k < w → seg1 s (lo + k) = seg1 t (lo + k)) :
    W s lo w = W t lo w
Proof
:= by
  induction w with
  | zero => rfl
  | succ w ih =>
    rw [W_succ, W_succ, ih (fun k hk => h k (by omega))]
    unfold segW; rw [h w (by omega)]
theorem W_one (s : State) (i : Int) : W s i 1 = segW s i
Proof
:= by
  rw [W_succ, W_zero]; simp
theorem width_split (s s' : State) (lo : Int) (w : Nat) (z : Int) (h1 : lo ≤ z) (h2 : z + 1 < lo + w)
    (hfar : ∀ i, i ≠ z → i ≠ z + 1 → seg1 s' i = seg1 s i) :
    ∃ B A, W s lo w = B + segW s z + segW s (z + 1) + A ∧ W s' lo w = B + segW s' z + segW s' (z + 1) + A ∧
      strandsBefore ⟨lo, w⟩ s z = B ∧ strandsBefore ⟨lo, w⟩ s (z + 1) = B + segW s z ∧
      strandsBefore ⟨lo, w⟩ s' z = B
Proof
:= by
  set a := (z - lo).toNat with ha
  have hz : lo + a = z := by omega
  have hw : w = a + 1 + 1 + (w - a - 2) := by omega
  have key : ∀ t : State, W t lo w = W t lo a + segW t z + segW t (z + 1) + W t (z + 2) (w - a - 2) := by
    intro t
    conv_lhs => rw [hw]
    rw [W_add, W_add, W_add, hz, W_one, W_one]
    have e1 : lo + ((a + 1 : Nat) : Int) = z + 1 := by omega
    have e2 : lo + ((a + 1 + 1 : Nat) : Int) = z + 2 := by omega
    rw [e1, e2]
  refine ⟨W s lo a, W s (z + 2) (w - a - 2), key s, ?_, ?_, ?_, ?_⟩
  · rw [key s', W_congr (s := s') (t := s) (fun k hk => hfar _ (by omega) (by omega)),
      W_congr (s := s') (t := s) (lo := z + 2) (fun k hk => hfar _ (by omega) (by omega))]
  · unfold strandsBefore; rfl
  · unfold strandsBefore
    have : (z + 1 - lo).toNat = a + 1 := by omega
    rw [show cellRowWidth (rowOf1 s lo (z + 1 - lo).toNat) = W s lo (z + 1 - lo).toNat from rfl, this, W_succ, hz]
  · unfold strandsBefore
    exact W_congr (fun k hk => hfar _ (by omega) (by omega))
theorem seg1_congr {s t : State} {i : Int} (hr : t.rack = s.rack) (hc : (t.carrier = i) ↔ (s.carrier = i))
    (hf : t.stk ⟨.f, i⟩ = s.stk ⟨.f, i⟩) (hb : t.stk ⟨.b, i - s.rack⟩ = s.stk ⟨.b, i - s.rack⟩) :
    seg1 t i = seg1 s i
Proof
:= by
  unfold seg1 leftToRight
  simp only [hr, hf, hb]
  by_cases h : s.carrier = i <;> simp [h, hc.mpr, hc]

Drawings with boxes: the events fit

theorem btop_swapB (w i l r : Nat) (b : Bool) (u : BWord PlainLabel) (h : i + l + r ≤ w) :
    btopWidth plainSig w (swapB i l r b ++ u) = btopWidth plainSig w u
Proof
:= by
  unfold swapB
  rw [btopWidth_append, btopWidth_plainB, swapBlocks_wf b h]
  rfl
theorem btop_swapB_end (w i l r : Nat) (b : Bool) (h : i + l + r ≤ w) :
    btopWidth plainSig w (swapB i l r b) = some w
Proof
:= by
  have := btop_swapB w i l r b [] h
  rwa [List.append_nil] at this
theorem btop_box (w i : Nat) (l : PlainLabel) (u : BWord PlainLabel) (h : i + l.ins ≤ w) :
    btopWidth plainSig w (.box l i :: u) = btopWidth plainSig (w - l.ins + l.outs) u
Proof
:= by
  have h' : i + plainSig.ins l ≤ w := h
  simp only [btopWidth, BEv.fits, BEv.widthAfter, h', decide_true, ↓reduceIte]
  rfl
theorem btop_caps (k i w : Nat) (h : i + 2 * k ≤ w) (h2 : 0 < k ∨ True) :
    btopWidth plainSig w ((List.replicate k (Gen.cap i)).map BEv.gen) = some (w - 2 * k)
Proof
:= by
  induction k generalizing w with
  | zero => rfl
  | succ k ih =>
    have hi : i + 1 < w := by omega
    simp only [List.replicate_succ, List.map_cons, btopWidth, BEv.fits, Gen.fits, BEv.widthAfter, Gen.widthAfter,
      hi, decide_true, ↓reduceIte]
    rw [ih (w - 2) (by omega) (Or.inr trivial)]
    congr 1; omega
theorem btop_nil (w : Nat) : btopWidth plainSig w ([] : BWord PlainLabel) = some w
Proof
:= rfl

Instructions other than a rack change nothing away from their position

theorem seg1_far {s t : State} {z : Int} (hr : t.rack = s.rack)
    (hloc : ∀ n : Needle, slot s.rack n ≠ z → t.stk n = s.stk n)
    (hc : (s.carrier = z ∨ s.carrier = z + 1) ∧ (t.carrier = z ∨ t.carrier = z + 1)) :
    ∀ i, i ≠ z → i ≠ z + 1 → seg1 t i = seg1 s i
Proof
:= by
  intro i h1 h2
  apply seg1_congr hr
  · constructor <;> intro h <;> omega
  · exact hloc _ (by simp [slot]; exact h1)
  · exact hloc _ (by simp [slot]; exact h1)
theorem upd_ne {f : Needle → List Nat} {a n : Needle} {v : List Nat} (h : n ≠ a) :
    Function.update f a v n = f n
Proof
:= Function.update_of_ne h _ _
theorem needle_ne_of_slot {r z : Int} {a n : Needle} (ha : slot r a = z) (hn : slot r n ≠ z) : n ≠ a
Proof
:= by
  rintro rfl; exact hn ha

The instructions, one by one

theorem denoteOp1_wf_xfer {win : Window} {s s' : State} {a b : Needle} (h : step1 s (.xfer a b) = .ok s') :
    BWF plainSig (windowWidth win s) (windowWidth win s') (denoteOp1 win s (.xfer a b))
Proof
:= by
  obtain ⟨hv, rfl⟩ := step1_ok.mp h
  have := points_xfer s a b (validCrate_validLin hv) win.lo win.w
  simp only [BWF, denoteOp1, btopWidth, windowWidth, rowOf1, this]
theorem denoteOp1_wf_tuck {win : Window} {s s' : State} {d : Dir} {n : Needle} (h : step1 s (.tuck d n) = .ok s')
    (hw : windowOk win s (.tuck d n) = true) :
    BWF plainSig (windowWidth win s) (windowWidth win s') (denoteOp1 win s (.tuck d n))
Proof
:= by
  obtain ⟨hv, rfl⟩ := step1_ok.mp h
  obtain ⟨lo, w⟩ := win
  obtain ⟨bd, j⟩ := n
  have hf : bd = .f := by
    cases bd
    · rfl
    · simp [validCrate, crateRefusal1, linRefusal, crateExtra1] at hv; split_ifs at hv
  subst hf
  have hc : s.carrier = arrivesFrom d j := by
    simp only [validCrate, crateRefusal1, linRefusal, crateExtra1, erase, slot] at hv
    split_ifs at hv with h1 <;> simp_all
  have hin : lo < j ∧ j < lo + w - 1 := by
    simp only [windowOk, Window.inside, slot] at hw; exact of_decide_eq_true hw
  have hfar := seg1_far (s := s) (t := apply s (.tuck d ⟨.f, j⟩)) (z := j) rfl
    (fun m hm => by simp only [apply]; exact upd_ne (needle_ne_of_slot (a := ⟨.f, j⟩) rfl hm))
    ⟨by cases d <;> simp [hc, arrivesFrom], by cases d <;> simp [apply, leavesTo, slot]⟩
  obtain ⟨B, A, h1, h2, h3, h4, _⟩ := width_split s _ lo w j (by omega) (by omega) hfar
  simp only [segW_eq] at h1 h2 h4
  have e1 : frontAt (apply s (.tuck d ⟨.f, j⟩)) j = frontAt s j + 2 := by
    simp [frontAt, apply]; omega
  have e2 : backAt (apply s (.tuck d ⟨.f, j⟩)) j = backAt s j := by
    simp [backAt, apply]
  have e3 : frontAt (apply s (.tuck d ⟨.f, j⟩)) (j + 1) = frontAt s (j + 1) := by
    simp [frontAt, apply]
  have e4 : backAt (apply s (.tuck d ⟨.f, j⟩)) (j + 1) = backAt s (j + 1) := by
    simp [backAt, apply]
  rw [e1, e2, e3, e4] at h2
  unfold BWF windowWidth
  change btopWidth plainSig (W s lo w) _ = some (W _ lo w)
  rw [h1, h2]
  cases d with
  | R =>
    have y1 : yarnAt s j = 1 := by simp [yarnAt, hc, arrivesFrom]
    have y2 : yarnAt s (j + 1) = 0 := by simp [yarnAt, hc, arrivesFrom]
    have y3 : yarnAt (apply s (.tuck .R ⟨.f, j⟩)) j = 0 := by simp [yarnAt, apply, leavesTo, slot]
    have y4 : yarnAt (apply s (.tuck .R ⟨.f, j⟩)) (j + 1) = 1 := by simp [yarnAt, apply, leavesTo, slot]
    simp only [y1, y2] at h4 h1 ⊢; simp only [y3, y4]
    simp only [denoteOp1, slot, arrivesFrom, h3, List.append_assoc, List.singleton_append]
    rw [btop_swapB _ _ _ _ _ _ (by omega), btop_box _ _ _ _ (by simp [PlainLabel.ins]; omega),
      btop_swapB_end _ _ _ _ _ (by simp [PlainLabel.ins, PlainLabel.outs]; omega)]
    simp [PlainLabel.ins, PlainLabel.outs]; omega
  | L =>
    have y1 : yarnAt s j = 0 := by simp [yarnAt, hc, arrivesFrom]
    have y2 : yarnAt s (j + 1) = 1 := by simp [yarnAt, hc, arrivesFrom]
    have y3 : yarnAt (apply s (.tuck .L ⟨.f, j⟩)) j = 1 := by simp [yarnAt, apply, leavesTo, slot]
    have y4 : yarnAt (apply s (.tuck .L ⟨.f, j⟩)) (j + 1) = 0 := by simp [yarnAt, apply, leavesTo, slot]
    simp only [y1, y2] at h4 h1 ⊢; simp only [y3, y4]
    simp only [denoteOp1, slot, arrivesFrom, h4, List.append_assoc, List.singleton_append]
    rw [btop_swapB _ _ _ _ _ _ (by omega), btop_box _ _ _ _ (by simp [PlainLabel.ins]; omega),
      btop_swapB_end _ _ _ _ _ (by simp [PlainLabel.ins, PlainLabel.outs]; omega)]
    simp [PlainLabel.ins, PlainLabel.outs]; omega

The statement for each instruction

def OpWF (op : Op) : Prop :=
  ∀ (win : Window) (s s' : State), step1 s op = .ok s' → windowOk win s op = true →
    BWF plainSig (windowWidth win s) (windowWidth win s') (denoteOp1 win s op)
theorem opWF_xfer (a b : Needle) : OpWF (.xfer a b)
Proof
:= fun _ _ _ h _ => denoteOp1_wf_xfer h
theorem opWF_tuck (d : Dir) (n : Needle) : OpWF (.tuck d n)
Proof
:= fun _ _ _ h hw => denoteOp1_wf_tuck h hw
def DropWF : Prop := ∀ n, OpWF (.drop n)

def KnitWF : Prop := ∀ d n, OpWF (.knit d n)

def SplitWF : Prop := ∀ d n m, OpWF (.split d n m)

def MissWF : Prop := ∀ d n, OpWF (.miss d n)

def RackWF : Prop := ∀ r, OpWF (.rack r)
theorem opWF_all (hd : DropWF) (hk : KnitWF) (hs : SplitWF) (hm : MissWF) (hr : RackWF) : ∀ op, OpWF op
Proof
  | .xfer a b => opWF_xfer a b
  | .tuck d n => opWF_tuck d n
  | .drop n => hd n
  | .knit d n => hk d n
  | .split d n m => hs d n m
  | .miss d n => hm d n
  | .rack r => hr r
theorem denote1_wf (hop : ∀ op, OpWF op) (win : Window) :
    ∀ (s : State) (ops : List Op) (t : State) (M : BWord PlainLabel), denote1 win s ops = some (t, M) →
      BWF plainSig (windowWidth win s) (windowWidth win t) M
Proof
  | s, [], t, M, h => by
    simp only [denote1, Option.some.injEq, Prod.mk.injEq] at h
    obtain ⟨rfl, rfl⟩ := h; rfl
  | s, op :: ops, t, M, h => by
    simp only [denote1] at h
    split at h
    · simp at h
    · rename_i s' hs
      split at h
      · rename_i hw
        split at h
        · simp at h
        · rename_i t' u hd
          simp only [Option.some.injEq, Prod.mk.injEq] at h
          obtain ⟨rfl, rfl⟩ := h
          unfold BWF
          rw [btopWidth_append, hop op win s s' hs hw]
          exact denote1_wf hop win s' ops t' u hd
      · simp at h
theorem denote1_wf_xfer_tuck (win : Window) (s : State) (ops : List Op) (t : State) (M : BWord PlainLabel)
    (hops : ∀ op ∈ ops, (∃ a b, op = .xfer a b) ∨ (∃ d n, op = .tuck d n))
    (h : denote1 win s ops = some (t, M)) : BWF plainSig (windowWidth win s) (windowWidth win t) M
Proof
:= by
  induction ops generalizing s M with
  | nil =>
    simp only [denote1, Option.some.injEq, Prod.mk.injEq] at h
    obtain ⟨rfl, rfl⟩ := h; rfl
  | cons op ops ih =>
    have hop : OpWF op := by
      rcases hops op (by simp) with ⟨a, b, rfl⟩ | ⟨d, n, rfl⟩
      · exact opWF_xfer a b
      · exact opWF_tuck d n
    simp only [denote1] at h
    split at h
    · simp at h
    · rename_i s' hs
      split at h
      · rename_i hw
        split at h
        · simp at h
        · rename_i t' u hd
          simp only [Option.some.injEq, Prod.mk.injEq] at h
          obtain ⟨rfl, rfl⟩ := h
          unfold BWF
          rw [btopWidth_append, hop win s s' hs hw]
          exact ih s' u (fun o ho => hops o (by simp [ho])) hd
      · simp at h

Well-formed drawings of each instruction

Proves OpWF for drop, knit, split and miss. Proves that RackWF is false, and proves the rack case with the hypothesis BackIn. Proves the program statements.

Theorem Statement
denoteOp1_wf_drop, denoteOp1_wf_miss, denoteOp1_wf_knit, denoteOp1_wf_split The drawing of the instruction is well formed
dropWF, knitWF, splitWF, missWF DropWF, KnitWF, SplitWF, MissWF
not_rackWF ¬ RackWF
denoteOp1_wf_rack The rack case, if each back needle with loops has its index in the window (BackIn)
opWF'_all OpWF' (OpWF with BackIn) for each instruction
opWF_of_ne_rack OpWF for each instruction that is not a rack
denote1_wf' The drawing of a program is well formed, if BackIn holds at the start and the window holds each named index
denoteCrate1_wf The drawing from initState on the window spanning is well formed. No hypothesis

Why RackWF is false

  • windowOk for a rack looks only at back needles whose index is in the window.
  • A back needle with loops can have its index outside the window and its physical position on the edge of the window.
  • A rack can move that needle out of the window. The window then loses two strands per loop.
  • On the window spanning, BackIn holds along each program (backIn_initState, backIn_apply).

Local instructions

theorem seg1_far' {s t : State} {z : Int} (hr : t.rack = s.rack)
    (hloc : ∀ n : Needle, slot s.rack n ≠ z → t.stk n = s.stk n)
    (hc : ∀ i, i ≠ z → i ≠ z + 1 → (t.carrier = i ↔ s.carrier = i)) :
    ∀ i, i ≠ z → i ≠ z + 1 → seg1 t i = seg1 s i
Proof
:= by
  intro i h1 h2
  apply seg1_congr hr (hc i h1 h2)
  · exact hloc _ (by simp [slot]; exact h1)
  · exact hloc _ (by simp [slot]; exact h1)
theorem local_widths {s t : State} {win : Window} {z : Int} (hin : win.inside z = true) (hr : t.rack = s.rack)
    (hloc : ∀ n : Needle, slot s.rack n ≠ z → t.stk n = s.stk n)
    (hc : ∀ i, i ≠ z → i ≠ z + 1 → (t.carrier = i ↔ s.carrier = i)) :
    ∃ B A, windowWidth win s = B + (yarnAt s z + frontAt s z + backAt s z) +
        (yarnAt s (z + 1) + frontAt s (z + 1) + backAt s (z + 1)) + A ∧
      windowWidth win t = B + (yarnAt t z + frontAt t z + backAt t z) +
        (yarnAt t (z + 1) + frontAt t (z + 1) + backAt t (z + 1)) + A ∧
      strandsBefore win s z = B ∧ strandsBefore win s (z + 1) = B + (yarnAt s z + frontAt s z + backAt s z)
Proof
:= by
  obtain ⟨lo, w⟩ := win
  have hin' : lo < z ∧ z < lo + w - 1 := by simpa [Window.inside] using hin
  obtain ⟨B, A, h1, h2, h3, h4, _⟩ := width_split s t lo w z (by omega) (by omega) (seg1_far' hr hloc hc)
  simp only [segW_eq] at h1 h2 h4
  exact ⟨B, A, h1, h2, h3, h4⟩
theorem slot_f (r j : Int) : slot r ⟨.f, j⟩ = j
Proof
:= rfl
theorem slot_b (r j : Int) : slot r ⟨.b, j⟩ = j + r
Proof
:= rfl
theorem upd_apply (f : Needle → List Nat) (a n : Needle) (v : List Nat) :
    Function.update f a v n = if n = a then v else f n
Proof
:= Function.update_apply f a v n
theorem needle_at_ne {r : Int} {n : Needle} {i : Int} (h : slot r n ≠ i) :
    (⟨.f, i⟩ : Needle) ≠ n ∧ (⟨.b, i - r⟩ : Needle) ≠ n
Proof
:= by
  obtain ⟨bd, j⟩ := n
  cases bd <;> simp [slot] at h ⊢ <;> omega
theorem valid_carrier {s : State} {d : Dir} {n : Needle}
    (h : linRefusal (erase s) (.miss d n) = none ∨ linRefusal (erase s) (.tuck d n) = none) :
    s.carrier = arrivesFrom d (slot s.rack n)
Proof
:= by
  rcases h with h | h <;> simp only [linRefusal, erase] at h <;> split_ifs at h with h1 <;> simp_all
theorem valid_carrier_knit {s : State} {d : Dir} {n : Needle} (h : validCrate s (.knit d n)) :
    s.carrier = arrivesFrom d (slot s.rack n)
Proof
:= by
  simp only [validCrate, crateRefusal1, linRefusal, erase] at h
  split_ifs at h with h1 <;> simp_all
theorem valid_carrier_split {s : State} {d : Dir} {n m : Needle} (h : validCrate s (.split d n m)) :
    s.carrier = arrivesFrom d (slot s.rack n)
Proof
:= by
  simp only [validCrate, crateRefusal1, linRefusal, erase] at h
  split_ifs at h with h1 <;> simp_all
theorem valid_miss {s : State} {d : Dir} {n : Needle} (h : validCrate s (.miss d n)) :
    s.carrier = arrivesFrom d (slot s.rack n)
Proof
:= by
  simp only [validCrate, crateRefusal1, linRefusal, erase] at h
  split_ifs at h with h1 <;> simp_all

Drop

theorem denoteOp1_wf_drop {win : Window} {s s' : State} {n : Needle} (h : step1 s (.drop n) = .ok s')
    (hw : windowOk win s (.drop n) = true) :
    BWF plainSig (windowWidth win s) (windowWidth win s') (denoteOp1 win s (.drop n))
Proof
:= by
  obtain ⟨_, rfl⟩ := step1_ok.mp h
  have hin : win.inside (slot s.rack n) = true := by simpa [windowOk] using hw
  obtain ⟨B, A, h1, h2, h3, _⟩ := local_widths (s := s) (t := apply s (.drop n)) hin rfl
    (fun m hm => upd_ne (needle_ne_of_slot (a := n) rfl hm))
    (fun i _ _ => by simp [apply])
  obtain ⟨bd, j⟩ := n
  unfold BWF
  cases bd with
  | f =>
    simp only [slot_f] at h1 h2 h3
    have e1 : yarnAt (apply s (.drop ⟨.f, j⟩)) j = yarnAt s j := rfl
    have e2 : frontAt (apply s (.drop ⟨.f, j⟩)) j = 0 := by simp [frontAt, apply]
    have e3 : backAt (apply s (.drop ⟨.f, j⟩)) j = backAt s j := by simp [backAt, apply]
    have e4 : yarnAt (apply s (.drop ⟨.f, j⟩)) (j + 1) = yarnAt s (j + 1) := rfl
    have e5 : frontAt (apply s (.drop ⟨.f, j⟩)) (j + 1) = frontAt s (j + 1) := by
      simp [frontAt, apply]
    have e6 : backAt (apply s (.drop ⟨.f, j⟩)) (j + 1) = backAt s (j + 1) := by simp [backAt, apply]
    rw [e1, e2, e3, e4, e5, e6] at h2
    have hF : frontAt s j = 2 * (s.stk ⟨.f, j⟩).length := rfl
    rw [h1, h2]
    simp only [denoteOp1, slot_f, h3, reduceCtorEq, ite_false]
    rw [btop_caps _ _ _ (by omega) (Or.inr trivial)]
    congr 1; omega
  | b =>
    simp only [slot_b] at h1 h2 h3
    have ne1 : j + s.rack + 1 - s.rack ≠ j := by omega
    have e1 : yarnAt (apply s (.drop ⟨.b, j⟩)) (j + s.rack) = yarnAt s (j + s.rack) := rfl
    have e2 : frontAt (apply s (.drop ⟨.b, j⟩)) (j + s.rack) = frontAt s (j + s.rack) := by
      simp [frontAt, apply]
    have e3 : backAt (apply s (.drop ⟨.b, j⟩)) (j + s.rack) = 0 := by simp [backAt, apply]
    have e4 : yarnAt (apply s (.drop ⟨.b, j⟩)) (j + s.rack + 1) = yarnAt s (j + s.rack + 1) := rfl
    have e5 : frontAt (apply s (.drop ⟨.b, j⟩)) (j + s.rack + 1) = frontAt s (j + s.rack + 1) := by
      simp [frontAt, apply]
    have e6 : backAt (apply s (.drop ⟨.b, j⟩)) (j + s.rack + 1) = backAt s (j + s.rack + 1) := by
      simp [backAt, apply, ne1]
    rw [e1, e2, e3, e4, e5, e6] at h2
    have hK : backAt s (j + s.rack) = 2 * (s.stk ⟨.b, j⟩).length := by simp [backAt]
    rw [h1, h2]
    simp only [denoteOp1, slot_b, h3, ite_true]
    rw [btop_caps _ _ _ (by omega) (Or.inr trivial)]
    congr 1; omega

Miss

theorem denoteOp1_wf_miss {win : Window} {s s' : State} {d : Dir} {n : Needle} (h : step1 s (.miss d n) = .ok s')
    (hw : windowOk win s (.miss d n) = true) :
    BWF plainSig (windowWidth win s) (windowWidth win s') (denoteOp1 win s (.miss d n))
Proof
:= by
  obtain ⟨hv, rfl⟩ := step1_ok.mp h
  have hc := valid_miss hv
  have hin : win.inside (slot s.rack n) = true := by simpa [windowOk] using hw
  set z := slot s.rack n with hz
  obtain ⟨B, A, h1, h2, h3, h4⟩ := local_widths (s := s) (t := apply s (.miss d n)) hin rfl
    (fun m _ => rfl)
    (fun i h1 h2 => by cases d <;> simp [apply, leavesTo, arrivesFrom, hc, ← hz] <;> omega)
  have ef : ∀ i, frontAt (apply s (.miss d n)) i = frontAt s i := fun _ => rfl
  have eb : ∀ i, backAt (apply s (.miss d n)) i = backAt s i := fun _ => rfl
  simp only [ef, eb] at h2
  unfold BWF
  rw [h1, h2]
  cases d with
  | R =>
    have y1 : yarnAt s z = 1 := by simp [yarnAt, hc, arrivesFrom]
    have y2 : yarnAt s (z + 1) = 0 := by simp [yarnAt, hc, arrivesFrom]
    have y3 : yarnAt (apply s (.miss .R n)) z = 0 := by simp [yarnAt, apply, leavesTo, ← hz]
    have y4 : yarnAt (apply s (.miss .R n)) (z + 1) = 1 := by simp [yarnAt, apply, leavesTo, ← hz]
    rw [y1, y2, y3, y4]
    simp only [denoteOp1, ← hz, arrivesFrom, h3]
    rw [btop_swapB _ _ _ _ _ _ (by omega), btop_swapB_end _ _ _ _ _ (by omega)]
    congr 1; omega
  | L =>
    have y1 : yarnAt s z = 0 := by simp [yarnAt, hc, arrivesFrom]
    have y2 : yarnAt s (z + 1) = 1 := by simp [yarnAt, hc, arrivesFrom]
    have y3 : yarnAt (apply s (.miss .L n)) z = 1 := by simp [yarnAt, apply, leavesTo, ← hz]
    have y4 : yarnAt (apply s (.miss .L n)) (z + 1) = 0 := by simp [yarnAt, apply, leavesTo, ← hz]
    rw [y1, y2, y3, y4]; rw [y1] at h4
    simp only [denoteOp1, ← hz, arrivesFrom, h4]
    rw [btop_swapB _ _ _ _ _ _ (by omega), btop_swapB_end _ _ _ _ _ (by omega)]
    congr 1; omega

Knit

theorem at_f {s t : State} {j : Int} {v : List Nat} (hr : t.rack = s.rack)
    (hs : t.stk = Function.update s.stk ⟨.f, j⟩ v) :
    frontAt t j = 2 * v.length ∧ backAt t j = backAt s j ∧ frontAt t (j + 1) = frontAt s (j + 1) ∧
      backAt t (j + 1) = backAt s (j + 1)
Proof
:= by
  simp [frontAt, backAt, hr, hs]
theorem at_b {s t : State} {j : Int} {v : List Nat} (hr : t.rack = s.rack)
    (hs : t.stk = Function.update s.stk ⟨.b, j⟩ v) :
    frontAt t (j + s.rack) = frontAt s (j + s.rack) ∧ backAt t (j + s.rack) = 2 * v.length ∧
      frontAt t (j + s.rack + 1) = frontAt s (j + s.rack + 1) ∧
      backAt t (j + s.rack + 1) = backAt s (j + s.rack + 1)
Proof
:= by
  have ne1 : j + s.rack + 1 - s.rack ≠ j := by omega
  simp [frontAt, backAt, hr, hs, ne1]
theorem denoteOp1_wf_knit {win : Window} {s s' : State} {d : Dir} {n : Needle} (h : step1 s (.knit d n) = .ok s')
    (hw : windowOk win s (.knit d n) = true) :
    BWF plainSig (windowWidth win s) (windowWidth win s') (denoteOp1 win s (.knit d n))
Proof
:= by
  obtain ⟨hv, rfl⟩ := step1_ok.mp h
  have hc := valid_carrier_knit hv
  have hin : win.inside (slot s.rack n) = true := by simpa [windowOk] using hw
  obtain ⟨B, A, h1, h2, h3, h4⟩ := local_widths (s := s) (t := apply s (.knit d n)) hin rfl
    (fun m hm => upd_ne (needle_ne_of_slot (a := n) rfl hm))
    (fun i h1 h2 => by cases d <;> simp [apply, leavesTo, arrivesFrom, hc] <;> omega)
  unfold BWF
  have hy : ∀ i, yarnAt s i = if arrivesFrom d (slot s.rack n) = i then 1 else 0 := by
    intro i; simp [yarnAt, hc]
  have hy' : ∀ i, yarnAt (apply s (.knit d n)) i = if leavesTo d (slot s.rack n) = i then 1 else 0 :=
    fun _ => rfl
  obtain ⟨bd, j⟩ := n
  cases bd with
  | f =>
    obtain ⟨e1, e2, e3, e4⟩ := at_f (s := s) (t := apply s (.knit d ⟨.f, j⟩)) (j := j) rfl rfl
    have hF : frontAt s j = 2 * (s.stk ⟨.f, j⟩).length := rfl
    simp only [slot_f] at h1 h2 h3 h4 hy hy'
    rw [e1, e2, e3, e4] at h2
    rw [h1, h2]
    cases d with
    | R =>
      simp only [hy, hy', arrivesFrom, leavesTo] at h1 h2 h4 ⊢
      simp only [denoteOp1, slot_f, arrivesFrom, h3, List.singleton_append]
      rw [btop_box _ _ _ _ (by simp [PlainLabel.ins]; omega),
        btop_swapB_end _ _ _ _ _ (by simp [PlainLabel.ins, PlainLabel.outs]; omega)]
      simp [PlainLabel.ins, PlainLabel.outs]; omega
    | L =>
      simp only [hy, hy', arrivesFrom, leavesTo] at h1 h2 h4 ⊢
      simp only [denoteOp1, slot_f, arrivesFrom, h4]
      simp at h4 ⊢
      rw [btop_swapB _ _ _ _ _ _ (by omega), btop_box _ _ _ _ (by simp [PlainLabel.ins]; omega)]
      simp [PlainLabel.ins, PlainLabel.outs, btopWidth]; omega
  | b =>
    obtain ⟨e1, e2, e3, e4⟩ := at_b (s := s) (t := apply s (.knit d ⟨.b, j⟩)) (j := j) rfl rfl
    have hK : backAt s (j + s.rack) = 2 * (s.stk ⟨.b, j⟩).length := by simp [backAt]
    simp only [slot_b] at h1 h2 h3 h4 hy hy'
    rw [e1, e2, e3, e4] at h2
    rw [h1, h2]
    cases d with
    | R =>
      simp only [hy, hy', arrivesFrom, leavesTo] at h1 h2 h4 ⊢
      simp only [denoteOp1, slot_b, arrivesFrom, h3]
      simp at h1 h2 ⊢
      rw [btop_swapB _ _ _ _ _ _ (by omega), btop_box _ _ _ _ (by simp [PlainLabel.ins]; omega)]
      simp [PlainLabel.ins, PlainLabel.outs, btopWidth]; omega
    | L =>
      simp only [hy, hy', arrivesFrom, leavesTo] at h1 h2 h4 ⊢
      simp only [denoteOp1, slot_b, arrivesFrom, h4]
      simp at h4 ⊢
      rw [btop_box _ _ _ _ (by simp [PlainLabel.ins]; omega),
        btop_swapB_end _ _ _ _ _ (by simp [PlainLabel.ins, PlainLabel.outs]; omega)]
      simp [PlainLabel.ins, PlainLabel.outs]; omega

Split

theorem valid_split_one {s : State} {d : Dir} {n m : Needle} (h : validCrate s (.split d n m)) :
    (s.stk n).length = 1
Proof
:= by
  simp only [validCrate, crateRefusal1] at h
  cases hl : linRefusal (erase s) (.split d n m) with
  | some r => simp [hl] at h
  | none => simp only [hl, crateExtra1] at h; split_ifs at h with h1; exact h1
theorem denoteOp1_wf_split {win : Window} {s s' : State} {d : Dir} {n m : Needle}
    (h : step1 s (.split d n m) = .ok s') (hw : windowOk win s (.split d n m) = true) :
    BWF plainSig (windowWidth win s) (windowWidth win s') (denoteOp1 win s (.split d n m))
Proof
:= by
  obtain ⟨hv, rfl⟩ := step1_ok.mp h
  have hc := valid_carrier_split hv
  have h1n := valid_split_one hv
  have hal := validLin_split (validCrate_validLin hv)
  have hin : win.inside (slot s.rack n) = true := by
    simp only [windowOk, Bool.and_eq_true] at hw; exact hw.1
  have hmz : slot s.rack m = slot s.rack n := by
    simp only [aligned, decide_eq_true_eq] at hal; exact hal.2.symm
  obtain ⟨B, A, h1, h2, h3, h4⟩ := local_widths (s := s) (t := apply s (.split d n m)) hin rfl
    (fun q hq => by
      simp only [apply]
      rw [upd_ne (needle_ne_of_slot (a := m) hmz hq), upd_ne (needle_ne_of_slot (a := n) rfl hq)])
    (fun i h1 h2 => by cases d <;> simp [apply, leavesTo, arrivesFrom, hc] <;> omega)
  unfold BWF
  have hy : ∀ i, yarnAt s i = if arrivesFrom d (slot s.rack n) = i then 1 else 0 := by
    intro i; simp [yarnAt, hc]
  have hy' : ∀ i, yarnAt (apply s (.split d n m)) i = if leavesTo d (slot s.rack n) = i then 1 else 0 :=
    fun _ => rfl
  have hst : (apply s (.split d n m)).stk =
      Function.update (Function.update s.stk n [s.fresh]) m (xferStack (s.stk n) (s.stk m)) := rfl
  obtain ⟨bd, j⟩ := n
  obtain ⟨bm, jm⟩ := m
  cases bd with
  | f =>
    have hbm : bm = .b := by
      cases bm
      · simp [aligned] at hal
      · rfl
    subst hbm
    have hjm : jm = j - s.rack := by simp [slot] at hmz; omega
    subst hjm
    have ne1 : j + 1 - s.rack ≠ j - s.rack := by omega
    have e1 : frontAt (apply s (.split d ⟨.f, j⟩ ⟨.b, j - s.rack⟩)) j = 2 := by
      simp [frontAt, hst]
    have e2 : backAt (apply s (.split d ⟨.f, j⟩ ⟨.b, j - s.rack⟩)) j = backAt s j + 2 := by
      simp [backAt, xferStack, h1n, apply]; omega
    have e3 : frontAt (apply s (.split d ⟨.f, j⟩ ⟨.b, j - s.rack⟩)) (j + 1) = frontAt s (j + 1) := by
      simp [frontAt, hst]
    have e4 : backAt (apply s (.split d ⟨.f, j⟩ ⟨.b, j - s.rack⟩)) (j + 1) = backAt s (j + 1) := by
      simp [backAt, apply, ne1]
    have hF : frontAt s j = 2 := by simp [frontAt, h1n]
    simp only [slot_f] at h1 h2 h3 h4 hy hy'
    rw [e1, e2, e3, e4] at h2
    rw [h1, h2]
    cases d with
    | R =>
      simp only [hy, hy', arrivesFrom, leavesTo] at h1 h2 h4 ⊢
      simp only [denoteOp1, slot_f, arrivesFrom, h3, List.singleton_append]
      rw [btop_box _ _ _ _ (by simp [PlainLabel.ins]; omega),
        btop_swapB_end _ _ _ _ _ (by simp [PlainLabel.ins, PlainLabel.outs]; omega)]
      simp [PlainLabel.ins, PlainLabel.outs]; omega
    | L =>
      simp only [hy, hy', arrivesFrom, leavesTo] at h1 h2 h4 ⊢
      simp only [denoteOp1, slot_f, arrivesFrom, h4]
      simp at h4 ⊢
      rw [btop_swapB _ _ _ _ _ _ (by omega), btop_box _ _ _ _ (by simp [PlainLabel.ins]; omega)]
      simp [PlainLabel.ins, PlainLabel.outs, btopWidth]; omega
  | b =>
    have hbm : bm = .f := by
      cases bm
      · rfl
      · simp [aligned] at hal
    subst hbm
    have hjm : jm = j + s.rack := by simp [slot] at hmz; omega
    subst hjm
    have ne1 : j + s.rack + 1 - s.rack ≠ j := by omega
    have e1 : frontAt (apply s (.split d ⟨.b, j⟩ ⟨.f, j + s.rack⟩)) (j + s.rack) = frontAt s (j + s.rack) + 2 := by
      simp [frontAt, hst, xferStack, h1n]; omega
    have e2 : backAt (apply s (.split d ⟨.b, j⟩ ⟨.f, j + s.rack⟩)) (j + s.rack) = 2 := by
      simp [backAt, apply]
    have e3 : frontAt (apply s (.split d ⟨.b, j⟩ ⟨.f, j + s.rack⟩)) (j + s.rack + 1) =
        frontAt s (j + s.rack + 1) := by
      simp [frontAt, hst]
    have e4 : backAt (apply s (.split d ⟨.b, j⟩ ⟨.f, j + s.rack⟩)) (j + s.rack + 1) =
        backAt s (j + s.rack + 1) := by
      simp [backAt, apply, ne1]
    have hK : backAt s (j + s.rack) = 2 := by simp [backAt, h1n]
    simp only [slot_b] at h1 h2 h3 h4 hy hy'
    rw [e1, e2, e3, e4] at h2
    rw [h1, h2]
    cases d with
    | R =>
      simp only [hy, hy', arrivesFrom, leavesTo] at h1 h2 h4 ⊢
      simp only [denoteOp1, slot_b, arrivesFrom, h3]
      simp at h1 h2 ⊢
      rw [btop_swapB _ _ _ _ _ _ (by omega), btop_box _ _ _ _ (by simp [PlainLabel.ins]; omega)]
      simp [PlainLabel.ins, PlainLabel.outs, btopWidth]; omega
    | L =>
      simp only [hy, hy', arrivesFrom, leavesTo] at h1 h2 h4 ⊢
      simp only [denoteOp1, slot_b, arrivesFrom, h4]
      simp at h4 ⊢
      rw [btop_box _ _ _ _ (by simp [PlainLabel.ins]; omega),
        btop_swapB_end _ _ _ _ _ (by simp [PlainLabel.ins, PlainLabel.outs]; omega)]
      simp [PlainLabel.ins, PlainLabel.outs]; omega
theorem dropWF : DropWF
Proof
:= fun _ _ _ _ h hw => denoteOp1_wf_drop h hw
theorem knitWF : KnitWF
Proof
:= fun _ _ _ _ _ h hw => denoteOp1_wf_knit h hw
theorem splitWF : SplitWF
Proof
:= fun _ _ _ _ _ _ h hw => denoteOp1_wf_split h hw
theorem missWF : MissWF
Proof
:= fun _ _ _ _ _ h hw => denoteOp1_wf_miss h hw

Rack: the statement RackWF is false

def rackCex : State := ⟨5, fun n => if n = ⟨.b, -5⟩ then [0] else [], 100, 1⟩
theorem not_rackWF : ¬ RackWF
Proof
:= by
  intro h
  have := h 4 ⟨0, 3⟩ rackCex { rackCex with rack := 4 } rfl (by decide)
  unfold BWF at this
  revert this
  decide

Rack, when every loaded back needle's index lies in the window

def BackIn (win : Window) (s : State) : Prop := ∀ j, s.stk ⟨.b, j⟩ ≠ [] → win.lo ≤ j ∧ j < win.lo + win.w
theorem W_sum (s : State) (lo : Int) (w : Nat) :
    W s lo w = ∑ k ∈ Finset.range w, (yarnAt s (lo + k) + frontAt s (lo + k) + backAt s (lo + k))
Proof
:= by
  induction w with
  | zero => rfl
  | succ w ih => rw [W_succ, ih, Finset.sum_range_succ, segW_eq]
theorem sum_shift (g : Int → Nat) (c : Int) (w : Nat) (h0 : g c = 0) (hw : g (c + w) = 0) :
    ∑ k ∈ Finset.range w, g (c + k) = ∑ k ∈ Finset.range w, g (c + 1 + k)
Proof
:= by
  have h1 : ∑ k ∈ Finset.range (w + 1), g (c + k) = ∑ k ∈ Finset.range w, g (c + k) + g (c + w) :=
    Finset.sum_range_succ _ _
  have h2 : ∑ k ∈ Finset.range (w + 1), g (c + k) = ∑ k ∈ Finset.range w, g (c + 1 + k) + g c := by
    rw [Finset.sum_range_succ']
    congr 1
    · apply Finset.sum_congr rfl; intro k _; congr 1; push_cast; omega
    · simp
  rw [hw] at h1; rw [h0] at h2
  omega
theorem windowOk_rack {win : Window} {s : State} {r : Int} (hw : windowOk win s (.rack r) = true) {j : Int}
    (hj : win.lo ≤ j ∧ j < win.lo + win.w) (hl : s.stk ⟨.b, j⟩ ≠ []) : win.inside (j + r) = true
Proof
:= by
  simp only [windowOk, List.all_eq_true, List.mem_range, Bool.or_eq_true, List.isEmpty_iff] at hw
  have := hw (j - win.lo).toNat (by omega)
  have e : win.lo + ((j - win.lo).toNat : Int) = j := by omega
  rw [e] at this
  exact this.resolve_left hl
theorem valid_rack {s : State} {r : Int} (h : validCrate s (.rack r)) : (r - s.rack).natAbs = 1
Proof
:= by
  simp only [validCrate, crateRefusal1, linRefusal, erase] at h
  split_ifs at h with h1 <;> simp_all
theorem back_empty_of {win : Window} {s : State} {r : Int} (hw : windowOk win s (.rack r) = true)
    (hb : BackIn win s) {j : Int} (hj : win.inside (j + r) = false) : s.stk ⟨.b, j⟩ = []
Proof
:= by
  by_contra hl
  have := windowOk_rack hw (hb j hl) hl
  rw [hj] at this; exact absurd this (by decide)
theorem inside_false {win : Window} {z : Int} (h : z ≤ win.lo ∨ win.lo + win.w - 1 ≤ z) :
    win.inside z = false
Proof
:= by
  simp [Window.inside]; omega
theorem rackBraid_eq (win : Window) (s : State) (r : Int) :
    rackBraid win s r = plainB ((List.range win.w).flatMap fun k =>
      if r < s.rack then swapBlocks (strandsBefore win s (win.lo + k)) (yarnAt s (win.lo + k) + frontAt s (win.lo + k))
        (backAt s (win.lo + k)) true
      else swapBlocks (strandsBefore win s (win.lo + k) - 2 * (s.stk ⟨.b, win.lo + k - 1 - s.rack⟩).length)
        (2 * (s.stk ⟨.b, win.lo + k - 1 - s.rack⟩).length) (yarnAt s (win.lo + k) + frontAt s (win.lo + k)) false)
Proof
:= by
  unfold rackBraid plainB
  rw [List.map_flatMap]
  congr 1; funext k
  split <;> rfl
theorem denoteOp1_wf_rack {win : Window} {s s' : State} {r : Int} (h : step1 s (.rack r) = .ok s')
    (hw : windowOk win s (.rack r) = true) (hb : BackIn win s) :
    BWF plainSig (windowWidth win s) (windowWidth win s') (denoteOp1 win s (.rack r))
Proof
:= by
  obtain ⟨hv, rfl⟩ := step1_ok.mp h
  have hr := valid_rack hv
  obtain ⟨lo, w⟩ := win
  have hW : windowWidth ⟨lo, w⟩ (apply s (.rack r)) = windowWidth ⟨lo, w⟩ s := by
    show W _ lo w = W s lo w
    rw [W_sum, W_sum]
    simp only [Finset.sum_add_distrib]
    congr 1
    set g : Int → Nat := fun j => 2 * (s.stk ⟨.b, j⟩).length with hg
    have hg0 : ∀ j, (lo + w - 1 ≤ j + r ∨ j + r ≤ lo) → g j = 0 := by
      intro j hj
      have := back_empty_of hw hb (j := j) (inside_false (win := ⟨lo, w⟩) (z := j + r) (by simp; omega))
      simp only [hg, this, List.length_nil]
    have eL : ∑ k ∈ Finset.range w, backAt (apply s (.rack r)) (lo + k) =
        ∑ k ∈ Finset.range w, g (lo - r + k) := by
      apply Finset.sum_congr rfl; intro k _
      show 2 * (s.stk ⟨.b, lo + k - r⟩).length = 2 * (s.stk ⟨.b, lo - r + k⟩).length
      rw [show lo + (k : Int) - r = lo - r + k by omega]
    have eR : ∑ k ∈ Finset.range w, backAt s (lo + k) = ∑ k ∈ Finset.range w, g (lo - s.rack + k) := by
      apply Finset.sum_congr rfl; intro k _
      show 2 * (s.stk ⟨.b, lo + k - s.rack⟩).length = 2 * (s.stk ⟨.b, lo - s.rack + k⟩).length
      rw [show lo + (k : Int) - s.rack = lo - s.rack + k by omega]
    rw [eL, eR]
    rcases Int.natAbs_eq (r - s.rack) with he | he <;> rw [hr] at he <;> push_cast at he
    · have := sum_shift g (lo - r) w (hg0 (lo - r) (by right; omega)) (hg0 (lo - r + w) (by left; omega))
      rw [this]; apply Finset.sum_congr rfl; intro k _; congr 1; omega
    · have := sum_shift g (lo - s.rack) w (hg0 (lo - s.rack) (by right; omega))
        (hg0 (lo - s.rack + w) (by left; omega))
      rw [this]; apply Finset.sum_congr rfl; intro k _; congr 1; omega
  unfold BWF
  rw [hW]
  rw [show denoteOp1 ⟨lo, w⟩ s (.rack r) = rackBraid ⟨lo, w⟩ s r from rfl, rackBraid_eq, btopWidth_plainB]
  apply topWidth_flatMap_keep
  intro ki hki
  obtain ⟨k, hk', rfl⟩ : ∃ k : Nat, k < w ∧ ki = (k : Int) := by
    simpa using hki
  have hsplit : windowWidth ⟨lo, w⟩ s = W s lo k + segW s (lo + k) + W s (lo + k + 1) (w - k - 1) := by
    show W s lo w = _
    have e : w = k + 1 + (w - k - 1) := by omega
    conv_lhs => rw [e]
    rw [W_add, W_succ]
    congr 2; push_cast; omega
  have hsb : strandsBefore ⟨lo, w⟩ s (lo + k) = W s lo k := by
    show cellRowWidth (rowOf1 s lo (lo + (k : Int) - lo).toNat) = W s lo k
    rw [show (lo + (k : Int) - lo).toNat = k by omega]; rfl
  rw [segW_eq] at hsplit
  simp only
  split
  · apply swapBlocks_wf; rw [hsb, hsplit]; omega
  · apply swapBlocks_wf
    rw [hsb, hsplit]
    rcases Nat.eq_zero_or_pos k with hk0 | hk0
    · subst hk0
      have : s.stk ⟨.b, lo + ((0 : Nat) : Int) - 1 - s.rack⟩ = [] := by
        apply back_empty_of hw hb (inside_false (by simp; omega))
      rw [this]; simp; omega
    · have hprev : W s lo k = W s lo (k - 1) + segW s (lo + (k - 1 : Nat)) := by
        rw [← W_succ]; congr 1; omega
      have hb' : backAt s (lo + (k - 1 : Nat)) = 2 * (s.stk ⟨.b, lo + k - 1 - s.rack⟩).length := by
        simp only [backAt]; congr 4; omega
      rw [segW_eq] at hprev
      omega

Every instruction, and programs

def OpWF' (op : Op) : Prop :=
  ∀ (win : Window) (s s' : State), step1 s op = .ok s' → windowOk win s op = true → BackIn win s →
    BWF plainSig (windowWidth win s) (windowWidth win s') (denoteOp1 win s op)
theorem opWF'_all : ∀ op, OpWF' op
Proof
  | .xfer _ _ => fun _ _ _ h _ _ => denoteOp1_wf_xfer h
  | .tuck _ _ => fun _ _ _ h hw _ => denoteOp1_wf_tuck h hw
  | .drop _ => fun _ _ _ h hw _ => denoteOp1_wf_drop h hw
  | .knit _ _ => fun _ _ _ h hw _ => denoteOp1_wf_knit h hw
  | .split _ _ _ => fun _ _ _ h hw _ => denoteOp1_wf_split h hw
  | .miss _ _ => fun _ _ _ h hw _ => denoteOp1_wf_miss h hw
  | .rack _ => fun _ _ _ h hw hb => denoteOp1_wf_rack h hw hb
theorem opWF_of_ne_rack (op : Op) (h : ∀ r, op ≠ .rack r) : OpWF op
Proof
:= by
  cases op with
  | rack r => exact absurd rfl (h r)
  | xfer a b => exact opWF_xfer a b
  | tuck d n => exact opWF_tuck d n
  | drop n => exact dropWF n
  | knit d n => exact knitWF d n
  | split d n m => exact splitWF d n m
  | miss d n => exact missWF d n
def NamedIn (win : Window) (op : Op) : Prop := ∀ j ∈ op.named, win.lo ≤ j ∧ j < win.lo + win.w
theorem loaded_apply (s : State) (op : Op) (q : Needle) (h : (apply s op).stk q ≠ []) :
    s.stk q ≠ [] ∨ q.idx ∈ op.named
Proof
:= by
  cases op with
  | xfer a b =>
    simp only [apply, upd_apply] at h
    by_cases hb : q = b
    · subst hb; right; simp [Op.named]
    · by_cases ha : q = a <;> simp_all
  | rack r => left; exact h
  | knit d n =>
    simp only [apply, upd_apply] at h
    by_cases hn : q = n
    · subst hn; right; simp [Op.named]
    · simp_all
  | tuck d n =>
    simp only [apply, upd_apply] at h
    by_cases hn : q = n
    · subst hn; right; simp [Op.named]
    · simp_all
  | split d n m =>
    simp only [apply, upd_apply] at h
    by_cases hm : q = m
    · subst hm; right; simp [Op.named]
    · by_cases hn : q = n
      · subst hn; right; simp [Op.named]
      · simp_all
  | miss d n => left; exact h
  | drop n =>
    simp only [apply, upd_apply] at h
    by_cases hn : q = n <;> simp_all
theorem backIn_apply {win : Window} {s : State} {op : Op} (hb : BackIn win s) (hn : NamedIn win op) :
    BackIn win (apply s op)
Proof
:= by
  intro j hj
  rcases loaded_apply s op ⟨.b, j⟩ hj with h | h
  · exact hb j h
  · exact hn j h
theorem denote1_wf' (win : Window) :
    ∀ (s : State) (ops : List Op) (t : State) (M : BWord PlainLabel), BackIn win s → (∀ op ∈ ops, NamedIn win op) →
      denote1 win s ops = some (t, M) → BWF plainSig (windowWidth win s) (windowWidth win t) M
Proof
  | s, [], t, M, _, _, h => by
    simp only [denote1, Option.some.injEq, Prod.mk.injEq] at h
    obtain ⟨rfl, rfl⟩ := h; rfl
  | s, op :: ops, t, M, hb, hn, h => by
    simp only [denote1] at h
    split at h
    · simp at h
    · rename_i s' hs
      split at h
      · rename_i hw
        split at h
        · simp at h
        · rename_i t' u hd
          simp only [Option.some.injEq, Prod.mk.injEq] at h
          obtain ⟨rfl, rfl⟩ := h
          have hs' := (step1_ok.mp hs).2
          unfold BWF
          rw [btopWidth_append, opWF'_all op win s s' hs hw hb]
          refine denote1_wf' win s' ops t' u ?_ (fun o ho => hn o (by simp [ho])) hd
          rw [hs']; exact backIn_apply hb (hn op (by simp))
      · simp at h

The window spanning

theorem foldl_min_le (l : List Int) : ∀ a, l.foldl min a ≤ a ∧ ∀ x ∈ l, l.foldl min a ≤ x
Proof
:= by
  induction l with
  | nil => intro a; simp
  | cons y ys ih =>
    intro a
    obtain ⟨h1, h2⟩ := ih (min a y)
    refine ⟨by simp only [List.foldl_cons]; omega, ?_⟩
    intro x hx
    simp only [List.foldl_cons]
    rcases List.mem_cons.mp hx with rfl | hx
    · omega
    · exact h2 x hx
theorem le_foldl_max (l : List Int) : ∀ a, a ≤ l.foldl max a ∧ ∀ x ∈ l, x ≤ l.foldl max a
Proof
:= by
  induction l with
  | nil => intro a; simp
  | cons y ys ih =>
    intro a
    obtain ⟨h1, h2⟩ := ih (max a y)
    refine ⟨by simp only [List.foldl_cons]; omega, ?_⟩
    intro x hx
    simp only [List.foldl_cons]
    rcases List.mem_cons.mp hx with rfl | hx
    · omega
    · exact h2 x hx
theorem spanning_reach (loops : List (Needle × Nat)) (yarnAt : Int) (ops : List Op) (j : Int)
    (hj : j ∈ loops.map (·.1.idx) ++ ops.flatMap Op.named ∨ j = yarnAt) :
    (spanning loops yarnAt ops).lo + rackReach ≤ j ∧ j + rackReach < (spanning loops yarnAt ops).lo +
      (spanning loops yarnAt ops).w
Proof
:= by
  obtain ⟨a1, a2⟩ := foldl_min_le (loops.map (·.1.idx) ++ ops.flatMap Op.named) yarnAt
  obtain ⟨b1, b2⟩ := le_foldl_max (loops.map (·.1.idx) ++ ops.flatMap Op.named) yarnAt
  have hmin : (loops.map (·.1.idx) ++ ops.flatMap Op.named).foldl min yarnAt ≤ j := by rcases hj with hj | rfl; exact a2 j hj; exact a1
  have hmax : j ≤ (loops.map (·.1.idx) ++ ops.flatMap Op.named).foldl max yarnAt := by rcases hj with hj | rfl; exact b2 j hj; exact b1
  simp only [spanning, rackReach]
  constructor <;> omega
theorem namedIn_spanning (loops : List (Needle × Nat)) (yarnAt : Int) (ops : List Op) :
    ∀ op ∈ ops, NamedIn (spanning loops yarnAt ops) op
Proof
:= by
  intro op hop j hj
  have := spanning_reach loops yarnAt ops j (Or.inl (List.mem_append_right _ (List.mem_flatMap.mpr ⟨op, hop, hj⟩)))
  simp only [rackReach] at this
  omega
theorem pushFresh_loaded (s : State) (n : Needle) : ∀ (k : Nat) (q : Needle), (pushFresh s n k).stk q ≠ [] →
    s.stk q ≠ [] ∨ q = n
Proof
  | 0, q, h => Or.inl h
  | k + 1, q, h => by
    rcases pushFresh_loaded _ n k q h with h' | h'
    · simp only [upd_apply] at h'
      by_cases hq : q = n
      · exact Or.inr hq
      · simp [hq] at h'; exact Or.inl h'
    · exact Or.inr h'
theorem place_loaded : ∀ (s : State) (L : List (Needle × Nat)) (q : Needle), (place s L).stk q ≠ [] →
    s.stk q ≠ [] ∨ q ∈ L.map (·.1)
Proof
  | s, [], q, h => Or.inl h
  | s, (n, k) :: rest, q, h => by
    rcases place_loaded _ rest q h with h' | h'
    · rcases pushFresh_loaded s n k q h' with h'' | h''
      · exact Or.inl h''
      · right; simp [h'']
    · right; simp only [List.map_cons, List.mem_cons]; exact Or.inr h'
theorem backIn_initState (loops : List (Needle × Nat)) (yarnAt : Int) (ops : List Op) :
    BackIn (spanning loops yarnAt ops) (initState loops yarnAt)
Proof
:= by
  intro j hj
  rcases place_loaded _ loops ⟨.b, j⟩ hj with h | h
  · exact absurd rfl h
  · have : j ∈ loops.map (·.1.idx) := by
      obtain ⟨p, hp, hpe⟩ := List.mem_map.mp h
      exact List.mem_map.mpr ⟨p, hp, by rw [hpe]⟩
    have := spanning_reach loops yarnAt ops j (Or.inl (List.mem_append_left _ this))
    simp only [rackReach] at this
    omega
theorem denoteCrate1_wf {loops : List (Needle × Nat)} {yarnAt : Int} {ops : List Op} {t : State} {M : BWord PlainLabel}
    (h : denoteCrate1 loops yarnAt ops = some (t, M)) :
    BWF plainSig (windowWidth (spanning loops yarnAt ops) (initState loops yarnAt))
      (windowWidth (spanning loops yarnAt ops) t) M
Proof
:=
  denote1_wf' _ _ ops t M (backIn_initState loops yarnAt ops) (namedIn_spanning loops yarnAt ops) h

The knitout machine with splits of stacks, and its drawing

The machine step allows a split of a needle with two or more loops. denote draws such a split as one box.

Declaration Content
PlainLabel.toLabel, liftB The labels of denoteOp1 in the shorthand signature. A split through one loop is splitK _ _ 1
denoteOp, denote The drawing with boxes of one instruction and of a program, with step
shared_order_kept, shared_order_kept_denote Loops that share a needle keep their order through step
distinct_initState initState has distinct loop identities
SplitDropOldIsKnit, SplitDropNewIsPass A split, then a drop of one output. Stated, not proved

The machine step

  • step is step1 with one change. step1 refuses a split of a needle that does not hold exactly one loop (crateExtra1). step refuses a split only of an empty needle (extraRefusal).
  • Beyond Lin Fig. 11, step refuses two things: a split of an empty needle, and each tuck on the back bed.
  • Lin requires a knit on a needle with loops (linRefusal). So no loop is made directly on an empty back needle.
  • apply already gives the effect of a split. The new loop is alone on the needle. The whole old stack goes on top of the needle across (xferStack).

The drawing denoteOp

  • denoteOp is liftB (denoteOp1 …) for each instruction except a split.
  • A split is one box splitK d bed k for the k loops of the needle.
  • The carrier passes the other needle at that position as in denoteOp1. The offset y + 4 there is y + 2 + F here, with F = 2k.
open Knitout
open scoped List
def PlainLabel.toLabel : PlainLabel → Label
  | .tuck d => .tuck d
  | .split d bd => .splitK d bd 1
  | .knit d bd k => .knit d bd k

def liftB (u : BWord PlainLabel) : BWord Label :=
  u.map fun
    | .gen g => .gen g
    | .box l i => .box (PlainLabel.toLabel l) i

def denoteOp (win : Window) (s : State) : Op → BWord Label
  | .split d n _ =>
    let z := slot s.rack n
    let F := frontAt s z
    let K := backAt s z
    let y := strandsBefore win s (arrivesFrom d z)
    let l := Label.splitK d n.bed (s.stk n).length
    match d, n.bed with
    | .R, .f => [.box l y] ++ plainB (swapBlocks (y + 2 + F) 1 K true)
    | .R, .b => plainB (swapBlocks y 1 F false) ++ [.box l (y + F)]
    | .L, .f => plainB (swapBlocks (y - K) K 1 false) ++ [.box l (y - K - F)]
    | .L, .b => [.box l (y - K)] ++ plainB (swapBlocks (y - K - F) F 1 true)
  | op => liftB (denoteOp1 win s op)

def denote (win : Window) : State → List Op → Option (State × BWord Label)
  | s, [] => some (s, [])
  | s, op :: ops =>
    match step s op with
    | .error _ => none
    | .ok s' =>
      if windowOk win s op then
        match denote win s' ops with
        | none => none
        | some (t, u) => some (t, denoteOp win s op ++ u)
      else none

Loops that share a needle never part

theorem validLin_apply_of_step {s s' : State} {op : Op} (h : step s op = .ok s') :
    validLin s op ∧ s' = apply s op
Proof
:= by
  unfold step at h
  split at h
  · rename_i hr
    refine ⟨?_, (Except.ok.inj h).symm⟩
    unfold refusal at hr; unfold validLin
    split at hr
    · simp at hr
    · assumption
  · simp at h
theorem runSteps_of_denote {win : Window} {s t : State} {ops : List Op} {M : BWord Label}
    (h : denote win s ops = some (t, M)) : runSteps s ops = some t
Proof
:= by
  induction ops generalizing s M with
  | nil =>
    simp only [denote, Option.some.injEq, Prod.mk.injEq] at h
    simp [runSteps, h.1]
  | cons op ops ih =>
    simp only [denote] at h
    split at h
    · simp at h
    · rename_i s' hst
      split at h
      · split at h
        · simp at h
        · rename_i t' u hd
          simp only [Option.some.injEq, Prod.mk.injEq] at h
          obtain ⟨rfl, -⟩ := h
          simp only [runSteps, hst]
          exact ih hd
      · simp at h
theorem shared_order_kept {s t : State} {ops : List Op} {n : Needle} {x y : Nat} (hs : Distinct s)
    (hrun : runSteps s ops = some t) (hxy : [x, y] <+ leftToRight s n) :
    (∃ m, [x, y] <+ leftToRight t m) ∨ (∀ m, x ∉ t.stk m ∧ y ∉ t.stk m)
Proof
:= by
  suffices key : ∀ (ops : List Op) (s : State), Distinct s → PairKept s x y → runSteps s ops = some t →
      PairKept t x y by
    rcases key ops s hs (Or.inl ⟨n, hxy⟩) hrun with h | ⟨_, _, h⟩
    · exact Or.inl h
    · exact Or.inr h
  intro ops
  induction ops with
  | nil => intro s _ hp hr; simp only [runSteps, Option.some.injEq] at hr; exact hr ▸ hp
  | cons op ops ih =>
    intro s hs hp hr
    simp only [runSteps] at hr
    split at hr
    · rename_i s' hst
      obtain ⟨hl, rfl⟩ := validLin_apply_of_step hst
      exact ih _ (distinct_apply hs hl) (pairKept_step1 hs hl hp) hr
    · simp at hr
theorem shared_order_kept_denote {win : Window} {s t : State} {ops : List Op} {M : BWord Label} {n : Needle}
    {x y : Nat} (hs : Distinct s) (h : denote win s ops = some (t, M)) (hxy : [x, y] <+ leftToRight s n) :
    (∃ m, [x, y] <+ leftToRight t m) ∨ (∀ m, x ∉ t.stk m ∧ y ∉ t.stk m)
Proof
:=
  shared_order_kept hs (runSteps_of_denote h) hxy
theorem distinct_pushFresh {s : State} (hs : Distinct s) (n : Needle) (k : Nat) : Distinct (pushFresh s n k)
Proof
:= by
  induction k generalizing s with
  | zero => exact hs
  | succ k ih =>
    apply ih
    have hv : validLin { s with carrier := arrivesFrom .R (slot s.rack n) } (.tuck .R n) := by
      simp [validLin, linRefusal, erase]
    exact distinct_apply (s := { s with carrier := arrivesFrom .R (slot s.rack n) }) hs hv
theorem distinct_place {s : State} (hs : Distinct s) (l : List (Needle × Nat)) : Distinct (place s l)
Proof
:= by
  induction l generalizing s with
  | nil => exact hs
  | cons p rest ih => obtain ⟨n, k⟩ := p; exact ih (distinct_pushFresh hs n k)
theorem distinct_initState (loops : List (Needle × Nat)) (yarnAt : Int) : Distinct (initState loops yarnAt)
Proof
:=
  distinct_place (distinct_empty yarnAt) loops

Split through a stack, then drop one of its outputs

def oldIdx : Dir → Bed → Nat
  | .R, .f => 1
  | .R, .b => 0
  | .L, .f => 2
  | .L, .b => 1

def newIdx : Dir → Bed → Nat
  | .R, .f => 0
  | .R, .b => 1
  | .L, .f => 1
  | .L, .b => 2

def SplitDropOldIsKnit : Prop := ∀ (d : Dir) (bd : Bed) (k : Nat), 0 < k →
  ∃ M M', D (besideRow d k) [.split d bd, .drop (oldIdx d bd)] = some (tuckRow d, M) ∧
    D (besideRow d k) [.knit d bd] = some (tuckRow d, M') ∧ Iso (2 * k + 1) M M'

def SplitDropNewIsPass : Prop := ∀ (d : Dir) (bd : Bed) (k : Nat), 0 < k →
  ∃ M, D (besideRow d k) [.split d bd, .drop (newIdx d bd)] = some (besideRow d k |>.reverse, M) ∧
    Iso (2 * k + 1) M (match d with
      | .R => swapBlocks 0 1 (2 * k) (bd = .b)
      | .L => swapBlocks 0 (2 * k) 1 (bd = .f))
theorem splitDropOld_Rf_one :
    D (besideRow .R 1) [.split .R .f, .drop (oldIdx .R .f)] = D (besideRow .R 1) [.knit .R .f]
Proof
:= rfl
theorem splitDropOld_Lb_one :
    D (besideRow .L 1) [.split .L .b, .drop (oldIdx .L .b)] = D (besideRow .L 1) [.knit .L .b]
Proof
:= rfl

A wider window changes nothing

win.Sub win': the window win lies inside the window win'. A state inside win has nothing at the positions of win' outside win: no carrier, no loops on the front needle, no loops on the back needle across.

Theorem On win'
rowOf_widen The same stack row
windowWidth_widen The same strand count
denote_widen The program is drawn, with the same end state and literally the same drawing
sim_widen The same reading
  • exists_window: a program that runs from a state with finitely many loops is drawn on some window.
namespace FormalizeKnitting.Knitout
open FormalizeKnitting.Bridge.MR
def Window.Sub (win win' : Window) : Prop := win'.lo ≤ win.lo ∧ win.lo + win.w ≤ win'.lo + win'.w

Runs over the positions of a window

def Fl {α : Type} (g : Int → List α) (lo : Int) (w : Nat) : List α :=
  List.flatMap (fun k => g (lo + k)) (do let a ← List.range w; pure (a : Int))
theorem Fl_eq {α : Type} (g : Int → List α) (lo : Int) (w : Nat) :
    Fl g lo w = (List.range w).flatMap (fun k : Nat => g (lo + k))
Proof
:=
  MR.Rack.flatMap_coe (fun k => g (lo + k)) w
theorem Fl_add {α : Type} (g : Int → List α) (lo : Int) (a b : Nat) :
    Fl g lo (a + b) = Fl g lo a ++ Fl g (lo + a) b
Proof
:= by
  simp only [Fl_eq, List.range_add, List.flatMap_append, List.flatMap_map]
  congr 1
  apply List.flatMap_congr; intro k _
  congr 1; push_cast; omega
theorem Fl_nil {α : Type} {g : Int → List α} {lo : Int} {w : Nat} (h : ∀ k : Nat, k < w → g (lo + k) = []) :
    Fl g lo w = []
Proof
:= by
  rw [Fl_eq, List.flatMap_eq_nil_iff]
  intro k hk
  exact h k (List.mem_range.mp hk)
theorem Fl_pre {α : Type} {g : Int → List α} {lo lo' : Int} (h0 : ∀ i, i < lo → g i = []) (hl : lo' ≤ lo) (i : Int) :
    Fl g lo' (i - lo').toNat = Fl g lo (i - lo).toNat
Proof
:= by
  by_cases hi : i ≤ lo
  · rw [show (i - lo).toNat = 0 by omega, Fl_nil (w := 0) (fun k hk => absurd hk (by omega))]
    exact Fl_nil fun k hk => h0 _ (by omega)
  · rw [show (i - lo').toNat = (lo - lo').toNat + (i - lo).toNat by omega, Fl_add,
      Fl_nil fun k hk => h0 _ (by omega), show lo' + ((lo - lo').toNat : Int) = lo by omega]
    rfl
theorem Fl_widen {α : Type} {g : Int → List α} {lo lo' : Int} {w w' : Nat}
    (h0 : ∀ i, (i < lo ∨ lo + w ≤ i) → g i = []) (hl : lo' ≤ lo) (hh : lo + w ≤ lo' + w') :
    Fl g lo' w' = Fl g lo w
Proof
:= by
  have e : w' = (lo - lo').toNat + (w + (lo' + w' - lo - w).toNat) := by omega
  rw [e, Fl_add, Fl_nil fun k hk => h0 _ (by omega), show lo' + ((lo - lo').toNat : Int) = lo by omega, Fl_add,
    Fl_nil (g := g) (lo := lo + w) fun k hk => h0 _ (by omega)]
  simp

Nothing outside the window

theorem stk_out {win : Window} {s : State} (hI : MR.Inv win s) {n : Needle}
    (hn : slot s.rack n < win.lo ∨ win.lo + win.w ≤ slot s.rack n) : s.stk n = []
Proof
:= by
  by_contra hne
  have := hI.2.1 n hne
  omega
theorem seg_out {win : Window} {s : State} (hI : MR.Inv win s) {i : Int} (hi : i < win.lo ∨ win.lo + win.w ≤ i) :
    seg s i = []
Proof
:= by
  have hc : s.carrier ≠ i := by have := hI.2.2; omega
  have hf : s.stk ⟨.f, i⟩ = [] := stk_out hI (by simp [slot]; omega)
  have hb : s.stk ⟨.b, i - s.rack⟩ = [] := stk_out hI (by simp [slot]; omega)
  simp [seg, hc, MR.nF, MR.nB, hf, hb, stkO]
theorem yarnAt_out {win : Window} {s : State} (hI : MR.Inv win s) {i : Int} (hi : i < win.lo ∨ win.lo + win.w ≤ i) :
    yarnAt s i = 0
Proof
:= by
  have hc : s.carrier ≠ i := by have := hI.2.2; omega
  simp [yarnAt, hc]
theorem frontAt_out {win : Window} {s : State} (hI : MR.Inv win s) {i : Int}
    (hi : i < win.lo ∨ win.lo + win.w ≤ i) : frontAt s i = 0
Proof
:= by
  have hf : s.stk ⟨.f, i⟩ = [] := stk_out hI (by simp [slot]; omega)
  simp [frontAt, hf]
theorem backAt_out {win : Window} {s : State} (hI : MR.Inv win s) {i : Int}
    (hi : i < win.lo ∨ win.lo + win.w ≤ i) : backAt s i = 0
Proof
:= by
  have hb : s.stk ⟨.b, i - s.rack⟩ = [] := stk_out hI (by simp [slot]; omega)
  simp [backAt, hb]
theorem nY_out {win : Window} {s : State} (hI : MR.Inv win s) {i : Int} (hi : i < win.lo ∨ win.lo + win.w ≤ i) :
    MR.nY s i = 0
Proof
:= by
  have hc : s.carrier ≠ i := by have := hI.2.2; omega
  simp [MR.nY, hc]
theorem nF_out {win : Window} {s : State} (hI : MR.Inv win s) {i : Int} (hi : i < win.lo ∨ win.lo + win.w ≤ i) :
    MR.nF s i = 0
Proof
:= by
  have hf : s.stk ⟨.f, i⟩ = [] := stk_out hI (by simp [slot]; omega)
  simp [MR.nF, hf]
theorem nB_out {win : Window} {s : State} (hI : MR.Inv win s) {i : Int} (hi : i < win.lo ∨ win.lo + win.w ≤ i) :
    MR.nB s i = 0
Proof
:= by
  have hb : s.stk ⟨.b, i - s.rack⟩ = [] := stk_out hI (by simp [slot]; omega)
  simp [MR.nB, hb]

Rows, strands and objects before a position

theorem rowOf_pre {win win' : Window} {s : State} (hI : MR.Inv win s) (h : win.Sub win') (i : Int) :
    rowOf s win'.lo (i - win'.lo).toNat = rowOf s win.lo (i - win.lo).toNat
Proof
:=
  Fl_pre (g := seg s) (fun _ hj => seg_out hI (Or.inl hj)) h.1 i
theorem strandsBefore_widen {win win' : Window} {s : State} (hI : MR.Inv win s) (h : win.Sub win') (i : Int) :
    strandsBefore win' s i = strandsBefore win s i
Proof
:= by
  rw [strandsBefore_rowOf, strandsBefore_rowOf, rowOf_pre hI h]
theorem objsBefore_widen {win win' : Window} {s : State} (hI : MR.Inv win s) (h : win.Sub win') (i : Int) :
    objsBefore win' s i = objsBefore win s i
Proof
:= by
  simp only [objsBefore, rowOf_pre hI h]

One instruction

theorem inside_widen {win win' : Window} (h : win.Sub win') {z : Int} (hz : win.inside z = true) :
    win'.inside z = true
Proof
:= by
  have := MR.inside_bounds hz
  have h1 := h.1; have h2 := h.2
  simp [Window.inside]; omega
theorem windowOk_widen {win win' : Window} {s : State} {op : Op} (hI : MR.Inv win s) (h : win.Sub win')
    (hw : windowOk win s op = true) : windowOk win' s op = true
Proof
:= by
  cases op with
  | xfer a b =>
    simp only [windowOk, Bool.and_eq_true] at hw ⊢
    exact ⟨inside_widen h hw.1, inside_widen h hw.2⟩
  | split d a b =>
    simp only [windowOk, Bool.and_eq_true] at hw ⊢
    exact ⟨inside_widen h hw.1, inside_widen h hw.2⟩
  | knit d n => exact inside_widen h hw
  | tuck d n => exact inside_widen h hw
  | miss d n => exact inside_widen h hw
  | drop n => exact inside_widen h hw
  | rack r =>
    simp only [windowOk, List.all_eq_true, List.mem_range, Bool.or_eq_true, List.isEmpty_iff] at hw ⊢
    intro k hk
    by_cases hl : s.stk ⟨.b, win'.lo + k⟩ = []
    · exact Or.inl hl
    · right
      have hj := hI.1 _ hl
      have := (hw (win'.lo + k - win.lo).toNat (by omega)).resolve_left
        (by rw [show win.lo + ((win'.lo + k - win.lo).toNat : Int) = win'.lo + k by omega]; exact hl)
      rw [show win.lo + ((win'.lo + k - win.lo).toNat : Int) = win'.lo + k by omega] at this
      exact inside_widen h this
def rackG (win : Window) (s : State) (r : Int) (i : Int) : BWord PlainLabel :=
  if r < s.rack then swapB (strandsBefore win s i) (yarnAt s i + frontAt s i) (backAt s i) true
  else swapB (strandsBefore win s i - 2 * (s.stk ⟨.b, i - 1 - s.rack⟩).length)
    (2 * (s.stk ⟨.b, i - 1 - s.rack⟩).length) (yarnAt s i + frontAt s i) false
theorem rackBraid_Fl (win : Window) (s : State) (r : Int) : rackBraid win s r = Fl (rackG win s r) win.lo win.w
Proof
:=
  rfl
theorem swapB_zero (a l : Nat) (b : Bool) : swapB a l 0 b = []
Proof
:= rfl
theorem rackBraid_widen {win win' : Window} {s : State} (hI : MR.Inv win s) (h : win.Sub win') (r : Int) :
    rackBraid win' s r = rackBraid win s r
Proof
:= by
  rw [rackBraid_Fl, rackBraid_Fl]
  have e : rackG win' s r = rackG win s r := by
    funext i; simp only [rackG, strandsBefore_widen hI h]
  rw [e]
  refine Fl_widen (fun i hi => ?_) h.1 h.2
  simp only [rackG, yarnAt_out hI hi, frontAt_out hI hi, backAt_out hI hi]
  split <;> rfl
theorem denoteOp_widen {win win' : Window} {s : State} (hI : MR.Inv win s) (h : win.Sub win') (op : Op) :
    denoteOp win' s op = denoteOp win s op
Proof
:= by
  have hsb := strandsBefore_widen hI h
  cases op with
  | rack r => simp only [denoteOp, denoteOp1, rackBraid_widen hI h]
  | xfer a b => rfl
  | knit d n => simp only [denoteOp, denoteOp1, hsb]
  | tuck d n => simp only [denoteOp, denoteOp1, hsb]
  | miss d n => simp only [denoteOp, denoteOp1, hsb]
  | drop n => simp only [denoteOp, denoteOp1, hsb]
  | split d n m => simp only [denoteOp, hsb]
def rackS (win : Window) (s : State) (r : Int) (i : Int) : List Step :=
  if r < s.rack then
    if MR.nB s i = 0 then [] else (List.range (MR.nY s i + ob (MR.nF s i))).map fun j =>
      .x (objsBefore win s i + (MR.nY s i + ob (MR.nF s i)) - 1 - j) true
  else
    if (s.stk ⟨.b, i - 1 - s.rack⟩).length = 0 then [] else (List.range (MR.nY s i + ob (MR.nF s i))).map fun j =>
      .x (objsBefore win s i - 1 + j) false
theorem rackSteps_Fl (win : Window) (s : State) (r : Int) : rackSteps win s r = Fl (rackS win s r) win.lo win.w
Proof
:=
  rfl
theorem rackSteps_widen {win win' : Window} {s : State} (hI : MR.Inv win s) (h : win.Sub win') (r : Int) :
    rackSteps win' s r = rackSteps win s r
Proof
:= by
  rw [rackSteps_Fl, rackSteps_Fl]
  have e : rackS win' s r = rackS win s r := by
    funext i; simp only [rackS, objsBefore_widen hI h]
  rw [e]
  refine Fl_widen (fun i hi => ?_) h.1 h.2
  simp only [rackS, nY_out hI hi, nF_out hI hi, nB_out hI hi, ob]
  split <;> simp
theorem simOp_widen {win win' : Window} {s : State} (hI : MR.Inv win s) (h : win.Sub win') (op : Op) :
    simOp win' s op = simOp win s op
Proof
:= by
  have hob := objsBefore_widen hI h
  cases op with
  | rack r => simp only [simOp, rackSteps_widen hI h]
  | xfer a b => simp only [simOp, hob]
  | knit d n => simp only [simOp, hob]
  | tuck d n => simp only [simOp, hob]
  | miss d n => simp only [simOp, hob]
  | drop n => simp only [simOp, hob]
  | split d n m => simp only [simOp, hob]
open Widen
theorem rowOf_widen {win win' : Window} {s : State} (hI : MR.Inv win s) (h : win.Sub win') :
    Bridge.MR.rowOf s win'.lo win'.w = Bridge.MR.rowOf s win.lo win.w
Proof
:=
  Fl_widen (g := seg s) (fun _ hi => seg_out hI hi) h.1 h.2
theorem windowWidth_widen {win win' : Window} {s : State} (hI : MR.Inv win s) (h : win.Sub win') :
    windowWidth win' s = windowWidth win s
Proof
:= by
  rw [windowWidth_rowOf, windowWidth_rowOf, rowOf_widen hI h]
theorem denote_widen {win win' : Window} {s t : State} {ops : List Op} {B : BWord Label}
    (hI : MR.Inv win s) (hN : ∀ op ∈ ops, NamedIn win op) (hd : denote win s ops = some (t, B))
    (h : win.Sub win') : denote win' s ops = some (t, B)
Proof
:= by
  induction ops generalizing s B with
  | nil => simpa [denote] using hd
  | cons op ops ih =>
    simp only [denote] at hd ⊢
    cases hst : step s op with
    | error e => simp [hst] at hd
    | ok s' =>
      simp only [hst] at hd ⊢
      have hw : windowOk win s op = true := by
        by_contra hw; simp [hw] at hd
      rw [ite_eq_left hw] at hd
      rw [ite_eq_left (windowOk_widen hI h hw)]
      cases hd' : denote win s' ops with
      | none => simp [hd'] at hd
      | some p =>
        obtain ⟨t', u⟩ := p
        simp only [hd', Option.some.injEq, Prod.mk.injEq] at hd
        obtain ⟨rfl, rfl⟩ := hd
        rw [ih (inv_step hI hst hw (hN op (by simp))) (fun o ho => hN o (by simp [ho])) hd',
          denoteOp_widen hI h]
theorem sim_widen {win win' : Window} {s t : State} {ops : List Op} {B : BWord Label}
    (hI : MR.Inv win s) (hN : ∀ op ∈ ops, NamedIn win op) (hd : denote win s ops = some (t, B))
    (h : win.Sub win') : Bridge.MR.sim win' s ops = Bridge.MR.sim win s ops
Proof
:= by
  induction ops generalizing s t B with
  | nil => rfl
  | cons op ops ih =>
    simp only [denote] at hd
    simp only [sim]
    cases hst : step s op with
    | error e => rfl
    | ok s' =>
      simp only [hst] at hd ⊢
      have hw : windowOk win s op = true := by
        by_contra hw; simp [hw] at hd
      rw [ite_eq_left hw] at hd
      cases hd' : denote win s' ops with
      | none => simp [hd'] at hd
      | some p =>
        obtain ⟨t', u⟩ := p
        rw [ih (inv_step hI hst hw (hN op (by simp))) (fun o ho => hN o (by simp [ho])) hd', simOp_widen hI h]

A window for every program

namespace Widen
theorem inv_mono {win win' : Window} {s : State} (hI : MR.Inv win s) (h : win.Sub win') : MR.Inv win' s
Proof
:= by
  obtain ⟨hB, hL, hC⟩ := hI
  have h1 := h.1; have h2 := h.2
  refine ⟨fun j hj => ?_, fun n hn => ?_, ?_⟩
  · have := hB j hj; omega
  · have := hL n hn; omega
  · omega
theorem exists_bound : ∀ l : List Int, ∃ B : Int, 0 ≤ B ∧ ∀ j ∈ l, -B ≤ j ∧ j ≤ B
Proof
  | [] => ⟨0, le_rfl, fun _ h => absurd h (List.not_mem_nil)⟩
  | a :: l => by
    obtain ⟨B, hB, hl⟩ := exists_bound l
    refine ⟨B + max a (-a), by omega, fun j hj => ?_⟩
    rcases List.mem_cons.mp hj with rfl | hj
    · omega
    · have := hl j hj; omega
def rackVals : Op → List Int
  | .rack r => [r]
  | _ => []

def Bounded (B : Int) (op : Op) : Prop :=
  (∀ j ∈ op.named, -B ≤ j ∧ j ≤ B) ∧ ∀ r, op = .rack r → -B ≤ r ∧ r ≤ B

def J (B : Int) (s : State) : Prop :=
  (-B ≤ s.rack ∧ s.rack ≤ B) ∧ ∀ n, s.stk n ≠ [] → -B ≤ n.idx ∧ n.idx ≤ B

def bigWin (B : Int) : Window := ⟨-(2 * B + 2), (4 * B + 5).toNat⟩
theorem inside_big {B z : Int} (hB : 0 ≤ B) (h1 : -(2 * B) - 1 ≤ z) (h2 : z ≤ 2 * B + 1) :
    (bigWin B).inside z = true
Proof
:= by
  simp [Window.inside, bigWin]; omega
theorem slot_bound {B r : Int} {n : Needle} (hr : -B ≤ r ∧ r ≤ B) (hn : -B ≤ n.idx ∧ n.idx ≤ B) :
    -(2 * B) ≤ slot r n ∧ slot r n ≤ 2 * B
Proof
:= by
  obtain ⟨bd, j⟩ := n
  cases bd <;> simp only [slot] at hn ⊢ <;> omega
theorem inside_slot {B : Int} {s : State} {n : Needle} (hB : 0 ≤ B) (hJ : J B s) (hn : n.idx ∈ op.named)
    (hb : Bounded B op) : (bigWin B).inside (slot s.rack n) = true
Proof
:= by
  have := slot_bound hJ.1 (hb.1 _ hn)
  exact inside_big hB (by omega) (by omega)
theorem windowOk_big {B : Int} {s : State} {op : Op} (hB : 0 ≤ B) (hJ : J B s) (hb : Bounded B op) :
    windowOk (bigWin B) s op = true
Proof
:= by
  cases op with
  | xfer a b =>
    simp only [windowOk, Bool.and_eq_true]
    exact ⟨inside_slot hB hJ (by simp [Op.named]) hb, inside_slot hB hJ (by simp [Op.named]) hb⟩
  | split d a b =>
    simp only [windowOk, Bool.and_eq_true]
    exact ⟨inside_slot hB hJ (by simp [Op.named]) hb, inside_slot hB hJ (by simp [Op.named]) hb⟩
  | knit d n => exact inside_slot hB hJ (by simp [Op.named]) hb
  | tuck d n => exact inside_slot hB hJ (by simp [Op.named]) hb
  | miss d n => exact inside_slot hB hJ (by simp [Op.named]) hb
  | drop n => exact inside_slot hB hJ (by simp [Op.named]) hb
  | rack r =>
    have hr := hb.2 r rfl
    simp only [windowOk, List.all_eq_true, List.mem_range, Bool.or_eq_true, List.isEmpty_iff]
    intro k hk
    by_cases hl : s.stk ⟨.b, (bigWin B).lo + k⟩ = []
    · exact Or.inl hl
    · right
      have := hJ.2 _ hl
      simp only at this
      exact inside_big hB (by omega) (by omega)
theorem J_apply {B : Int} {s : State} {op : Op} (hJ : J B s) (hb : Bounded B op) : J B (apply s op)
Proof
:= by
  refine ⟨?_, fun n hn => ?_⟩
  · cases op with
    | rack r => exact hb.2 r rfl
    | _ => exact hJ.1
  · rcases loaded_apply s op n hn with h | h'
    · exact hJ.2 n h
    · exact hb.1 _ h'
theorem denote_big {B : Int} {t : State} (hB : 0 ≤ B) :
    ∀ (ops : List Op) (s : State), (∀ op ∈ ops, Bounded B op) → J B s → runSteps s ops = some t →
      ∃ M, denote (bigWin B) s ops = some (t, M)
Proof
  | [], s, _, _, hr => by
    simp only [runSteps, Option.some.injEq] at hr
    exact ⟨[], by simp [denote, hr]⟩
  | op :: ops, s, hb, hJ, hr => by
    simp only [runSteps] at hr
    cases hst : step s op with
    | error e => simp [hst] at hr
    | ok s' =>
      simp only [hst] at hr
      have hs' : s' = apply s op := (step_ok.mp hst).2
      have hbo := hb op (by simp)
      obtain ⟨M, hM⟩ := denote_big hB ops s' (fun o ho => hb o (by simp [ho])) (hs' ▸ J_apply hJ hbo) hr
      refine ⟨denoteOp (bigWin B) s op ++ M, ?_⟩
      simp only [denote, hst, ite_eq_left (windowOk_big hB hJ hbo), hM]
theorem exists_window {s t : State} {ops : List Op} (hfin : ∃ win0, MR.Inv win0 s)
    (hr : runSteps s ops = some t) :
    ∃ win, MR.Inv win s ∧ (∀ op ∈ ops, NamedIn win op) ∧ ∃ B, denote win s ops = some (t, B)
Proof
:= by
  obtain ⟨win0, hI0⟩ := hfin
  obtain ⟨B, hB, hl⟩ := exists_bound ([s.rack, win0.lo, win0.lo + win0.w] ++
    ops.flatMap (fun op => op.named ++ rackVals op))
  have hrk := hl s.rack (by simp)
  have hlo := hl win0.lo (by simp)
  have hhi := hl (win0.lo + win0.w) (by simp)
  have hops : ∀ op ∈ ops, Bounded B op := by
    intro op hop
    refine ⟨fun j hj => hl j ?_, fun r hr => hl r ?_⟩
    · exact List.mem_append_right _ (List.mem_flatMap.mpr ⟨op, hop, List.mem_append_left _ hj⟩)
    · subst hr
      exact List.mem_append_right _ (List.mem_flatMap.mpr ⟨_, hop, List.mem_append_right _ (by simp [rackVals])⟩)
  have hJ : J B s := by
    refine ⟨hrk, fun n hn => ?_⟩
    obtain ⟨bd, j⟩ := n
    cases bd with
    | f => have := hI0.2.1 _ hn; simp only [slot] at this ⊢; omega
    | b => have := hI0.1 j hn; simp only at this ⊢; omega
  have hsub : win0.Sub (bigWin B) := by
    simp only [Window.Sub, bigWin]; omega
  refine ⟨bigWin B, inv_mono hI0 hsub, fun op hop j hj => ?_, denote_big hB ops s hops hJ hr⟩
  have := (hops op hop).1 j hj
  simp only [bigWin]; omega

Only the loop counts matter

The reader and the drawing use the number of loops on each needle. They do not use the loop identities. So two tracked states with the same counts read the same and draw the same.

Declaration Content
SameCounts s s' erase s = erase s': the same rack, carrier and number of loops on each needle
step_erase step gives the same result up to erase
denote_erase The same drawing, and end states with the same counts
MR.sim_erase The same reading
windowWidth_erase The same strand count
namespace FormalizeKnitting.Knitout
def SameCounts (s s' : State) : Prop := erase s = erase s'
theorem SameCounts.rack {s s' : State} (h : SameCounts s s') : s.rack = s'.rack
Proof
:= by
  have := congrArg LinState.rack h; simpa [erase] using this
theorem SameCounts.carrier {s s' : State} (h : SameCounts s s') : s.carrier = s'.carrier
Proof
:= by
  have := congrArg LinState.Y h; simpa [erase] using this
theorem SameCounts.len {s s' : State} (h : SameCounts s s') (n : Needle) : (s.stk n).length = (s'.stk n).length
Proof
:= by
  have := congrFun (congrArg LinState.L h) n; simpa [erase] using this
theorem leftToRight_length (s : State) (n : Needle) : (leftToRight s n).length = (s.stk n).length
Proof
:= by
  unfold leftToRight; split <;> simp
theorem map_loop_obj (l : List Nat) : (l.map Pt.loop).map Pt.obj = List.replicate l.length CellObj.loop
Proof
:= by
  induction l with
  | nil => rfl
  | cons x xs ih => simp [List.replicate_succ, Pt.obj, ih]
theorem seg1_obj_erase {s s' : State} (h : SameCounts s s') (i : Int) :
    (seg1 s i).map Pt.obj = (seg1 s' i).map Pt.obj
Proof
:= by
  simp only [seg1, List.map_append, map_loop_obj, leftToRight_length, h.carrier, h.rack, h.len]
theorem rowOf1_erase {s s' : State} (h : SameCounts s s') (lo : Int) (w : Nat) : rowOf1 s lo w = rowOf1 s' lo w
Proof
:= by
  simp only [rowOf1, points, List.map_flatMap, seg1_obj_erase h]
theorem strandsBefore_erase {s s' : State} (h : SameCounts s s') (win : Window) (i : Int) :
    strandsBefore win s i = strandsBefore win s' i
Proof
:= by
  simp [strandsBefore, rowOf1_erase h]
theorem windowWidth_erase {s s' : State} (h : SameCounts s s') (win : Window) :
    windowWidth win s = windowWidth win s'
Proof
:= by
  simp [windowWidth, rowOf1_erase h]
theorem frontAt_erase {s s' : State} (h : SameCounts s s') (i : Int) : frontAt s i = frontAt s' i
Proof
:= by
  simp [frontAt, h.len]
theorem backAt_erase {s s' : State} (h : SameCounts s s') (i : Int) : backAt s i = backAt s' i
Proof
:= by
  simp [backAt, h.len, h.rack]
theorem yarnAt_erase {s s' : State} (h : SameCounts s s') (i : Int) : yarnAt s i = yarnAt s' i
Proof
:= by
  simp [yarnAt, h.carrier]
theorem rackBraid_erase {s s' : State} (h : SameCounts s s') (win : Window) (r : Int) :
    rackBraid win s r = rackBraid win s' r
Proof
:= by
  simp only [rackBraid, yarnAt_erase h, frontAt_erase h, backAt_erase h, strandsBefore_erase h, h.rack, h.len]
theorem denoteOp1_erase {s s' : State} (h : SameCounts s s') (win : Window) (op : Op) :
    denoteOp1 win s op = denoteOp1 win s' op
Proof
:= by
  cases op <;> simp only [denoteOp1, rackBraid_erase h, frontAt_erase h, backAt_erase h, strandsBefore_erase h,
    yarnAt_erase h, h.rack, h.len]
theorem denoteOp_erase {s s' : State} (h : SameCounts s s') (win : Window) (op : Op) :
    denoteOp win s op = denoteOp win s' op
Proof
:= by
  cases op <;> simp only [denoteOp, denoteOp1_erase h, frontAt_erase h, backAt_erase h, strandsBefore_erase h,
    h.rack, h.len]
theorem windowOk_erase {s s' : State} (h : SameCounts s s') (win : Window) (op : Op) :
    windowOk win s op = windowOk win s' op
Proof
:= by
  have he : ∀ n, (s.stk n).isEmpty = (s'.stk n).isEmpty := fun n => by
    rw [Bool.eq_iff_iff, List.isEmpty_iff, List.isEmpty_iff, ← List.length_eq_zero_iff, ← List.length_eq_zero_iff,
      h.len]
  cases op <;> simp only [windowOk, h.rack, he]
theorem step_erase {s s' : State} (h : SameCounts s s') (op : Op) :
    (step s op).map erase = (step s' op).map erase
Proof
:= by
  rw [stepL_erase, stepL_erase]; exact congrArg (stepL · op) h
theorem denote_erase (win : Window) : ∀ (s s' : State) (ops : List Op), SameCounts s s' →
    (denote win s ops).map (fun p => (erase p.1, p.2)) = (denote win s' ops).map (fun p => (erase p.1, p.2))
Proof
  | s, s', [], h => by simp [denote, show erase s = erase s' from h]
  | s, s', op :: ops, h => by
    have e := step_erase h op
    simp only [denote]
    cases h1 : step s op with
    | error r =>
      cases h2 : step s' op with
      | error r' => rfl
      | ok t' => rw [h1, h2] at e; simp [Except.map] at e
    | ok t =>
      cases h2 : step s' op with
      | error r' => rw [h1, h2] at e; simp [Except.map] at e
      | ok t' =>
        rw [h1, h2] at e
        simp only [Except.map, Except.ok.injEq] at e
        simp only [windowOk_erase h, denoteOp_erase h]
        split
        · have ih := denote_erase win t t' ops e
          cases d1 : denote win t ops with
          | none => cases d2 : denote win t' ops with
            | none => rfl
            | some q => rw [d1, d2] at ih; simp at ih
          | some p => cases d2 : denote win t' ops with
            | none => rw [d1, d2] at ih; simp at ih
            | some q =>
              rw [d1, d2] at ih
              simp only [Option.map_some, Option.some.injEq, Prod.mk.injEq] at ih
              simp [ih.1, ih.2]
        · rfl
namespace FormalizeKnitting.Bridge.MR
open FormalizeKnitting.Knitout FormalizeKnitting.Knitout.MR
theorem seg_erase {s s' : State} (h : SameCounts s s') (i : Int) : seg s i = seg s' i
Proof
:= by
  simp [seg, nF, nB, h.carrier, h.rack, h.len]
theorem rowOf_erase {s s' : State} (h : SameCounts s s') (lo : Int) (w : Nat) : rowOf s lo w = rowOf s' lo w
Proof
:= by
  simp only [rowOf, seg_erase h]
theorem objsBefore_erase {s s' : State} (h : SameCounts s s') (win : Window) (i : Int) :
    objsBefore win s i = objsBefore win s' i
Proof
:= by
  simp only [objsBefore, rowOf_erase h]
theorem simOp_erase {s s' : State} (h : SameCounts s s') (win : Window) (op : Op) :
    simOp win s op = simOp win s' op
Proof
:= by
  cases op <;> simp [simOp, rackSteps, objsBefore_erase h, nY, nF, nB, h.carrier, h.rack, h.len]
theorem sim_erase (win : Window) : ∀ (s s' : State) (ops : List Op), SameCounts s s' → sim win s ops = sim win s' ops
Proof
  | _, _, [], _ => rfl
  | s, s', op :: ops, h => by
    have e := step_erase h op
    simp only [sim]
    cases h1 : step s op with
    | error r =>
      cases h2 : step s' op with
      | error r' => rfl
      | ok t' => rw [h1, h2] at e; simp [Except.map] at e
    | ok t =>
      cases h2 : step s' op with
      | error r' => rw [h1, h2] at e; simp [Except.map] at e
      | ok t' =>
        rw [h1, h2] at e
        simp only [Except.map, Except.ok.injEq] at e
        dsimp only
        rw [simOp_erase h, sim_erase win t t' ops e]

Good windows

Declaration Content
Window.hull The smallest window that contains two windows (sub_hull_left, sub_hull_right)
Good win s ops The window holds the state (MR.Inv), holds each needle that the program names (NamedIn), and denote draws the program in it
exists_good A program that runs from a state with finitely many loops has a good window

Windows

def _root_.FormalizeKnitting.Knitout.Window.hull (a b : Window) : Window :=
  ⟨min a.lo b.lo, (max (a.lo + a.w) (b.lo + b.w) - min a.lo b.lo).toNat⟩
theorem sub_hull_left (a b : Window) : a.Sub (a.hull b)
Proof
:= by
  simp only [Window.Sub, Window.hull]; constructor <;> omega
theorem sub_hull_right (a b : Window) : b.Sub (a.hull b)
Proof
:= by
  simp only [Window.Sub, Window.hull]; constructor <;> omega
def Good (win : Window) (s : State) (ops : List Op) : Prop :=
  MR.Inv win s ∧ (∀ op ∈ ops, NamedIn win op) ∧ ∃ t B, denote win s ops = some (t, B)
theorem exists_good {s t : State} {ops : List Op} (hfin : ∃ win0, MR.Inv win0 s) (hr : runSteps s ops = some t) :
    ∃ win, Good win s ops
Proof
:= by
  obtain ⟨win, hI, hN, B, hd⟩ := exists_window hfin hr
  exact ⟨win, hI, hN, t, B, hd⟩

Any good window gives the same drawing and reading

A knitout program is drawn and read in a window. The choice of good window does not change the drawing or the reading. Only the loop counts of the state matter.

Declaration Content
hop SimOpCorrect for every instruction
bw The drawing of a program in a window. It is empty when denote does not draw the program there.
bw_indep, sim_indep Two good windows give the same drawing and the same reading.
good_erase A good window for a state is good for each state with the same counts.
good_split A good window for p ++ q is good for p, and for q after p. The drawing of p ++ q is the two drawings.
sameCounts_end A program from a to b ends on a state with the counts of b.
winOf, winHom A chosen window for a count state, and a chosen good window for a knitout program
namespace FormalizeKnitting.Retract
open CategoryTheory FormalizeKnitting.Knitout FormalizeKnitting.Bridge
theorem hop : ∀ op, MR.SimOpCorrect op
Proof
:=
  MR.simOpCorrect_all MR.missCase MR.tuckCase MR.knitCase MR.splitCase MR.Rack.rackCase
theorem inv_erase {win : Window} {s s' : State} (h : SameCounts s s') (hI : MR.Inv win s) : MR.Inv win s'
Proof
:= by
  obtain ⟨hB, hL, hC⟩ := hI
  have hne : ∀ n, s'.stk n ≠ [] → s.stk n ≠ [] := by
    intro n hn he
    apply hn
    apply List.eq_nil_of_length_eq_zero
    rw [← h.len n, he]; rfl
  refine ⟨fun j hj => hB j (hne _ hj), fun n hn => ?_, ?_⟩
  · rw [← h.rack]; exact hL n (hne n hn)
  · rw [← h.carrier]; exact hC
def bw (win : Window) (s : State) (ops : List Op) : BWord Label :=
  ((denote win s ops).map Prod.snd).getD []
theorem bw_eq {win : Window} {s t : State} {ops : List Op} {B : BWord Label}
    (h : denote win s ops = some (t, B)) : bw win s ops = B
Proof
:= by
  simp [bw, h]
theorem bw_erase {win : Window} {s s' : State} (h : SameCounts s s') (ops : List Op) :
    bw win s ops = bw win s' ops
Proof
:= by
  have e := congrArg (Option.map Prod.snd) (denote_erase win s s' ops h)
  simp only [Option.map_map] at e
  unfold bw
  exact congrArg (fun o => Option.getD o []) e
theorem good_erase {win : Window} {s s' : State} {ops : List Op} (h : SameCounts s s') (hg : Good win s ops) :
    Good win s' ops
Proof
:= by
  obtain ⟨hI, hN, t, B, hd⟩ := hg
  refine ⟨inv_erase h hI, hN, ?_⟩
  have e := denote_erase win s s' ops h
  rw [hd] at e
  cases hd' : denote win s' ops with
  | none => rw [hd'] at e; simp at e
  | some p => exact ⟨p.1, p.2, rfl⟩
theorem bw_indep {w1 w2 : Window} {s : State} {ops : List Op} (h1 : Good w1 s ops) (h2 : Good w2 s ops) :
    bw w1 s ops = bw w2 s ops
Proof
:= by
  obtain ⟨hI1, hN1, t1, B1, hd1⟩ := h1
  obtain ⟨hI2, hN2, t2, B2, hd2⟩ := h2
  have e1 := denote_widen hI1 hN1 hd1 (sub_hull_left w1 w2)
  have e2 := denote_widen hI2 hN2 hd2 (sub_hull_right w1 w2)
  rw [e1] at e2
  rw [bw_eq hd1, bw_eq hd2]
  simp only [Option.some.injEq, Prod.mk.injEq] at e2
  exact e2.2
theorem sim_indep {w1 w2 : Window} {s : State} {ops : List Op} (h1 : Good w1 s ops) (h2 : Good w2 s ops) :
    MR.sim w1 s ops = MR.sim w2 s ops
Proof
:= by
  obtain ⟨hI1, hN1, t1, B1, hd1⟩ := h1
  obtain ⟨hI2, hN2, t2, B2, hd2⟩ := h2
  rw [← sim_widen hI1 hN1 hd1 (sub_hull_left w1 w2), sim_widen hI2 hN2 hd2 (sub_hull_right w1 w2)]
theorem denote_split (win : Window) : ∀ (s : State) (p q : List Op) (t : State) (B : BWord Label),
    denote win s (p ++ q) = some (t, B) →
      ∃ s1 B1 B2, denote win s p = some (s1, B1) ∧ denote win s1 q = some (t, B2) ∧ B = B1 ++ B2
Proof
  | s, [], q, t, B, h => ⟨s, [], B, rfl, h, rfl⟩
  | s, op :: ops, q, t, B, h => by
    simp only [List.cons_append, denote] at h
    cases hs : step s op with
    | error e => simp [hs] at h
    | ok s' =>
      simp only [hs] at h
      by_cases hw : windowOk win s op = true
      · rw [ite_eq_left hw] at h
        cases hd : denote win s' (ops ++ q) with
        | none => simp [hd] at h
        | some p =>
          obtain ⟨t', u⟩ := p
          simp only [hd, Option.some.injEq, Prod.mk.injEq] at h
          obtain ⟨rfl, rfl⟩ := h
          obtain ⟨s1, B1, B2, h1, h2, rfl⟩ := denote_split win s' ops q t' u hd
          refine ⟨s1, denoteOp win s op ++ B1, B2, ?_, h2, by simp⟩
          simp [denote, hs, ite_eq_left hw, h1]
      · rw [ite_eq_right hw] at h; simp at h
theorem good_split {win : Window} {s : State} {p q : List Op} (h : Good win s (p ++ q)) :
    Good win s p ∧ ∃ s1, runSteps s p = some s1 ∧ Good win s1 q ∧ bw win s (p ++ q) = bw win s p ++ bw win s1 q
Proof
:= by
  obtain ⟨hI, hN, t, B, hd⟩ := h
  obtain ⟨s1, B1, B2, h1, h2, rfl⟩ := denote_split win s p q t B hd
  have hNp : ∀ op ∈ p, NamedIn win op := fun op ho => hN op (List.mem_append_left _ ho)
  have hNq : ∀ op ∈ q, NamedIn win op := fun op ho => hN op (List.mem_append_right _ ho)
  refine ⟨⟨hI, hNp, s1, B1, h1⟩, s1, runSteps_of_denote h1,
    ⟨MR.inv_denote win s p s1 B1 hI hNp h1, hNq, t, B2, h2⟩, ?_⟩
  rw [bw_eq hd, bw_eq h1, bw_eq h2]
theorem sameCounts_end {a b : KnitoutObj} (f : KnitoutProgram a b) {s : State} (h : runSteps (lift a.t) f.1 = some s) :
    SameCounts s (lift b.t)
Proof
:= by
  have e := runStepsL_of_runSteps _ _ _ h
  rw [erase_lift, f.2] at e
  show erase s = erase (lift b.t)
  rw [erase_lift]; exact (Option.some.inj e).symm
theorem runSteps_hom {a b : KnitoutObj} (f : KnitoutProgram a b) : ∃ s, runSteps (lift a.t) f.1 = some s
Proof
:= by
  have e : runStepsL (erase (lift a.t)) f.1 = some b.t := by rw [erase_lift]; exact f.2
  obtain ⟨s, hs, -⟩ := runSteps_of_runStepsL _ _ _ e
  exact ⟨s, hs⟩
theorem exists_good_hom {a b : KnitoutObj} (f : KnitoutProgram a b) : ∃ win, Good win (lift a.t) f.1
Proof
:= by
  obtain ⟨s, hs⟩ := runSteps_hom f
  exact exists_good a.fin hs
noncomputable def winOf (a : KnitoutObj) : Window := Classical.choose a.fin
theorem winOf_inv (a : KnitoutObj) : MR.Inv (winOf a) (lift a.t)
Proof
:= Classical.choose_spec a.fin
noncomputable def winHom {a b : KnitoutObj} (f : KnitoutProgram a b) : Window := Classical.choose (exists_good_hom f)
theorem winHom_good {a b : KnitoutObj} (f : KnitoutProgram a b) : Good (winHom f) (lift a.t) f.1
Proof
:=
  Classical.choose_spec (exists_good_hom f)

The drawing functor draw𝒦 : 𝒦 ⥤ 𝒯

Part Definition
Objects A count state goes to its strand count (wK).
Arrows A knitout program goes to the class of expand sig (bw …), the opened boxed drawing of denote (drawKmap).
Composition good_split and bw_erase
  • drawKmap uses the window winHom. drawKmap_eq: any good window gives the same arrow.
  • wf_good gives that the drawing is well formed. Its proof reads the program and uses MR.D_wf on the reading.
namespace FormalizeKnitting.Retract
open CategoryTheory FormalizeKnitting.Knitout FormalizeKnitting.Bridge
noncomputable def drawKmap {a b : KnitoutObj} (f : KnitoutProgram a b) : (⟨wK a⟩ : TangleObj) ⟶ ⟨wK b⟩ :=
  TangleObj.hom (expand sig (bw (winHom f) (lift a.t) f.1)) (wf_good f (winHom_good f))
theorem drawKmap_eq {a b : KnitoutObj} (f : KnitoutProgram a b) {win : Window} (h : Good win (lift a.t) f.1) :
    drawKmap f = TangleObj.hom (expand sig (bw win (lift a.t) f.1)) (wf_good f h)
Proof
:=
  TangleObj.hom_congr _ _ (by rw [bw_indep (winHom_good f) h])
noncomputable def drawK : KnitoutObj ⥤ TangleObj where
  obj a := ⟨wK a⟩
  map f := drawKmap f
  map_id a := by
    show drawKmap (𝟙 a) = TangleObj.hom [] rfl
    exact TangleObj.hom_congr _ _ rfl
  map_comp {a b c} f g := by
    show drawKmap (KnitoutProgram.comp f g) = drawKmap f ≫ drawKmap g
    have hg := winHom_good (KnitoutProgram.comp f g)
    obtain ⟨hp, s1, hs1, hq, hbw⟩ := good_split hg
    have hc := sameCounts_end f hs1
    rw [drawKmap_eq f hp, drawKmap_eq g (good_erase hc hq), TangleObj.hom_comp]
    apply TangleObj.hom_congr
    rw [show (KnitoutProgram.comp f g).1 = f.1 ++ g.1 from rfl, hbw, expand_append, bw_erase hc]
end FormalizeKnitting.Retract

References

  1. Lin, Narayanan, Ikarashi, Ragan-Kelley, Bernstein, McCann, "Semantics and Scheduling for Machine Knitting Compilers", ACM TOG 42(4), 2023. Lemma B.1; Def. 5.5, Fig. 12; Def. 5.6.
  2. Hurtig et al. 2025. Fig. 5; Fig. 5 (moves L1, L2, M1).