Research | Knitting | Functor C: Compile

Functor C: Compile

C compiles shorthand programs to knitout. It puts each row on the machine in one fixed layout. It compiles each step to knitout instructions. The proofs show that the machine accepts each compiled program, and that the program draws the same tangle as the steps.

The compact layout and the layout planner

Machine facts for the bridge between knitout and the shorthand. The planner moves the objects of a row of single loops along the front bed. The compiler uses it on a row in which each object is the yarn or a needle with loops.

Section Key declarations
The compact layout compactAt1
The layout planner Comp1, cpos, loopStep, yarnTo, moveObject1, arrange1, canonical
The planner invariant Fits1, NamedIn3, denote1_append
Free moves draw nothing rackBraid_nil, miss_free, loopStep_right_free, loopStep_left_free
arrange1 arrange1_def, arrange1_total, arrangeTotal'_two
Reading a laid-out machine sb_lo, sb_succ, sb_add, sb_congr
One instruction denote1_single_op, tuck_valid, knitOps1, Knit.knit_block, Knit.loopStep_onto

The compact layout

  • Rack 0. The back bed is empty.
  • The k-th loop (from 1) is alone on front needle f k.
  • The carrier is in the slot immediately after the loops before it.

The layout planner

  • Comp1: a row, one coordinate for each object, and the knitout written so far.
  • arrange1 looks only at the objects of the row: the yarn or a loop.

The layout convention

def compactAt1 : CellRow → Nat → List Int
  | [], _ => []
  | .loop :: r, j => ((j + 1 : Nat) : Int) :: compactAt1 r (j + 1)
  | .yarn :: r, j => ((j + 1 : Nat) : Int) :: compactAt1 r j

The layout planner

structure Comp1 where
  row : CellRow
  at_ : List Int
  ops : List Op

def cpos (o : CellObj) (c : Int) : Int := if o = .loop then 2 * c else 2 * c - 1

def fN (i : Int) : Needle := ⟨.f, i⟩

def bN (i : Int) : Needle := ⟨.b, i⟩

def loopStep (n : Int) (right : Bool) : List Op :=
  if right then [.xfer (fN n) (bN n), .rack 1, .xfer (bN n) (fN (n + 1)), .rack 0]
  else [.xfer (fN n) (bN n), .rack (-1), .xfer (bN n) (fN (n - 1)), .rack 0]

def yarnTo (a b : Int) : List Op :=
  if a < b then (List.range (b - a).toNat).map fun k => .miss .R (fN (a + k))
  else (List.range (a - b).toNat).map fun k => .miss .L (fN (a - 1 - k))

def moveObject1 (c : Comp1) (j : Nat) (dest : Int) : Comp1 :=
  let fr := c.at_.getD j 0
  let moves :=
    if c.row.getD j .yarn = .yarn then yarnTo fr dest
    else if fr < dest then (List.range (dest - fr).toNat).flatMap fun k => loopStep (fr + k) true
    else (List.range (fr - dest).toNat).flatMap fun k => loopStep (fr - k) false
  { c with at_ := c.at_.set j dest, ops := c.ops ++ moves }

def arrange1 (c : Comp1) (target : List Int) : Option Comp1 :=
  let n := c.row.length
  let pt := fun j => cpos (c.row.getD j .yarn) (target.getD j 0)
  let cur := fun j => cpos (c.row.getD j .yarn) (c.at_.getD j 0)
  if target.length = n ∧ (List.range (n - 1)).all (fun j => decide (pt j < pt (j + 1))) then
    let c1 := (List.range n).reverse.foldl (fun c j => if pt j > cur j then moveObject1 c j (target.getD j 0) else c) c
    some ((List.range n).foldl (fun c j => if pt j < cur j then moveObject1 c j (target.getD j 0) else c) c1)
  else none

def canonical (S : Nat) (n : Nat) : List Int := (List.range n).map fun j => (S : Int) + 1 + S * j

def spliceL {α : Type} (l : List α) (first len : Nat) (new : List α) : List α :=
  l.take first ++ new ++ l.drop (first + len)

def swapAt {α : Type} (l : List α) (j : Nat) (d : α) : List α := spliceL l j 2 [l.getD (j + 1) d, l.getD j d]
end Knitout

The planner invariant

Declaration Content
Fits1 Each coordinate is at least 2 inside the window
NamedIn3 Each named needle is at least 3 inside the window
denote1_append The drawing of two programs, one after the other
namespace Knitout
open scoped List
def Fits1 (win : Window) (c : Comp1) : Prop := ∀ x ∈ c.at_, win.lo + 2 ≤ x ∧ x + 2 < win.lo + win.w

def NamedIn3 (win : Window) (op : Op) : Prop := ∀ j ∈ op.named, win.lo + 3 ≤ j ∧ j + 3 < win.lo + win.w

Programs: running one after the other

theorem denote1_append (win : Window) :
    ∀ (s : State) (a b : List Op) (s1 s2 : State) (M1 M2 : BWord PlainLabel),
      denote1 win s a = some (s1, M1) → denote1 win s1 b = some (s2, M2) → denote1 win s (a ++ b) = some (s2, M1 ++ M2)
Proof
  | s, [], b, s1, s2, M1, M2, ha, hb => by
    simp only [denote1, Option.some.injEq, Prod.mk.injEq] at ha
    obtain ⟨rfl, rfl⟩ := ha; simpa using hb
  | s, op :: ops, b, s1, s2, M1, M2, ha, hb => by
    simp only [denote1] at ha
    split at ha
    · simp at ha
    · rename_i s' hs
      split at ha
      · rename_i hw
        split at ha
        · simp at ha
        · rename_i t' u hd
          simp only [Option.some.injEq, Prod.mk.injEq] at ha
          obtain ⟨rfl, rfl⟩ := ha
          simp only [List.cons_append, denote1, hs, hw, ite_true, denote1_append win s' ops b t' s2 u M2 hd hb,
            List.append_assoc]
      · simp at ha

Free moves draw nothing

These hold for each state. They assume no layout.

  • rackBraid_nil: a rack draws nothing if, at each position of the window, one side of each swap is empty.
  • miss_free: a miss past a position with no loops draws nothing.
  • loopStep_right_free, loopStep_left_free: loopStep into a free position is accepted and draws nothing.
namespace Knitout
theorem swapBlocks_left_zero (i r : Nat) (b : Bool) : swapBlocks i 0 r b = []
Proof
:= by
  simp [swapBlocks]
theorem swapBlocks_right_zero (i l : Nat) (b : Bool) : swapBlocks i l 0 b = []
Proof
:= by
  simp [swapBlocks]
theorem swapB_nil {i l r : Nat} {b : Bool} (h : l = 0 ∨ r = 0) : swapB i l r b = []
Proof
:= by
  rcases h with rfl | rfl
  · simp [swapB, swapBlocks_left_zero, plainB]
  · simp [swapB, swapBlocks_right_zero, plainB]
theorem rackBraid_nil (win : Window) (s : State) (r : Int)
    (h : ∀ k : Nat, k < win.w →
      if r < s.rack then yarnAt s (win.lo + k) + frontAt s (win.lo + k) = 0 ∨ backAt s (win.lo + k) = 0
      else (s.stk ⟨.b, win.lo + k - 1 - s.rack⟩).length = 0 ∨
        yarnAt s (win.lo + k) + frontAt s (win.lo + k) = 0) :
    rackBraid win s r = []
Proof
:= by
  rw [rackBraid_eq]
  simp only [plainB, List.map_eq_nil_iff, List.flatMap_eq_nil_iff]
  intro ki hki
  obtain ⟨k, hk, rfl⟩ : ∃ k : Nat, k < win.w ∧ ki = (k : Int) := by simpa using hki
  have hk' := h k hk
  split at hk' <;> simp only [*, ite_true, ite_false]
  · rcases hk' with h0 | h0
    · rw [h0, swapBlocks_left_zero]
    · rw [h0, swapBlocks_right_zero]
  · rcases hk' with h0 | h0
    · rw [h0, Nat.mul_zero, swapBlocks_left_zero]
    · rw [h0, swapBlocks_right_zero]
theorem miss_free (win : Window) (s : State) (d : Dir) (n : Needle)
    (hf : frontAt s (slot s.rack n) = 0) (hb : backAt s (slot s.rack n) = 0) : denoteOp1 win s (.miss d n) = []
Proof
:= by
  cases d <;> simp only [denoteOp1, hf, hb, swapB_nil (Or.inr rfl), swapB_nil (Or.inl rfl), List.append_nil]
theorem denote1_cons_ok {win : Window} {s s' : State} {op : Op} (ops : List Op) (h : step1 s op = .ok s')
    (hw : windowOk win s op = true) :
    denote1 win s (op :: ops) = (denote1 win s' ops).map (fun p => (p.1, denoteOp1 win s op ++ p.2))
Proof
:= by
  simp only [denote1, h, hw, ite_true]
  cases denote1 win s' ops <;> rfl
theorem loopStep_right_free (win : Window) (st : State) (n : Int) (hr : st.rack = 0)
    (hb : ∀ j, st.stk ⟨.b, j⟩ = []) (hc : st.carrier ≠ n + 1) (hf : st.stk ⟨.f, n + 1⟩ = [])
    (hin : win.inside n = true) (hin1 : win.inside (n + 1) = true) :
    ∃ st', denote1 win st (loopStep n true) = some (st', []) ∧ st'.rack = 0 ∧ st'.carrier = st.carrier ∧
      ∀ q, st'.stk q = if q = ⟨.f, n + 1⟩ then st.stk ⟨.f, n⟩ else if q = ⟨.f, n⟩ then [] else st.stk q
Proof
:= by
  set s1 := apply st (.xfer (fN n) (bN n)) with hs1
  set s2 := apply s1 (.rack 1) with hs2
  set s3 := apply s2 (.xfer (bN n) (fN (n + 1))) with hs3
  set s4 := apply s3 (.rack 0) with hs4
  have k1 : ∀ q, s1.stk q = if q = ⟨.b, n⟩ then (st.stk ⟨.f, n⟩).reverse else if q = ⟨.f, n⟩ then [] else st.stk q := by
    intro q
    simp only [hs1, apply, upd_apply, xferStack, fN, bN, hb, List.append_nil]
  have k3 : ∀ q, s3.stk q = if q = ⟨.f, n + 1⟩ then st.stk ⟨.f, n⟩ else if q = ⟨.f, n⟩ then [] else st.stk q := by
    intro q
    have e2 : ∀ q, s2.stk q = s1.stk q := fun _ => rfl
    show Function.update (Function.update s2.stk (bN n) []) (fN (n + 1))
      (xferStack (s2.stk (bN n)) (s2.stk (fN (n + 1)))) q = _
    simp only [upd_apply, xferStack, e2, k1, fN, bN]
    by_cases h1 : q = ⟨.f, n + 1⟩
    · subst h1; simp [hf]
    · by_cases h2 : q = ⟨.b, n⟩
      · subst h2; simp [hb]
      · simp [h1, h2]
  have h1 : step1 st (.xfer (fN n) (bN n)) = .ok s1 :=
    step1_ok.mpr ⟨by simp [validCrate, crateRefusal1, linRefusal, aligned, slot, erase, hr, crateExtra1, fN, bN], rfl⟩
  have w1 : windowOk win st (.xfer (fN n) (bN n)) = true := by simp [windowOk, slot, hr, fN, bN, hin]
  have h2 : step1 s1 (.rack 1) = .ok s2 :=
    step1_ok.mpr ⟨by simp [validCrate, crateRefusal1, linRefusal, erase, hs1, apply, hr, crateExtra1], rfl⟩
  have w2 : windowOk win s1 (.rack 1) = true := by
    simp only [windowOk, List.all_eq_true, List.mem_range, Bool.or_eq_true, List.isEmpty_iff]
    intro k _
    rw [k1]
    by_cases hk : win.lo + (k : Int) = n
    · right; rw [hk]; exact hin1
    · left; simp [hk, hb]
  have d2 : denoteOp1 win s1 (.rack 1) = [] := by
    apply rackBraid_nil
    intro k _
    have hr1 : s1.rack = 0 := by simp [hs1, apply, hr]
    rw [ite_eq_right (by rw [hr1]; omega)]
    by_cases hk : win.lo + (k : Int) - 1 - s1.rack = n
    · right
      have e : win.lo + (k : Int) = n + 1 := by rw [hr1] at hk; omega
      rw [e]
      simp only [yarnAt, frontAt, k1]
      simp [hs1, apply, hc, hf]
    · left; rw [k1]; simp [hk, hb]
  have h3 : step1 s2 (.xfer (bN n) (fN (n + 1))) = .ok s3 :=
    step1_ok.mpr ⟨by simp [validCrate, crateRefusal1, linRefusal, aligned, slot, erase, hs2, apply, crateExtra1, fN, bN], rfl⟩
  have w3 : windowOk win s2 (.xfer (bN n) (fN (n + 1))) = true := by
    simp [windowOk, slot, hs2, apply, fN, bN, hin1]
  have h4 : step1 s3 (.rack 0) = .ok s4 :=
    step1_ok.mpr ⟨by simp [validCrate, crateRefusal1, linRefusal, erase, hs3, hs2, apply, crateExtra1], rfl⟩
  have w4 : windowOk win s3 (.rack 0) = true := by
    simp only [windowOk, List.all_eq_true, List.mem_range, Bool.or_eq_true, List.isEmpty_iff]
    intro k _; left; rw [k3]; simp [hb]
  have d4 : denoteOp1 win s3 (.rack 0) = [] := by
    apply rackBraid_nil
    intro k _
    have hr3 : s3.rack = 1 := by simp [hs3, hs2, apply]
    rw [ite_eq_left (by rw [hr3]; omega)]
    right; simp only [backAt, k3]; simp [hb]
  refine ⟨s4, ?_, by simp [hs4, apply], by simp [hs4, hs3, hs2, hs1, apply], fun q => by
    rw [show s4.stk q = s3.stk q from rfl, k3]⟩
  simp only [loopStep, ite_true]
  rw [denote1_cons_ok _ h1 w1, denote1_cons_ok _ h2 w2, denote1_cons_ok _ h3 w3, denote1_cons_ok _ h4 w4, d2, d4]
  simp [denote1, denoteOp1]
theorem loopStep_left_free (win : Window) (st : State) (n : Int) (hr : st.rack = 0)
    (hb : ∀ j, st.stk ⟨.b, j⟩ = []) (hc : st.carrier ≠ n) (hf : st.stk ⟨.f, n - 1⟩ = [])
    (hin : win.inside n = true) (hin1 : win.inside (n - 1) = true) :
    ∃ st', denote1 win st (loopStep n false) = some (st', []) ∧ st'.rack = 0 ∧ st'.carrier = st.carrier ∧
      ∀ q, st'.stk q = if q = ⟨.f, n - 1⟩ then st.stk ⟨.f, n⟩ else if q = ⟨.f, n⟩ then [] else st.stk q
Proof
:= by
  set s1 := apply st (.xfer (fN n) (bN n)) with hs1
  set s2 := apply s1 (.rack (-1)) with hs2
  set s3 := apply s2 (.xfer (bN n) (fN (n - 1))) with hs3
  set s4 := apply s3 (.rack 0) with hs4
  have k1 : ∀ q, s1.stk q = if q = ⟨.b, n⟩ then (st.stk ⟨.f, n⟩).reverse else if q = ⟨.f, n⟩ then [] else st.stk q := by
    intro q
    simp only [hs1, apply, upd_apply, xferStack, fN, bN, hb, List.append_nil]
  have k3 : ∀ q, s3.stk q = if q = ⟨.f, n - 1⟩ then st.stk ⟨.f, n⟩ else if q = ⟨.f, n⟩ then [] else st.stk q := by
    intro q
    have e2 : ∀ q, s2.stk q = s1.stk q := fun _ => rfl
    show Function.update (Function.update s2.stk (bN n) []) (fN (n - 1))
      (xferStack (s2.stk (bN n)) (s2.stk (fN (n - 1)))) q = _
    simp only [upd_apply, xferStack, e2, k1, fN, bN]
    by_cases h1 : q = ⟨.f, n - 1⟩
    · subst h1; simp [hf]
    · by_cases h2 : q = ⟨.b, n⟩
      · subst h2; simp [hb]
      · simp [h1, h2]
  have h1 : step1 st (.xfer (fN n) (bN n)) = .ok s1 :=
    step1_ok.mpr ⟨by simp [validCrate, crateRefusal1, linRefusal, aligned, slot, erase, hr, crateExtra1, fN, bN], rfl⟩
  have w1 : windowOk win st (.xfer (fN n) (bN n)) = true := by simp [windowOk, slot, hr, fN, bN, hin]
  have h2 : step1 s1 (.rack (-1)) = .ok s2 :=
    step1_ok.mpr ⟨by simp [validCrate, crateRefusal1, linRefusal, erase, hs1, apply, hr, crateExtra1], rfl⟩
  have w2 : windowOk win s1 (.rack (-1)) = true := by
    simp only [windowOk, List.all_eq_true, List.mem_range, Bool.or_eq_true, List.isEmpty_iff]
    intro k _
    rw [k1]
    by_cases hk : win.lo + (k : Int) = n
    · right; rw [hk]; exact hin1
    · left; simp [hk, hb]
  have d2 : denoteOp1 win s1 (.rack (-1)) = [] := by
    apply rackBraid_nil
    intro k _
    have hr1 : s1.rack = 0 := by simp [hs1, apply, hr]
    rw [ite_eq_left (by rw [hr1]; omega)]
    by_cases hk : win.lo + (k : Int) = n
    · left
      rw [hk]
      simp only [yarnAt, frontAt, k1]
      simp [hs1, apply, hc]
    · right; simp only [backAt, hr1, sub_zero, k1]; simp [hk, hb]
  have em : n + -1 = n - 1 := by omega
  have h3 : step1 s2 (.xfer (bN n) (fN (n - 1))) = .ok s3 :=
    step1_ok.mpr ⟨by simp [validCrate, crateRefusal1, linRefusal, aligned, slot, erase, hs2, apply, crateExtra1, fN, bN, em], rfl⟩
  have w3 : windowOk win s2 (.xfer (bN n) (fN (n - 1))) = true := by
    simp [windowOk, slot, hs2, apply, fN, bN, hin1, em]
  have h4 : step1 s3 (.rack 0) = .ok s4 :=
    step1_ok.mpr ⟨by simp [validCrate, crateRefusal1, linRefusal, erase, hs3, hs2, apply, crateExtra1], rfl⟩
  have w4 : windowOk win s3 (.rack 0) = true := by
    simp only [windowOk, List.all_eq_true, List.mem_range, Bool.or_eq_true, List.isEmpty_iff]
    intro k _; left; rw [k3]; simp [hb]
  have d4 : denoteOp1 win s3 (.rack 0) = [] := by
    apply rackBraid_nil
    intro k _
    have hr3 : s3.rack = -1 := by simp [hs3, hs2, apply]
    rw [ite_eq_right (by rw [hr3]; omega)]
    left; simp only [k3]; simp [hb]
  refine ⟨s4, ?_, by simp [hs4, apply], by simp [hs4, hs3, hs2, hs1, apply], fun q => by
    rw [show s4.stk q = s3.stk q from rfl, k3]⟩
  simp only [loopStep, Bool.false_eq_true, ite_false]
  rw [denote1_cons_ok _ h1 w1, denote1_cons_ok _ h2 w2, denote1_cons_ok _ h3 w3, denote1_cons_ok _ h4 w4, d2, d4]
  simp [denote1, denoteOp1]

The compact layout

  • length_compactAt1: compactAt1 gives one coordinate for each object of the row.
namespace Knitout
theorem length_compactAt1 : ∀ (r : CellRow) (m : Nat), (compactAt1 r m).length = r.length
Proof
  | [], _ => rfl
  | .loop :: r, m => by simp [compactAt1, length_compactAt1 r]
  | .yarn :: r, m => by simp [compactAt1, length_compactAt1 r]

The starting machine

theorem compact_sorted : ∀ (r : CellRow) (m : Nat), r.count .yarn ≤ 1 → ∀ j, j + 1 < r.length →
    cpos (r.getD j .yarn) ((compactAt1 r m).getD j 0) < cpos (r.getD (j + 1) .yarn) ((compactAt1 r m).getD (j + 1) 0)
Proof
  | [], _, _, j, hj => by simp at hj
  | [_], _, _, j, hj => by simp at hj
  | o :: o' :: r, m, hc, 0, _ => by
    cases o <;> cases o' <;> simp [compactAt1, cpos] at hc ⊢; omega
  | o :: o' :: r, m, hc, j + 1, hj => by
    have hc' : (o' :: r).count .yarn ≤ 1 :=
      le_trans (List.Sublist.count_le _ (List.sublist_cons_self _ _)) hc
    have hj' : j + 1 < (o' :: r).length := by simpa using hj
    cases o with
    | loop => simpa [compactAt1] using compact_sorted (o' :: r) (m + 1) hc' j hj'
    | yarn => simpa [compactAt1] using compact_sorted (o' :: r) m hc' j hj'

List facts

theorem getD_set_eq {α : Type} (l : List α) (j i : Nat) (v d : α) (hj : j < l.length) :
    (l.set j v).getD i d = if i = j then v else l.getD i d
Proof
:= by
  by_cases h : i = j
  · subst h; simp [List.getD_eq_getElem?_getD, hj]
  · simp [List.getD_eq_getElem?_getD, h, show (j = i) ↔ (i = j) from eq_comm]
theorem sorted_pw {f : Nat → Int} {n : Nat} (h : ∀ j, j + 1 < n → f j < f (j + 1)) :
    ∀ k l, k < l → l < n → f k < f l
Proof
:= by
  intro k l hkl hl
  induction l with
  | zero => omega
  | succ l ih =>
    rcases Nat.lt_succ_iff_lt_or_eq.mp hkl with h1 | h1
    · exact lt_trans (ih h1 (by omega)) (h l hl)
    · subst h1; exact h k hl

The objects other than j are outside the stretch it moves over

theorem cpos_loop (x : Int) : cpos .loop x = 2 * x
Proof
:= rfl
theorem cpos_yarn (x : Int) : cpos .yarn x = 2 * x - 1
Proof
:= rfl
def cp (r : CellRow) (a : List Int) (k : Nat) : Int := cpos (r.getD k .yarn) (a.getD k 0)
theorem far_of_sorted {r : CellRow} {a : List Int} {j : Nat} {v : Int}
    (hs : ∀ k, k + 1 < r.length → cp r a k < cp r a (k + 1)) (hj : j < r.length)
    (hprev : 0 < j → cp r a (j - 1) < v) (hnext : j + 1 < r.length → v < cp r a (j + 1)) :
    ∀ k, k < r.length → k ≠ j → (cp r a k < cp r a j ∧ cp r a k < v) ∨ (cp r a j < cp r a k ∧ v < cp r a k)
Proof
:= by
  have hpw := sorted_pw hs
  intro k hk hkj
  rcases Nat.lt_or_gt_of_ne hkj with h | h
  · left
    refine ⟨hpw k j h hj, ?_⟩
    rcases Nat.lt_or_ge k (j - 1) with h2 | h2
    · exact lt_trans (hpw k (j - 1) h2 (by omega)) (hprev (by omega))
    · have : k = j - 1 := by omega
      subst this; exact hprev (by omega)
  · right
    refine ⟨hpw j k h hk, ?_⟩
    rcases Nat.lt_or_ge (j + 1) k with h2 | h2
    · exact lt_trans (hnext (by omega)) (hpw (j + 1) k h2 hk)
    · have : k = j + 1 := by omega
      subst this; exact hnext hk
theorem sorted_set {r : CellRow} {a : List Int} {j : Nat} {y : Int} (hlen : a.length = r.length)
    (hs : ∀ k, k + 1 < r.length → cp r a k < cp r a (k + 1)) (hj : j < r.length)
    (hprev : 0 < j → cp r a (j - 1) < cpos (r.getD j .yarn) y)
    (hnext : j + 1 < r.length → cpos (r.getD j .yarn) y < cp r a (j + 1)) :
    ∀ k, k + 1 < r.length → cp r (a.set j y) k < cp r (a.set j y) (k + 1)
Proof
:= by
  intro k hk
  have hj' : j < a.length := by omega
  simp only [cp, getD_set_eq a j _ y 0 hj']
  by_cases h1 : k = j
  · subst h1; simpa [cp] using hnext hk
  · by_cases h2 : k + 1 = j
    · subst h2; simpa [cp] using hprev (by omega)
    · simpa [h1, h2, cp] using hs k hk
theorem denote1_single {win : Window} {s s' : State} {op : Op} (h : step1 s op = .ok s')
    (hw : windowOk win s op = true) : denote1 win s [op] = some (s', denoteOp1 win s op)
Proof
:= by
  rw [denote1_cons_ok _ h hw]; simp [denote1]

Walks

theorem set_getD_self {α : Type} (l : List α) (j : Nat) (d : α) (hj : j < l.length) : l.set j (l.getD j d) = l
Proof
:= by
  simp [List.getD_eq_getElem?_getD, List.getElem?_eq_getElem hj]
theorem cp_set_ne {r : CellRow} {a : List Int} {j k : Nat} {v : Int} (hj : j < a.length) (hk : k ≠ j) :
    cp r (a.set j v) k = cp r a k
Proof
:= by
  simp only [cp, getD_set_eq a j k v 0 hj, ite_eq_right hk]
theorem inside_of_named {win : Window} {op : Op} (h : NamedIn3 win op) {z : Int} (hz : z ∈ op.named) :
    win.inside z = true
Proof
:= by
  have := h z hz; simp [Window.inside]; omega

arrange1 as two folds

  • arrange1_def: arrange1 first moves the objects that go right, rightmost first (ar1). Then it moves the objects that go left, leftmost first (ar2).
  • ar1_row, ar1_at and the next lemmas: the rows, prefixes, coordinates and lengths of the folds.
  • char1, char2: the objects that are at their targets.
namespace Knitout
theorem flatMap_single {α β : Type} (f : α → β) (l : List α) : l.flatMap (fun a => [f a]) = l.map f
Proof
:= by
  induction l <;> simp_all [List.flatMap_cons]
theorem moveObject1_ops (c : Comp1) (j : Nat) (dest : Int) :
    (moveObject1 c j dest).ops = c.ops ++
      (if c.row.getD j .yarn = .yarn then
        (if c.at_.getD j 0 < dest then
          (List.range (dest - c.at_.getD j 0).toNat).map (fun k : Nat => Op.miss .R (fN (c.at_.getD j 0 + (k : Int))))
         else (List.range (c.at_.getD j 0 - dest).toNat).map
          (fun k : Nat => Op.miss .L (fN (c.at_.getD j 0 - 1 - (k : Int)))))
      else if c.at_.getD j 0 < dest then
        (List.range (dest - c.at_.getD j 0).toNat).flatMap (fun k : Nat => loopStep (c.at_.getD j 0 + (k : Int)) true)
      else (List.range (c.at_.getD j 0 - dest).toNat).flatMap
        (fun k : Nat => loopStep (c.at_.getD j 0 - (k : Int)) false))
Proof
:= by
  show c.ops ++ _ = _
  congr 1
  unfold yarnTo
  split_ifs <;> simp [flatMap_single, List.flatMap_map]
theorem getD_mem' {l : List Int} {j : Nat} (hj : j < l.length) : l.getD j 0 ∈ l
Proof
:= by
  simp [List.getD_eq_getElem?_getD, List.getElem?_eq_getElem hj, List.getElem_mem]

The two folds of arrange1

def ar1 (c : Comp1) (t : List Int) (c' : Comp1) (j : Nat) : Comp1 :=
  if cp c.row c.at_ j < cp c.row t j then moveObject1 c' j (t.getD j 0) else c'

def ar2 (c : Comp1) (t : List Int) (c' : Comp1) (j : Nat) : Comp1 :=
  if cp c.row t j < cp c.row c.at_ j then moveObject1 c' j (t.getD j 0) else c'
theorem arrange1_def (c : Comp1) (t : List Int) : arrange1 c t =
    if t.length = c.row.length ∧ (List.range (c.row.length - 1)).all (fun j =>
        decide (cpos (c.row.getD j .yarn) (t.getD j 0) < cpos (c.row.getD (j + 1) .yarn) (t.getD (j + 1) 0))) then
      some ((List.range c.row.length).foldl (ar2 c t) ((List.range c.row.length).reverse.foldl (ar1 c t) c))
    else none
Proof
:= rfl
theorem ar1_row (c : Comp1) (t : List Int) (c' : Comp1) (j : Nat) : (ar1 c t c' j).row = c'.row
Proof
:= by
  unfold ar1; split_ifs <;> rfl
theorem ar2_row (c : Comp1) (t : List Int) (c' : Comp1) (j : Nat) : (ar2 c t c' j).row = c'.row
Proof
:= by
  unfold ar2; split_ifs <;> rfl
theorem ar1_prefix (c : Comp1) (t : List Int) (c' : Comp1) (j : Nat) : c'.ops <+: (ar1 c t c' j).ops
Proof
:= by
  unfold ar1; split_ifs
  · rw [moveObject1_ops]; exact List.prefix_append _ _
  · exact List.prefix_refl _
theorem ar2_prefix (c : Comp1) (t : List Int) (c' : Comp1) (j : Nat) : c'.ops <+: (ar2 c t c' j).ops
Proof
:= by
  unfold ar2; split_ifs
  · rw [moveObject1_ops]; exact List.prefix_append _ _
  · exact List.prefix_refl _
theorem ar1_at (c : Comp1) (t : List Int) (c' : Comp1) (j : Nat) : (ar1 c t c' j).at_ =
    if cp c.row c.at_ j < cp c.row t j then c'.at_.set j (t.getD j 0) else c'.at_
Proof
:= by
  unfold ar1; split_ifs <;> rfl
theorem ar2_at (c : Comp1) (t : List Int) (c' : Comp1) (j : Nat) : (ar2 c t c' j).at_ =
    if cp c.row t j < cp c.row c.at_ j then c'.at_.set j (t.getD j 0) else c'.at_
Proof
:= by
  unfold ar2; split_ifs <;> rfl
theorem foldl_row_prefix (f : Comp1 → Nat → Comp1) (hf : ∀ c' j, (f c' j).row = c'.row ∧ c'.ops <+: (f c' j).ops) :
    ∀ (L : List Nat) (c' : Comp1), (L.foldl f c').row = c'.row ∧ c'.ops <+: (L.foldl f c').ops
Proof
  | [], c' => ⟨rfl, List.prefix_refl _⟩
  | j :: L, c' => by
    obtain ⟨h1, h2⟩ := foldl_row_prefix f hf L (f c' j)
    exact ⟨h1.trans (hf c' j).1, (hf c' j).2.trans h2⟩
theorem foldl_length (f : Comp1 → Nat → Comp1) (hf : ∀ c' j, (f c' j).at_.length = c'.at_.length) :
    ∀ (L : List Nat) (c' : Comp1), (L.foldl f c').at_.length = c'.at_.length
Proof
  | [], _ => rfl
  | j :: L, c' => (foldl_length f hf L (f c' j)).trans (hf c' j)
theorem ar1_length (c : Comp1) (t : List Int) (c' : Comp1) (j : Nat) : (ar1 c t c' j).at_.length = c'.at_.length
Proof
:= by
  rw [ar1_at]; split_ifs <;> simp
theorem ar2_length (c : Comp1) (t : List Int) (c' : Comp1) (j : Nat) : (ar2 c t c' j).at_.length = c'.at_.length
Proof
:= by
  rw [ar2_at]; split_ifs <;> simp
def char1 (c : Comp1) (t : List Int) (c' : Comp1) (m : Nat) : Prop :=
  ∀ i < c.row.length, c'.at_.getD i 0 = if m ≤ i ∧ cp c.row c.at_ i < cp c.row t i then t.getD i 0 else c.at_.getD i 0

def char2 (c : Comp1) (t : List Int) (c' : Comp1) (m : Nat) : Prop :=
  ∀ i < c.row.length, c'.at_.getD i 0 =
    if cp c.row c.at_ i < cp c.row t i ∨ (i < m ∧ cp c.row t i < cp c.row c.at_ i) then t.getD i 0 else c.at_.getD i 0
theorem char_step1 {c : Comp1} {t : List Int} {c' : Comp1} {m : Nat} (hlen : c'.at_.length = c.row.length)
    (hm : m < c.row.length) (hc : char1 c t c' (m + 1)) : char1 c t (ar1 c t c' m) m
Proof
:= by
  intro i hi
  rw [ar1_at]
  have hj : m < c'.at_.length := by omega
  have hiff : i ≠ m → ∀ Q : Prop, ((m + 1 ≤ i ∧ Q) ↔ (m ≤ i ∧ Q)) := fun h Q =>
    ⟨fun h' => ⟨by omega, h'.2⟩, fun h' => ⟨by omega, h'.2⟩⟩
  by_cases hP : cp c.row c.at_ m < cp c.row t m
  · rw [ite_eq_left hP, getD_set_eq _ _ _ _ _ hj]
    by_cases him : i = m
    · subst him; rw [ite_eq_left rfl, ite_eq_left ⟨le_refl _, hP⟩]
    · rw [ite_eq_right him, hc i hi]; exact if_congr (hiff him _) rfl rfl
  · rw [ite_eq_right hP, hc i hi]
    by_cases him : i = m
    · subst him; rw [ite_eq_right (fun h => by omega), ite_eq_right (fun h => hP h.2)]
    · exact if_congr (hiff him _) rfl rfl
theorem char_step2 {c : Comp1} {t : List Int} {c' : Comp1} {m : Nat} (hlen : c'.at_.length = c.row.length)
    (hm : m < c.row.length) (hc : char2 c t c' m) : char2 c t (ar2 c t c' m) (m + 1)
Proof
:= by
  intro i hi
  rw [ar2_at]
  have hj : m < c'.at_.length := by omega
  have hiff : i ≠ m → ∀ P Q : Prop, ((P ∨ (i < m ∧ Q)) ↔ (P ∨ (i < m + 1 ∧ Q))) := fun h P Q =>
    ⟨fun h' => h'.imp_right (fun h'' => ⟨by omega, h''.2⟩), fun h' => h'.imp_right (fun h'' => ⟨by omega, h''.2⟩)⟩
  by_cases hP : cp c.row t m < cp c.row c.at_ m
  · rw [ite_eq_left hP, getD_set_eq _ _ _ _ _ hj]
    by_cases him : i = m
    · subst him; rw [ite_eq_left rfl, ite_eq_left (Or.inr ⟨by omega, hP⟩)]
    · rw [ite_eq_right him, hc i hi]; exact if_congr (hiff him _ _) rfl rfl
  · rw [ite_eq_right hP, hc i hi]
    by_cases him : i = m
    · subst him
      exact if_congr ⟨fun h' => h'.imp_right (fun h'' => absurd h''.2 hP),
        fun h' => h'.imp_right (fun h'' => absurd h''.2 hP)⟩ rfl rfl
    · exact if_congr (hiff him _ _) rfl rfl
theorem drop_trans {a b d : List Op} (h1 : a <+: b) (h2 : b <+: d) :
    d.drop a.length = b.drop a.length ++ d.drop b.length
Proof
:= by
  obtain ⟨x, rfl⟩ := h1; obtain ⟨y, rfl⟩ := h2; simp [List.append_assoc]
theorem fits_set {win : Window} {c' : Comp1} {j : Nat} {d : Int} (hF : Fits1 win c') (hj : j < c'.at_.length)
    (hd : d = c'.at_.getD j 0 ∨ (win.lo + 2 ≤ d ∧ d + 2 < win.lo + win.w)) :
    ∀ x ∈ c'.at_.set j d, win.lo + 2 ≤ x ∧ x + 2 < win.lo + win.w
Proof
:= by
  intro x hx
  rcases List.mem_or_eq_of_mem_set hx with h | h
  · exact hF x h
  · subst h
    rcases hd with h | h
    · rw [h]; exact hF _ (getD_mem' hj)
    · exact h
theorem sorted_of_all {c : Comp1} {t : List Int}
    (h : (List.range (c.row.length - 1)).all (fun j =>
        decide (cpos (c.row.getD j .yarn) (t.getD j 0) < cpos (c.row.getD (j + 1) .yarn) (t.getD (j + 1) 0))) = true) :
    ∀ j, j + 1 < c.row.length → cp c.row t j < cp c.row t (j + 1)
Proof
:= by
  intro j hj
  have := List.all_eq_true.mp h j (List.mem_range.mpr (by omega))
  simpa [cp] using this

When arrange1 succeeds

  • ArrangeTotal' S: from a state with one coordinate for each object, arrange1 to the canonical layout (and to the compact layout) succeeds.
  • arrangeTotal'_two proves it for spacing 2, from arrange1_total.
namespace Knitout
def ArrangeTotal' (S : Nat) : Prop :=
  ∀ c : Comp1, c.row.count .yarn = 1 → c.at_.length = c.row.length →
    (∃ c', arrange1 c (canonical S c.row.length) = some c' ∧ c'.row = c.row ∧
      c'.at_ = canonical S c.row.length ∧ c.ops <+: c'.ops) ∧
    (∃ c', arrange1 c (compactAt1 c.row 0) = some c' ∧ c'.row = c.row ∧ c'.at_ = compactAt1 c.row 0 ∧ c.ops <+: c'.ops)
theorem pfold1 {c : Comp1} {t : List Int} :
    ∀ m, m ≤ c.row.length → ∀ c', c'.at_.length = c.row.length → char1 c t c' m →
      char1 c t ((List.range m).reverse.foldl (ar1 c t) c') 0
Proof
  | 0, _, c', _, h => by simpa using h
  | m + 1, hm, c', hl, h => by
    have e : (List.range (m + 1)).reverse = m :: (List.range m).reverse := by simp [List.range_succ]
    rw [e, List.foldl_cons]
    exact pfold1 m (by omega) _ ((ar1_length c t c' m).trans hl) (char_step1 hl (by omega) h)
theorem pfold2 {c : Comp1} {t : List Int} :
    ∀ k s, s + k = c.row.length → ∀ c', c'.at_.length = c.row.length → char2 c t c' s →
      char2 c t ((List.range' s k).foldl (ar2 c t) c') c.row.length
Proof
  | 0, s, hs, c', _, h => by simp only [List.range'_zero, List.foldl_nil]; rw [← hs]; simpa using h
  | k + 1, s, hs, c', hl, h => by
    rw [List.range'_succ, List.foldl_cons]
    exact pfold2 k (s + 1) (by omega) _ ((ar2_length c t c' s).trans hl) (char_step2 hl (by omega) h)
theorem cpos_inj {o : CellObj} {x y : Int} (h : cpos o x = cpos o y) : x = y
Proof
:= by
  cases o <;> simp [cpos] at h <;> omega
theorem getD_eq_getElem' {l : List Int} {i : Nat} (h : i < l.length) : l.getD i 0 = l[i]
Proof
:= by
  simp [List.getD_eq_getElem?_getD, List.getElem?_eq_getElem h]
theorem arrange1_total (c : Comp1) (t : List Int) (hl : c.at_.length = c.row.length) (htl : t.length = c.row.length)
    (hs : ∀ j, j + 1 < c.row.length → cp c.row t j < cp c.row t (j + 1)) :
    ∃ c', arrange1 c t = some c' ∧ c'.row = c.row ∧ c'.at_ = t ∧ c.ops <+: c'.ops
Proof
:= by
  have hall : (List.range (c.row.length - 1)).all (fun j =>
      decide (cpos (c.row.getD j .yarn) (t.getD j 0) < cpos (c.row.getD (j + 1) .yarn) (t.getD (j + 1) 0))) = true :=
    List.all_eq_true.mpr (fun j hj => decide_eq_true (hs j (by have := List.mem_range.mp hj; omega)))
  rw [arrange1_def, ite_eq_left ⟨htl, hall⟩]
  set c1 := (List.range c.row.length).reverse.foldl (ar1 c t) c with hc1
  have hp1 := foldl_row_prefix (ar1 c t) (fun c' j => ⟨ar1_row c t c' j, ar1_prefix c t c' j⟩)
    (List.range c.row.length).reverse c
  have hl1 : c1.at_.length = c.row.length := (foldl_length _ (ar1_length c t) _ _).trans hl
  have hch1 := pfold1 (t := t) c.row.length (le_refl _) c hl (fun i hi => by rw [ite_eq_right (fun h => by omega)])
  have hch2 : char2 c t c1 0 := fun i hi => by
    rw [hch1 i hi]
    by_cases hP : cp c.row c.at_ i < cp c.row t i
    · rw [ite_eq_left ⟨Nat.zero_le _, hP⟩, ite_eq_left (Or.inl hP)]
    · rw [ite_eq_right (fun h => hP h.2), ite_eq_right (fun h => h.elim hP (fun h' => by omega))]
  have hp2 := foldl_row_prefix (ar2 c t) (fun c' j => ⟨ar2_row c t c' j, ar2_prefix c t c' j⟩)
    (List.range c.row.length) c1
  have hl2 := (foldl_length _ (ar2_length c t) (List.range c.row.length) c1).trans hl1
  rw [List.range_eq_range'] at hp2 hl2 ⊢
  have hch := pfold2 c.row.length 0 (by omega) c1 hl1 hch2
  refine ⟨_, rfl, hp2.1.trans hp1.1, ?_, hp1.2.trans hp2.2⟩
  apply List.ext_getElem (by rw [hl2, htl])
  intro i h1 h2
  have hi : i < c.row.length := by omega
  rw [← getD_eq_getElem' h1, ← getD_eq_getElem' h2, hch i hi]
  split_ifs with hP
  · rfl
  · exact cpos_inj (show cp c.row c.at_ i = cp c.row t i by
      rcases lt_trichotomy (cp c.row c.at_ i) (cp c.row t i) with h | h | h
      · exact absurd (Or.inl h) hP
      · exact h
      · exact absurd (Or.inr ⟨hi, h⟩) hP)
theorem canonical_getD (S n j : Nat) (hj : j < n) : (canonical S n).getD j 0 = (S : Int) + 1 + S * j
Proof
:= by
  simp [canonical, flatMap_single, List.getD_eq_getElem?_getD, hj]
theorem arrangeTotal'_two : ArrangeTotal' 2
Proof
:= by
  intro c hy hl
  refine ⟨arrange1_total c _ hl (by simp [canonical]) (fun j hj => ?_),
    arrange1_total c _ hl (length_compactAt1 _ _) (fun j hj => compact_sorted c.row 0 (by omega) j hj)⟩
  simp only [cp, canonical_getD 2 c.row.length j (by omega),
    canonical_getD 2 c.row.length (j + 1) hj]
  cases c.row.getD j .yarn <;> cases c.row.getD (j + 1) .yarn <;> simp [cpos] <;> omega

The length of the canonical layout

namespace Knitout
theorem length_canonical (S n : Nat) : (canonical S n).length = n
Proof
:= by
  simp [canonical, flatMap_single]

The canonical layout

theorem bind_coe_length : ∀ (l : List Nat), (l >>= fun a => (pure (a : Int) : List Int)).length = l.length
Proof
  | [] => rfl
  | x :: xs => by
    have := bind_coe_length xs
    show (xs >>= fun a => (pure (a : Int) : List Int)).length + 1 = xs.length + 1
    omega
theorem bind_coe_getD : ∀ (l : List Nat) (j : Nat), j < l.length →
    (l >>= fun a => (pure (a : Int) : List Int)).getD j 0 = ((l.getD j 0 : Nat) : Int)
Proof
  | [], _, h => by simp at h
  | x :: xs, 0, _ => rfl
  | x :: xs, j + 1, h => by
    have := bind_coe_getD xs j (by simp at h; omega)
    exact this
theorem canonical_getD_two {n j : Nat} (h : j < n) : (canonical 2 n).getD j 0 = 3 + 2 * (j : Int)
Proof
:= by
  unfold canonical
  rw [List.getD_eq_getElem?_getD, List.getElem?_map]
  have h2 := bind_coe_getD (List.range n) j (by simpa using h)
  have hl := bind_coe_length (List.range n)
  rw [List.getD_eq_getElem?_getD] at h2
  cases e : (List.range n >>= fun a => (pure (a : Int) : List Int))[j]? with
  | none => rw [List.getElem?_eq_none_iff, hl, List.length_range] at e; omega
  | some v => rw [e] at h2; simp at h2 ⊢; simp [h] at h2; omega
theorem canonical_length (n : Nat) : (canonical 2 n).length = n
Proof
:= by
  unfold canonical; rw [List.length_map, bind_coe_length, List.length_range]

One yarn

theorem two_yarns1 {r : CellRow} {i j : Nat} (hij : i < j) (hj : j < r.length) (hi : r[i]'(by omega) = .yarn)
    (hj' : r[j] = .yarn) : 2 ≤ r.count .yarn
Proof
:= by
  have e : r = r.take j ++ r.drop j := (List.take_append_drop j r).symm
  have h1 : CellObj.yarn ∈ r.take j := by
    rw [List.mem_iff_getElem]; exact ⟨i, by simp; omega, by simp [hi]⟩
  have h2 : CellObj.yarn ∈ r.drop j := by
    rw [List.mem_iff_getElem]; exact ⟨0, by simp; omega, by simp [hj']⟩
  have := List.count_append (a := CellObj.yarn) (l₁ := r.take j) (l₂ := r.drop j)
  rw [← e] at this
  have c1 := List.count_pos_iff.mpr h1
  have c2 := List.count_pos_iff.mpr h2
  omega
theorem getD_eq_yarn_iff1 {r : CellRow} (hy : r.count .yarn = 1) {j : Nat} (hj : j < r.length) :
    r.getD j .yarn = .yarn ↔ j = cellYarnIdx r
Proof
:= by
  have hmem : CellObj.yarn ∈ r := List.count_pos_iff.mp (by omega)
  have hlt : cellYarnIdx r < r.length := List.idxOf_lt_length_iff.mpr hmem
  have hget : r[cellYarnIdx r] = .yarn := List.getElem_idxOf hlt
  constructor
  · intro h
    have h' : r[j] = .yarn := by simpa [List.getD_eq_getElem?_getD, hj] using h
    by_contra hne
    rcases Nat.lt_or_gt_of_ne hne with hlt' | hgt
    · have := two_yarns1 hlt' hlt h' hget; omega
    · have := two_yarns1 hgt hj hget h'; omega
  · rintro rfl; simp [List.getD_eq_getElem?_getD, hlt, hget]

Front counts of the canonical layout

theorem getD_of_lt {α : Type} {l : List α} {i : Nat} (h : i < l.length) (d : α) : l.getD i d = l[i]
Proof
:= by
  simp [List.getD_eq_getElem?_getD, h]
theorem getD_of_ge {α : Type} {l : List α} {i : Nat} (h : l.length ≤ i) (d : α) : l.getD i d = d
Proof
:= by
  simp [List.getD_eq_getElem?_getD, List.getElem?_eq_none h]

Strands before a position

theorem sb_lo (win : Window) (s : State) : strandsBefore win s win.lo = 0
Proof
:= by
  simp [strandsBefore, rowOf1, points, cellRowWidth]
theorem sb_succ (win : Window) (s : State) {i : Int} (h : win.lo ≤ i) :
    strandsBefore win s (i + 1) = strandsBefore win s i + segW s i
Proof
:= by
  unfold strandsBefore
  have e : (i + 1 - win.lo).toNat = (i - win.lo).toNat + 1 := by omega
  rw [e, show cellRowWidth (rowOf1 s win.lo ((i - win.lo).toNat + 1)) = W s win.lo ((i - win.lo).toNat + 1) from rfl,
    W_succ]
  have e2 : win.lo + ((i - win.lo).toNat : Int) = i := by omega
  rw [e2]; rfl
theorem sb_add (win : Window) (s : State) {i : Int} (h : win.lo ≤ i) :
    ∀ k : Nat, strandsBefore win s (i + k) = strandsBefore win s i + ∑ t ∈ Finset.range k, segW s (i + t)
Proof
  | 0 => by simp
  | k + 1 => by
    have := sb_succ win s (i := i + k) (by omega)
    rw [Finset.sum_range_succ, ← Nat.add_assoc, ← sb_add win s h k, ← this]
    congr 1; push_cast; omega
theorem sb_congr (win : Window) {s t : State} :
    ∀ (k : Nat), (∀ p : Int, win.lo ≤ p → p < win.lo + k → segW t p = segW s p) →
      strandsBefore win t (win.lo + k) = strandsBefore win s (win.lo + k)
Proof
  | 0, _ => by simp [sb_lo]
  | k + 1, h => by
    have e : win.lo + ((k + 1 : Nat) : Int) = win.lo + k + 1 := by push_cast; omega
    rw [e, sb_succ win t (by omega), sb_succ win s (by omega), sb_congr win k (fun p h1 h2 => h p h1 (by omega)),
      h _ (by omega) (by omega)]
theorem sb_congr' (win : Window) {s t : State} {i : Int} (hi : win.lo ≤ i)
    (h : ∀ p : Int, win.lo ≤ p → p < i → segW t p = segW s p) : strandsBefore win t i = strandsBefore win s i
Proof
:= by
  have := sb_congr win (s := s) (t := t) (i - win.lo).toNat (fun p h1 h2 => h p h1 (by omega))
  rwa [show win.lo + ((i - win.lo).toNat : Int) = i by omega] at this

spliceL: positions, front counts, order

theorem length_spliceL {α : Type} (l : List α) (f len : Nat) (N : List α) (hf : f + len ≤ l.length) :
    (spliceL l f len N).length = l.length - len + N.length
Proof
:= by
  simp [spliceL]; omega
theorem getD_spliceL {α : Type} (l : List α) (f len : Nat) (N : List α) (d : α) (hf : f + len ≤ l.length) (j : Nat) :
    (spliceL l f len N).getD j d =
      if j < f then l.getD j d else if j < f + N.length then N.getD (j - f) d else l.getD (j - N.length + len) d
Proof
:= by
  unfold spliceL
  simp only [List.getD_eq_getElem?_getD]
  have htf : (l.take f).length = f := by simp; omega
  split_ifs with h1 h2
  · rw [List.append_assoc, List.getElem?_append_left (by omega), List.getElem?_take_of_lt h1]
  · rw [List.getElem?_append_left (by simp; omega), List.getElem?_append_right (by omega), htf]
  · rw [List.getElem?_append_right (by simp; omega), List.getElem?_drop]
    simp only [List.length_append, htf]
    congr 2; omega

Running one instruction

theorem denote1_single_op {win : Window} {s : State} {op : Op} (h : validCrate s op) (hw : windowOk win s op = true) :
    denote1 win s [op] = some (apply s op, denoteOp1 win s op)
Proof
:= by
  have := denote1_cons_ok (win := win) [] (step1_ok.mpr ⟨h, rfl⟩) hw
  rw [this]; simp [denote1]
theorem inside_of {win : Window} {z : Int} (h1 : win.lo + 1 ≤ z) (h2 : z + 2 ≤ win.lo + win.w) :
    win.inside z = true
Proof
:= by
  simp [Window.inside]; omega
theorem seg1_one {α : Type} (l : List α) {f : Nat} (h : f < l.length) (d : α) : (l.drop f).take 1 = [l.getD f d]
Proof
:= by
  rw [List.drop_eq_getElem_cons h, getD_of_lt h]; rfl
theorem tuck_valid {st : State} {d : Dir} {cc : Int} (h : st.carrier = arrivesFrom d cc) :
    validCrate st (.tuck d (fN cc))
Proof
:= by
  simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, fN, slot, h]

Drop

theorem eraseIdx_spliceL {α : Type} (l : List α) (a : Nat) : l.eraseIdx a = spliceL l a 1 []
Proof
:= by
  simp [spliceL, List.eraseIdx_eq_take_drop_succ]

Split

theorem denote1_cons_v {win : Window} {s : State} {op : Op} (ops : List Op) (h : validCrate s op)
    (hw : windowOk win s op = true) :
    denote1 win s (op :: ops) = (denote1 win (apply s op) ops).map (fun p => (p.1, denoteOp1 win s op ++ p.2))
Proof
:=
  denote1_cons_ok ops (step1_ok.mpr ⟨h, rfl⟩) hw
theorem seg1_two {α : Type} (l : List α) {f : Nat} (h : f + 1 < l.length) (d : α) :
    (l.drop f).take 2 = [l.getD f d, l.getD (f + 1) d]
Proof
:= by
  rw [List.drop_eq_getElem_cons (by omega), List.drop_eq_getElem_cons h, getD_of_lt (by omega), getD_of_lt h]; rfl

The knit instructions on a laid-out machine

  • loopStep_onto: loopStep n false onto a needle that can already hold loops is accepted and draws nothing. The moved loops go on top.
  • missL_walk, missR_walk: the carrier past empty positions draws nothing.
  • knit_block: the knit instructions knitOps1 from a needle with k loops draw exactly one knit box, at the strands left of the position of the needle. For the back bed, knitOps1 adds the transfers across and back.
namespace Knitout
namespace Knit
theorem loopStep_onto (win : Window) (st : State) (n : Int) (hr : st.rack = 0)
    (hb : ∀ j, st.stk ⟨.b, j⟩ = []) (hc : st.carrier ≠ n)
    (hin : win.inside n = true) (hin1 : win.inside (n - 1) = true) :
    ∃ st', denote1 win st (loopStep n false) = some (st', []) ∧ st'.rack = 0 ∧ st'.carrier = st.carrier ∧
      ∀ q, st'.stk q = if q = ⟨.f, n - 1⟩ then st.stk ⟨.f, n⟩ ++ st.stk ⟨.f, n - 1⟩
        else if q = ⟨.f, n⟩ then [] else st.stk q
Proof
:= by
  set s1 := apply st (.xfer (fN n) (bN n)) with hs1
  set s2 := apply s1 (.rack (-1)) with hs2
  set s3 := apply s2 (.xfer (bN n) (fN (n - 1))) with hs3
  set s4 := apply s3 (.rack 0) with hs4
  have k1 : ∀ q, s1.stk q = if q = ⟨.b, n⟩ then (st.stk ⟨.f, n⟩).reverse else if q = ⟨.f, n⟩ then [] else st.stk q := by
    intro q
    simp only [hs1, apply, upd_apply, xferStack, fN, bN, hb, List.append_nil]
  have k3 : ∀ q, s3.stk q = if q = ⟨.f, n - 1⟩ then st.stk ⟨.f, n⟩ ++ st.stk ⟨.f, n - 1⟩
      else if q = ⟨.f, n⟩ then [] else st.stk q := by
    intro q
    have e2 : ∀ q, s2.stk q = s1.stk q := fun _ => rfl
    show Function.update (Function.update s2.stk (bN n) []) (fN (n - 1))
      (xferStack (s2.stk (bN n)) (s2.stk (fN (n - 1)))) q = _
    simp only [upd_apply, xferStack, e2, k1, fN, bN]
    by_cases h1 : q = ⟨.f, n - 1⟩
    · subst h1; simp
    · by_cases h2 : q = ⟨.b, n⟩
      · subst h2; simp [hb]
      · simp [h1, h2]
  have h1 : step1 st (.xfer (fN n) (bN n)) = .ok s1 :=
    step1_ok.mpr ⟨by simp [validCrate, crateRefusal1, linRefusal, aligned, slot, erase, hr, crateExtra1, fN, bN], rfl⟩
  have w1 : windowOk win st (.xfer (fN n) (bN n)) = true := by simp [windowOk, slot, hr, fN, bN, hin]
  have h2 : step1 s1 (.rack (-1)) = .ok s2 :=
    step1_ok.mpr ⟨by simp [validCrate, crateRefusal1, linRefusal, erase, hs1, apply, hr, crateExtra1], rfl⟩
  have w2 : windowOk win s1 (.rack (-1)) = true := by
    simp only [windowOk, List.all_eq_true, List.mem_range, Bool.or_eq_true, List.isEmpty_iff]
    intro k _
    rw [k1]
    by_cases hk : win.lo + (k : Int) = n
    · right; rw [hk]; exact hin1
    · left; simp [hk, hb]
  have d2 : denoteOp1 win s1 (.rack (-1)) = [] := by
    apply rackBraid_nil
    intro k _
    have hr1 : s1.rack = 0 := by simp [hs1, apply, hr]
    rw [ite_eq_left (by rw [hr1]; omega)]
    by_cases hk : win.lo + (k : Int) = n
    · left
      rw [hk]
      simp only [yarnAt, frontAt, k1]
      simp [hs1, apply, hc]
    · right; simp only [backAt, hr1, sub_zero, k1]; simp [hk, hb]
  have em : n + -1 = n - 1 := by omega
  have h3 : step1 s2 (.xfer (bN n) (fN (n - 1))) = .ok s3 :=
    step1_ok.mpr ⟨by simp [validCrate, crateRefusal1, linRefusal, aligned, slot, erase, hs2, apply, crateExtra1, fN, bN, em], rfl⟩
  have w3 : windowOk win s2 (.xfer (bN n) (fN (n - 1))) = true := by
    simp [windowOk, slot, hs2, apply, fN, bN, hin1, em]
  have h4 : step1 s3 (.rack 0) = .ok s4 :=
    step1_ok.mpr ⟨by simp [validCrate, crateRefusal1, linRefusal, erase, hs3, hs2, apply, crateExtra1], rfl⟩
  have w4 : windowOk win s3 (.rack 0) = true := by
    simp only [windowOk, List.all_eq_true, List.mem_range, Bool.or_eq_true, List.isEmpty_iff]
    intro k _; left; rw [k3]; simp [hb]
  have d4 : denoteOp1 win s3 (.rack 0) = [] := by
    apply rackBraid_nil
    intro k _
    have hr3 : s3.rack = -1 := by simp [hs3, hs2, apply]
    rw [ite_eq_right (by rw [hr3]; omega)]
    left; simp only [k3]; simp [hb]
  refine ⟨s4, ?_, by simp [hs4, apply], by simp [hs4, hs3, hs2, hs1, apply], fun q => by
    rw [show s4.stk q = s3.stk q from rfl, k3]⟩
  simp only [loopStep, Bool.false_eq_true, ite_false]
  rw [denote1_cons_ok _ h1 w1, denote1_cons_ok _ h2 w2, denote1_cons_ok _ h3 w3, denote1_cons_ok _ h4 w4, d2, d4]
  simp [denote1, denoteOp1]
theorem missL_walk (win : Window) (s : State) (x : Int) (hr : s.rack = 0) (hc : s.carrier = x)
    (hb : ∀ j, s.stk ⟨.b, j⟩ = []) :
    ∀ m : Nat, (∀ t : Nat, t < m → s.stk ⟨.f, x - 1 - t⟩ = [] ∧ win.inside (x - 1 - t) = true) →
      denote1 win s ((List.range m).map fun t : Nat => Op.miss .L (fN (x - 1 - t))) =
        some ({ s with carrier
Proof
:= x - m }, [])
  | 0, _ => by cases s; simp [denote1] at hc ⊢; omega
  | m + 1, h => by
    rw [List.range_succ, List.map_append, List.map_cons, List.map_nil]
    have ih := missL_walk win s x hr hc hb m (fun t ht => h t (by omega))
    obtain ⟨hf, hi⟩ := h m (Nat.lt_succ_self m)
    set s1 : State := { s with carrier := x - m }
    have v : validCrate s1 (.miss .L (fN (x - 1 - m))) := by
      have hc1 : s1.carrier = x - m := rfl
      have hr1 : s1.rack = 0 := hr
      simp only [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, fN, slot, arrivesFrom, hc1, hr1]
      rw [ite_eq_right (by omega)]
    have w : windowOk win s1 (.miss .L (fN (x - 1 - m))) = true := by simp only [windowOk, slot, fN]; exact hi
    have dd : denoteOp1 win s1 (.miss .L (fN (x - 1 - m))) = [] :=
      miss_free _ _ _ _ (by simp [frontAt, slot, fN, s1, hf]) (by simp [backAt, slot, fN, s1, hb])
    have := denote1_append win s _ _ s1 _ [] _ ih (denote1_single_op v w)
    rw [this, dd]
    congr 2
    simp [apply, s1, slot, fN, leavesTo, hr]; omega
theorem missR_walk (win : Window) (s : State) (x : Int) (hr : s.rack = 0) (hc : s.carrier = x)
    (hb : ∀ j, s.stk ⟨.b, j⟩ = []) :
    ∀ m : Nat, (∀ t : Nat, t < m → s.stk ⟨.f, x + t⟩ = [] ∧ win.inside (x + t) = true) →
      denote1 win s ((List.range m).map fun t : Nat => Op.miss .R (fN (x + t))) =
        some ({ s with carrier
Proof
:= x + m }, [])
  | 0, _ => by cases s; simp [denote1] at hc ⊢; omega
  | m + 1, h => by
    rw [List.range_succ, List.map_append, List.map_cons, List.map_nil]
    have ih := missR_walk win s x hr hc hb m (fun t ht => h t (by omega))
    obtain ⟨hf, hi⟩ := h m (Nat.lt_succ_self m)
    set s1 : State := { s with carrier := x + m }
    have v : validCrate s1 (.miss .R (fN (x + m))) := by
      have hc1 : s1.carrier = x + m := rfl
      have hr1 : s1.rack = 0 := hr
      simp only [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, fN, slot, arrivesFrom, hc1, hr1]
      rw [ite_eq_right (by omega)]
    have w : windowOk win s1 (.miss .R (fN (x + m))) = true := by simp only [windowOk, slot, fN]; exact hi
    have dd : denoteOp1 win s1 (.miss .R (fN (x + m))) = [] :=
      miss_free _ _ _ _ (by simp [frontAt, slot, fN, s1, hf]) (by simp [backAt, slot, fN, s1, hb])
    have := denote1_append win s _ _ s1 _ [] _ ih (denote1_single_op v w)
    rw [this, dd]
    congr 2
    simp [apply, s1, slot, fN, leavesTo, hr]; omega
def knitOps1 (d : Dir) (bd : Bed) (c1 : Int) : List Op :=
  (if bd = .b then [Op.xfer (fN c1) (bN c1)] else []) ++ [Op.knit d ⟨bd, c1⟩] ++
    (if bd = .b then [Op.xfer (bN c1) (fN c1)] else [])
theorem knit_block (win : Window) (s : State) (d : Dir) (bd : Bed) (c1 : Int) (k : Nat) (hr : s.rack = 0)
    (hb : ∀ j, s.stk ⟨.b, j⟩ = []) (hcar : s.carrier = arrivesFrom d c1) (hk : (s.stk ⟨.f, c1⟩).length = k)
    (hk0 : 0 < k) (hin : win.inside c1 = true) (hlo : win.lo ≤ c1) :
    ∃ s', denote1 win s (knitOps1 d bd c1) = some (s', [.box (.knit d bd k) (strandsBefore win s c1)]) ∧
      s'.rack = 0 ∧ (∀ j, s'.stk ⟨.b, j⟩ = []) ∧ s'.carrier = leavesTo d c1 ∧ (s'.stk ⟨.f, c1⟩).length = 1 ∧
      ∀ i, i ≠ c1 → s'.stk ⟨.f, i⟩ = s.stk ⟨.f, i⟩
Proof
:= by
  have hsb1 : d = .L → strandsBefore win s (c1 + 1) = strandsBefore win s c1 + 2 * k := by
    intro hd; subst hd
    rw [sb_succ win s hlo, segW_eq]
    simp only [yarnAt, frontAt, backAt, hr, hb, hk, sub_zero]
    simp [arrivesFrom] at hcar; simp [hcar]
  have hne : s.stk ⟨.f, c1⟩ ≠ [] := by intro h; rw [h] at hk; simp at hk; omega
  cases bd with
  | f =>
    have v : validCrate s (.knit d ⟨.f, c1⟩) := by
      cases d <;> simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, slot, hcar, hne]
    have w : windowOk win s (.knit d ⟨.f, c1⟩) = true := by simp only [windowOk, slot]; exact hin
    refine ⟨apply s (.knit d ⟨.f, c1⟩), ?_, by simp [apply, hr], by intro j; simp [apply, hb],
      by simp [apply, slot], by simp [apply], by intro i hi; simp [apply, hi]⟩
    simp only [knitOps1, reduceCtorEq, ite_false, List.nil_append, List.append_nil]
    rw [denote1_single_op v w]
    congr 1
    have hK : backAt s c1 = 0 := by simp [backAt, hb]
    have hF : frontAt s c1 = 2 * k := by simp [frontAt, hk]
    cases d
    · simp only [denoteOp1, slot, arrivesFrom, hK, hk, swapB_nil (Or.inr rfl), List.append_nil]
    · simp only [denoteOp1, slot, arrivesFrom, hK, hF, hk, hsb1 rfl, swapB_nil (Or.inl rfl), List.nil_append,
        Nat.sub_zero, Nat.add_sub_cancel]
  | b =>
    set sX := apply s (.xfer (fN c1) (bN c1)) with hsX
    set sK := apply sX (.knit d ⟨.b, c1⟩) with hsK
    have kX : ∀ q, sX.stk q = if q = ⟨.b, c1⟩ then (s.stk ⟨.f, c1⟩).reverse else if q = ⟨.f, c1⟩ then []
        else s.stk q := by
      intro q; simp only [hsX, apply, upd_apply, xferStack, hb, List.append_nil, fN, bN]
    have kK : ∀ q, sK.stk q = if q = ⟨.b, c1⟩ then [sX.fresh] else if q = ⟨.f, c1⟩ then [] else s.stk q := by
      intro q; simp only [hsK, apply, upd_apply, kX]
      by_cases h : q = ⟨.b, c1⟩
      · subst h; simp
      · simp [h]
    have eXr : sX.rack = 0 := hr
    have eXc : sX.carrier = arrivesFrom d c1 := hcar
    have eKr : sK.rack = 0 := hr
    have vX : validCrate s (.xfer (fN c1) (bN c1)) := by
      simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, slot, aligned, hr, fN, bN]
    have wX : windowOk win s (.xfer (fN c1) (bN c1)) = true := by
      simp only [windowOk, slot, hr, fN, bN, Int.add_zero, Bool.and_self]; exact hin
    have vK : validCrate sX (.knit d ⟨.b, c1⟩) := by
      cases d <;> simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, slot, eXc, eXr, kX, hne, arrivesFrom]
    have wK : windowOk win sX (.knit d ⟨.b, c1⟩) = true := by
      simp only [windowOk, slot, eXr, Int.add_zero]; exact hin
    have vB : validCrate sK (.xfer (bN c1) (fN c1)) := by
      simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, slot, aligned, eKr, fN, bN]
    have wB : windowOk win sK (.xfer (bN c1) (fN c1)) = true := by
      simp only [windowOk, slot, eKr, fN, bN, Int.add_zero, Bool.and_self]; exact hin
    refine ⟨apply sK (.xfer (bN c1) (fN c1)), ?_, by simp [apply, eKr], ?_, ?_, ?_, ?_⟩
    · simp only [knitOps1, ite_true, List.cons_append, List.nil_append]
      rw [denote1_cons_v _ vX wX, denote1_cons_v _ vK wK, denote1_single_op vB wB]
      simp only [Option.map_some, Option.some.injEq, Prod.mk.injEq, true_and]
      have hsbX : strandsBefore win sX c1 = strandsBefore win s c1 := by
        apply sb_congr' win hlo
        intro p _ hp
        rw [segW_eq, segW_eq]
        simp only [yarnAt, frontAt, backAt, eXc, eXr, hr, kX, Int.sub_zero]
        simp [show p ≠ c1 by omega, hcar]
      have hK : backAt sX c1 = 2 * k := by simp [backAt, eXr, kX, hk]
      have hF : frontAt sX c1 = 0 := by simp [frontAt, kX]
      have hsbX1 : d = .L → strandsBefore win sX (c1 + 1) = strandsBefore win s c1 + 2 * k := by
        intro hd; subst hd
        rw [sb_succ win sX hlo, segW_eq, hsbX, hK, hF]
        simp [yarnAt, eXc, arrivesFrom]
      have hl : (sX.stk ⟨.b, c1⟩).length = k := by simp [kX, hk]
      cases d
      · simp only [denoteOp1, slot, eXr, arrivesFrom, Int.add_zero, hsbX, hF, hl, swapB_nil (Or.inr rfl),
          List.nil_append, List.append_nil, Nat.add_zero]
      · simp only [denoteOp1, slot, eXr, arrivesFrom, Int.add_zero, hsbX1 rfl, hF, hK, hl,
          swapB_nil (Or.inl rfl), List.nil_append, List.append_nil, Nat.add_sub_cancel, Nat.sub_zero]
    · intro j; by_cases h : j = c1
      · subst h; simp [apply, kK, fN, bN]
      · simp [apply, kK, fN, bN, h, hb]
    · show sK.carrier = _; simp [hsK, apply, slot, eXr]
    · simp [apply, xferStack, kK, fN, bN]
    · intro i hi; simp [apply, xferStack, kK, hi, fN, bN]

List and drawing helpers for exchanges

  • yarnTo_L2, yarnTo_R3: the walk of the carrier.
  • rackBraid_single: the drawing of a rack when only one position moves.
  • List facts about spliceL and List.set.
namespace Knitout
namespace Exch
theorem yarnTo_L2 (a : Int) : yarnTo (a + 2) a = [.miss .L (fN (a + 1)), .miss .L (fN a)]
Proof
:= by
  simp [yarnTo, List.range_succ]
  exact ⟨congrArg fN (by omega), congrArg fN (by omega)⟩
theorem yarnTo_R3 (a : Int) : yarnTo a (a + 3) = [.miss .R (fN a), .miss .R (fN (a + 1)), .miss .R (fN (a + 2))]
Proof
:= by
  simp [yarnTo, List.range_succ]
theorem flatMap_single {α β : Type} (f : α → List β) (k0 : α) :
    ∀ (l : List α), l.Nodup → k0 ∈ l → (∀ k ∈ l, k ≠ k0 → f k = []) → l.flatMap f = f k0
Proof
  | [], _, h, _ => by simp at h
  | x :: xs, hn, hm, h => by
    rw [List.flatMap_cons]
    have hn' := List.nodup_cons.mp hn
    by_cases hx : x = k0
    · subst hx
      rw [List.flatMap_eq_nil_iff.mpr (fun k hk => h k (List.mem_cons_of_mem _ hk) (fun e => hn'.1 (e ▸ hk))),
        List.append_nil]
    · rw [h x (List.mem_cons_self) hx, List.nil_append]
      exact flatMap_single f k0 xs hn'.2 (by simpa [Ne.symm hx] using hm) (fun k hk => h k (List.mem_cons_of_mem _ hk))
theorem bind_coe_map1 : ∀ (l : List Nat), (l >>= fun a => (pure (a : Int) : List Int)) = List.map (Nat.cast : Nat → Int) l
Proof
  | [] => rfl
  | x :: xs => by
    show [(x : Int)] ++ (xs >>= fun a => (pure (a : Int) : List Int)) = _
    rw [bind_coe_map1 xs]; rfl
theorem rackBraid_single (win : Window) (s : State) (r : Int) (k0 : Nat) (hk0 : k0 < win.w)
    (h : ∀ k : Nat, k < win.w → k ≠ k0 →
      if r < s.rack then yarnAt s (win.lo + k) + frontAt s (win.lo + k) = 0 ∨ backAt s (win.lo + k) = 0
      else (s.stk ⟨.b, win.lo + k - 1 - s.rack⟩).length = 0 ∨
        yarnAt s (win.lo + k) + frontAt s (win.lo + k) = 0) :
    rackBraid win s r =
      if r < s.rack then
        swapB (strandsBefore win s (win.lo + k0)) (yarnAt s (win.lo + k0) + frontAt s (win.lo + k0))
          (backAt s (win.lo + k0)) true
      else
        swapB (strandsBefore win s (win.lo + k0) - 2 * (s.stk ⟨.b, win.lo + k0 - 1 - s.rack⟩).length)
          (2 * (s.stk ⟨.b, win.lo + k0 - 1 - s.rack⟩).length) (yarnAt s (win.lo + k0) + frontAt s (win.lo + k0))
          false
Proof
:= by
  unfold rackBraid
  rw [bind_coe_map1, flatMap_single _ (k0 : Int) _ (List.nodup_range.map (fun a b h => by exact_mod_cast h))
    (List.mem_map.mpr ⟨k0, List.mem_range.mpr hk0, rfl⟩)]
  intro ki hki hne
  obtain ⟨k, hk, rfl⟩ := List.mem_map.mp hki
  have hk' := h k (List.mem_range.mp hk) (fun e => hne (by rw [e]))
  dsimp only
  split
  · rename_i hr
    rw [ite_eq_left hr] at hk'
    rcases hk' with h0 | h0
    · exact swapB_nil (Or.inl h0)
    · exact swapB_nil (Or.inr h0)
  · rename_i hr
    rw [ite_eq_right hr] at hk'
    rcases hk' with h0 | h0
    · exact swapB_nil (Or.inl (by rw [h0]))
    · exact swapB_nil (Or.inr h0)
theorem spliceL_set {α : Type} (l : List α) (f len j : Nat) (v : α) (N : List α) (h1 : f ≤ j) (h2 : j < f + len) :
    spliceL (l.set j v) f len N = spliceL l f len N
Proof
:= by
  unfold spliceL
  rw [List.take_set_of_le h1, List.drop_set_of_lt h2]
theorem getD_set_eq {α : Type} (l : List α) (j : Nat) (v d : α) (h : j < l.length) : (l.set j v).getD j d = v
Proof
:= by
  simp [List.getD_eq_getElem?_getD, h]
theorem getD_set_ne {α : Type} (l : List α) (i j : Nat) (v d : α) (h : i ≠ j) : (l.set j v).getD i d = l.getD i d
Proof
:= by
  simp [List.getD_eq_getElem?_getD, List.getElem?_set_ne (Ne.symm h)]

The compiler: shorthand steps to knitout

compileStep and compileSteps turn a shorthand program on a row of stacks into a one-carrier knitout program. Laid is the layout invariant that the correctness proofs keep.

Layout Object j Used
Canonical, spacing S (canonical S n) coordinate S + 1 + S·j between steps
Compact (compactAt) the k-th stack on front needle k; the yarn in the slot after the stacks before it a target of arrange (ArrangeTotal)
  • An object is the yarn or a stack (Obj). A stack of k loops sits whole on one front needle.
  • The yarn at coordinate c is the carrier in slot c. A stack at coordinate c is on front needle c.
  • scpos puts the objects in order: a stack on needle c at 2c, the carrier in slot c at 2c − 1.

The fragment of each step (compileStep)

Step Instructions
Free moves (moveObject, arrange) loopStep for a stack, yarnTo for the yarn
x a front, yarn and stack misses past the stack; for one sense, the stack goes to the back needle across and back
x a front, two stacks one stack moves by loopStep, then through the back bed with racks -1 and 1
tuck d one tuck on the front needle beside the carrier
merge a the right stack moves left by loopStep; the last move puts it onto the left stack's needle
knit d bd the carrier moves beside the stack, then knitOps
split d bd the carrier moves beside the stack, then splitOps
drop a one drop of the stack's needle
  • loopStep transfers the whole needle to the back bed and back. So it moves a whole stack.
  • compileSteps S: each step, then arrange back to the canonical layout.
  • compile S r w: compact layout to canonical, compileSteps S, canonical to compact. The result is none when a step or an arrange fails.
namespace FormalizeKnitting.Bridge.RM
open FormalizeKnitting.Knitout
structure Comp where
  row : Row
  at_ : List Int
  ops : List Op

def scpos : Obj → Int → Int
  | .yarn, c => 2 * c - 1
  | .stack _, c => 2 * c

def moveObject (c : Comp) (j : Nat) (dest : Int) : Comp :=
  let fr := c.at_.getD j 0
  let moves :=
    if c.row.getD j .yarn = .yarn then yarnTo fr dest
    else if fr < dest then (List.range (dest - fr).toNat).flatMap fun k => loopStep (fr + k) true
    else (List.range (fr - dest).toNat).flatMap fun k => loopStep (fr - k) false
  { c with at_ := c.at_.set j dest, ops := c.ops ++ moves }

def arrange (c : Comp) (target : List Int) : Option Comp :=
  let n := c.row.length
  let pt := fun j => scpos (c.row.getD j .yarn) (target.getD j 0)
  let cur := fun j => scpos (c.row.getD j .yarn) (c.at_.getD j 0)
  if target.length = n ∧ (List.range (n - 1)).all (fun j => decide (pt j < pt (j + 1))) then
    let c1 := (List.range n).reverse.foldl (fun c j => if pt j > cur j then moveObject c j (target.getD j 0) else c) c
    some ((List.range n).foldl (fun c j => if pt j < cur j then moveObject c j (target.getD j 0) else c) c1)
  else none

def emit (c : Comp) (ops : List Op) : Comp := { c with ops := c.ops ++ ops }

def knitOps (d : Dir) (bd : Bed) (c1 : Int) : List Op :=
  (if bd = .b then [.xfer (fN c1) (bN c1)] else []) ++ [.knit d ⟨bd, c1⟩] ++
    (if bd = .b then [.xfer (bN c1) (fN c1)] else [])

def splitOps (d : Dir) (bd : Bed) (c1 : Int) : List Op :=
  let other : Bed := if bd = .f then .b else .f
  (if bd = .b then [.xfer (fN c1) (bN c1)] else []) ++ [.split d ⟨bd, c1⟩ ⟨other, c1⟩] ++
    (if d = .R then [.miss .R (fN (c1 + 1))] else []) ++ [.rack 1, .xfer (bN c1) (fN (c1 + 1)), .rack 0]
compileStep: 81 lines of Lean
def compileStep (c : Comp) : Step → Option Comp
  | .x a front =>
    if Obj.yarn ∈ c.row ∧ a + 1 < c.row.length then
      let p := c.at_.getD a 0
      let q := c.at_.getD (a + 1) 0
      let c' : Option Comp :=
        match c.row.getD a .yarn, c.row.getD (a + 1) .yarn with
        | .stack _, .stack _ =>
          if !front then
            let c1 := moveObject c a (q - 1)
            let c2 := emit c1 [.rack (-1), .xfer (fN (q - 1)) (bN q), .rack 0, .rack 1, .xfer (bN q) (fN (q + 1)),
              .rack 0]
            some { c2 with at_ := c2.at_.set a (q + 1) }
          else
            let c1 := moveObject c (a + 1) (p + 1)
            let c2 := emit c1 [.rack 1, .xfer (fN (p + 1)) (bN p), .rack 0, .rack (-1), .xfer (bN p) (fN (p - 1)),
              .rack 0]
            some { c2 with at_ := c2.at_.set (a + 1) (p - 1) }
        | .yarn, .stack _ =>
          let c1 := emit c ((if front then [.xfer (fN q) (bN q)] else []) ++ yarnTo p (q + 1) ++
            (if front then [.xfer (bN q) (fN q)] else []))
          some { c1 with at_ := c1.at_.set a (q + 1) }
        | .stack _, .yarn =>
          let c1 := emit c ((if !front then [.xfer (fN p) (bN p)] else []) ++ yarnTo q p ++
            (if !front then [.xfer (bN p) (fN p)] else []))
          some { c1 with at_ := c1.at_.set (a + 1) p }
        | .yarn, .yarn => none
      c'.map fun c2 => { c2 with row := splice c2.row a 2 [c2.row.getD (a + 1) .yarn, c2.row.getD a .yarn],
                                 at_ := swapAt c2.at_ a 0 }
    else none
  | .tuck d =>
    if Obj.yarn ∈ c.row then
      let y := yarnIdx c.row
      let cc := c.at_.getD y 0
      match d with
      | .R => some { c with ops := c.ops ++ [.tuck .R (fN cc)], row := splice c.row y 1 (tuckRow .R),
                            at_ := spliceL c.at_ y 1 [cc, cc + 1] }
      | .L => some { c with ops := c.ops ++ [.tuck .L (fN (cc - 1))], row := splice c.row y 1 (tuckRow .L),
                            at_ := spliceL c.at_ y 1 [cc - 1, cc - 1] }
    else none
  | .merge a =>
    if Obj.yarn ∈ c.row then
      match stackAt c.row a, stackAt c.row (a + 1) with
      | some k, some l =>
        let p := c.at_.getD a 0
        let c1 := moveObject c (a + 1) (p + 1)
        let c2 := emit c1 (loopStep (p + 1) false)
        some { c2 with row := splice c2.row a 2 [.stack (k + l)], at_ := spliceL c2.at_ a 2 [p] }
      | _, _ => none
    else none
  | .knit d bd =>
    if Obj.yarn ∈ c.row ∧ hasBeside c.row d then
      match stackAt c.row (besideIdx c.row d) with
      | some _ =>
        let c1 := c.at_.getD (besideIdx c.row d) 0
        let ys := c.at_.getD (yarnIdx c.row) 0
        let cK := emit c (yarnTo ys (if d = .R then c1 else c1 + 1) ++ knitOps d bd c1)
        let newAt : List Int := if d = .R then [c1, c1 + 1] else [c1, c1]
        some { cK with row := splice cK.row (firstIdx c.row d) 2 (tuckRow d),
                       at_ := spliceL cK.at_ (firstIdx c.row d) 2 newAt }
      | none => none
    else none
  | .split d bd =>
    if Obj.yarn ∈ c.row ∧ hasBeside c.row d then
      match stackAt c.row (besideIdx c.row d) with
      | some k =>
        let c1 := c.at_.getD (besideIdx c.row d) 0
        let ys := c.at_.getD (yarnIdx c.row) 0
        let cO := emit c (yarnTo ys (if d = .R then c1 else c1 + 1) ++ splitOps d bd c1)
        let newAt : List Int := if d = .R then [c1, c1 + 1, c1 + 2] else [c1, c1, c1 + 1]
        some { cO with row := splice cO.row (firstIdx c.row d) 2 (splitRow d bd k),
                       at_ := spliceL cO.at_ (firstIdx c.row d) 2 newAt }
      | none => none
    else none
  | .drop a =>
    if Obj.yarn ∈ c.row then
      match stackAt c.row a with
      | some _ => some { c with ops := c.ops ++ [.drop (fN (c.at_.getD a 0))], row := c.row.eraseIdx a,
                                at_ := c.at_.eraseIdx a }
      | none => none
    else none
def compileSteps (S : Nat) : Comp → List Step → Option Comp
  | c, [] => some c
  | c, st :: sts =>
    match compileStep c st with
    | none => none
    | some c1 =>
      match arrange c1 (canonical S c1.row.length) with
      | none => none
      | some c2 => compileSteps S c2 sts

The compact layout of a stack row

def compactAt : Row → Nat → List Int
  | [], _ => []
  | .stack _ :: r, j => ((j + 1 : Nat) : Int) :: compactAt r (j + 1)
  | .yarn :: r, j => ((j + 1 : Nat) : Int) :: compactAt r j

def stackSize : Obj → Nat
  | .yarn => 0
  | .stack k => k

The layout invariant

def loadAt (r : Row) (a : List Int) (i : Int) : Nat :=
  ((r.zip a).map fun p => if p.2 = i then stackSize p.1 else 0).sum

def Laid (c : Comp) (st : State) : Prop :=
  c.row.count .yarn = 1 ∧ c.at_.length = c.row.length ∧ st.rack = 0 ∧ (∀ j, st.stk ⟨.b, j⟩ = []) ∧
  (∀ i, (st.stk ⟨.f, i⟩).length = loadAt c.row c.at_ i) ∧
  st.carrier = c.at_.getD (yarnIdx c.row) 0 ∧
  ∀ j, j + 1 < c.row.length →
    scpos (c.row.getD j .yarn) (c.at_.getD j 0) < scpos (c.row.getD (j + 1) .yarn) (c.at_.getD (j + 1) 0)
end FormalizeKnitting.Bridge.RM

Compiler correctness from four pieces

compileSteps_spec proves the compiled steps correct from four Prop pieces. The compiled program's boxed drawing is the shorthand program's boxed drawing (DB).

Piece Statement Proof
ArrangeFree from a laid-out state, arrange's moves are accepted, draw nothing, and end laid out arrangeFree
ArrangeTotal S arrange succeeds on the canonical and the compact targets arrangeTotal_two (S = 2)
CompileTotal S compileStep accepts every step that runStepB accepts, from the canonical layout compileTotal_any
StepFragment S the fragment of each step is accepted, draws exactly the step's boxed drawing, and ends laid out stepFragment_of_kinds, from one FragmentFor per step kind
  • FragmentFor S P: StepFragment S for the steps that satisfy P. The step kinds are isX, isTuck, isMerge, isKnit, isSplit, isDrop.
  • Fits win c: each coordinate of c is at least 2 inside window win.
  • compileSteps_spec: the pieces, by induction over the steps of a program.

Programs under denote

theorem denote_append (win : Window) :
    ∀ (s : State) (a b : List Op) (s1 s2 : State) (M1 M2 : BWord Label),
      denote win s a = some (s1, M1) → denote win s1 b = some (s2, M2) →
      denote win s (a ++ b) = some (s2, M1 ++ M2)
Proof
  | s, [], b, s1, s2, M1, M2, ha, hb => by
    simp only [denote, Option.some.injEq, Prod.mk.injEq] at ha
    obtain ⟨rfl, rfl⟩ := ha; simpa using hb
  | s, op :: ops, b, s1, s2, M1, M2, ha, hb => by
    simp only [denote] at ha
    split at ha
    · simp at ha
    · rename_i s' hs
      split at ha
      · rename_i hw
        split at ha
        · simp at ha
        · rename_i t' u hd
          simp only [Option.some.injEq, Prod.mk.injEq] at ha
          obtain ⟨rfl, rfl⟩ := ha
          simp only [List.cons_append, denote, hs, hw, ite_true,
            denote_append win s' ops b t' s2 u M2 hd hb, List.append_assoc]
      · simp at ha
def Fits (win : Window) (c : Comp) : Prop := ∀ x ∈ c.at_, win.lo + 2 ≤ x ∧ x + 2 < win.lo + win.w

The pieces

def ArrangeFree : Prop :=
  ∀ (win : Window) (c c' : Comp) (target : List Int) (st : State), Laid c st → Fits win c →
    arrange c target = some c' → c.ops <+: c'.ops → (∀ op ∈ c'.ops, NamedIn3 win op) →
    Fits win c' ∧ ∃ st', denote win st (c'.ops.drop c.ops.length) = some (st', []) ∧ Laid c' st'

def ArrangeTotal (S : Nat) : Prop :=
  ∀ c : Comp, c.row.count .yarn = 1 → c.at_.length = c.row.length →
    (∃ c', arrange c (canonical S c.row.length) = some c' ∧ c'.row = c.row ∧
      c'.at_ = canonical S c.row.length ∧ c.ops <+: c'.ops) ∧
    (∃ c', arrange c (compactAt c.row 0) = some c' ∧ c'.row = c.row ∧ c'.at_ = compactAt c.row 0 ∧
      c.ops <+: c'.ops)

def CompileTotal (S : Nat) : Prop :=
  ∀ (c : Comp) (s : Step) (r' : Row) (M : BWord Label), c.row.count .yarn = 1 →
    c.at_ = canonical S c.row.length → runStepB c.row s = some (r', M) →
    ∃ c1, compileStep c s = some c1 ∧ c1.row = r' ∧ r'.count .yarn = 1 ∧ c.ops <+: c1.ops ∧
      c1.at_.length = c1.row.length

def FragmentFor (S : Nat) (P : Step → Prop) : Prop :=
  ∀ (win : Window) (c c1 : Comp) (st : State) (s : Step) (r' : Row) (M : BWord Label), P s →
    Laid c st → c.at_ = canonical S c.row.length → Fits win c → runStepB c.row s = some (r', M) →
    compileStep c s = some c1 → c.ops <+: c1.ops → (∀ op ∈ c1.ops, NamedIn3 win op) →
    Fits win c1 ∧ ∃ st', denote win st (c1.ops.drop c.ops.length) = some (st', M) ∧ Laid c1 st'

def isX : Step → Prop | .x _ _ => True | _ => False

def isTuck : Step → Prop | .tuck _ => True | _ => False

def isMerge : Step → Prop | .merge _ => True | _ => False

def isKnit : Step → Prop | .knit _ _ => True | _ => False

def isSplit : Step → Prop | .split _ _ => True | _ => False

def isDrop : Step → Prop | .drop _ => True | _ => False

def StepFragment (S : Nat) : Prop := FragmentFor S (fun _ => True)
theorem stepFragment_of_kinds {S : Nat} (hx : FragmentFor S isX) (ht : FragmentFor S isTuck)
    (hm : FragmentFor S isMerge) (hk : FragmentFor S isKnit) (hs : FragmentFor S isSplit)
    (hd : FragmentFor S isDrop) : StepFragment S
Proof
:= by
  intro win c c1 st s r' M _
  cases s with
  | x a f => exact hx win c c1 st _ r' M trivial
  | tuck d => exact ht win c c1 st _ r' M trivial
  | merge a => exact hm win c c1 st _ r' M trivial
  | knit d bd => exact hk win c c1 st _ r' M trivial
  | split d bd => exact hs win c c1 st _ r' M trivial
  | drop a => exact hd win c c1 st _ r' M trivial

The steps, by induction

theorem length_canonical' (S n : Nat) : (canonical S n).length = n
Proof
:= length_canonical S n
theorem compileSteps_spec {S : Nat} (hA : ArrangeFree) (hT : ArrangeTotal S) (hS : StepFragment S)
    (hC : CompileTotal S) :
    ∀ (w : List Step) (c : Comp) (r' : Row) (M : BWord Label), c.row.count .yarn = 1 →
      c.at_ = canonical S c.row.length → DB c.row w = some (r', M) →
      ∃ c2, compileSteps S c w = some c2 ∧ c2.row = r' ∧ c2.row.count .yarn = 1 ∧ c.ops <+: c2.ops ∧
        c2.at_.length = c2.row.length ∧
        ∀ win st, Laid c st → Fits win c → (∀ op ∈ c2.ops, NamedIn3 win op) →
          Fits win c2 ∧ ∃ st', denote win st (c2.ops.drop c.ops.length) = some (st', M) ∧ Laid c2 st'
Proof
  | [], c, r', M, hy, hcan, hDB => by
    simp only [DB, Option.some.injEq, Prod.mk.injEq] at hDB
    obtain ⟨rfl, rfl⟩ := hDB
    refine ⟨c, rfl, rfl, hy, List.prefix_refl _, by rw [hcan, length_canonical'],
      fun win st hL hF _ => ⟨hF, st, ?_, hL⟩⟩
    simp [denote]
  | s :: ss, c, r', M, hy, hcan, hDB => by
    simp only [DB] at hDB
    cases hrs : runStepB c.row s with
    | none => simp [hrs] at hDB
    | some p =>
      obtain ⟨r1, M1⟩ := p
      simp only [hrs] at hDB
      cases hrest : DB r1 ss with
      | none => simp [hrest] at hDB
      | some q =>
        obtain ⟨r2, M2⟩ := q
        simp only [hrest] at hDB
        simp only [Option.some.injEq, Prod.mk.injEq] at hDB
        obtain ⟨rfl, rfl⟩ := hDB
        obtain ⟨c1, hc1, hr1, hy1, hp1, hl1⟩ := hC c s r1 M1 hy hcan hrs
        obtain ⟨⟨c1', ha1, hr1', hat1, hp1'⟩, _⟩ := hT c1 (by rw [hr1]; exact hy1) hl1
        obtain ⟨c2, hc2, hr2, hy2, hp2, hl2, hcond⟩ :=
          compileSteps_spec hA hT hS hC ss c1' r2 M2 (by rw [hr1', hr1]; exact hy1)
            (by rw [hat1, hr1']) (by rw [hr1', hr1]; exact hrest)
        refine ⟨c2, ?_, hr2, hy2, hp1.trans (hp1'.trans hp2), hl2, ?_⟩
        · simp only [compileSteps, hc1, ha1, hc2]
        · intro win st hL hF hN
          have hN1' : ∀ op ∈ c1'.ops, NamedIn3 win op := fun op ho => hN op (hp2.subset ho)
          have hN1 : ∀ op ∈ c1.ops, NamedIn3 win op := fun op ho => hN1' op (hp1'.subset ho)
          obtain ⟨hF1, st1, hd1, hL1⟩ := hS win c c1 st s r1 M1 trivial hL hcan hF hrs hc1 hp1 hN1
          obtain ⟨hF1', st1', hd1', hL1'⟩ := hA win c1 c1' _ st1 hL1 hF1 ha1 hp1' hN1'
          obtain ⟨hF2, st2, hd2, hL2⟩ := hcond win st1' hL1' hF1' hN
          refine ⟨hF2, st2, ?_, hL2⟩
          obtain ⟨t1, e1⟩ := hp1
          obtain ⟨t2, e2⟩ := hp1'
          obtain ⟨t3, e3⟩ := hp2
          rw [← e1, List.drop_left] at hd1
          rw [← e2, List.drop_left] at hd1'
          rw [← e3, List.drop_left] at hd2
          rw [← e3, ← e2, ← e1, List.append_assoc, List.append_assoc, List.drop_left]
          have := denote_append win st _ _ st1 st2 M1 ([] ++ M2) hd1
            (denote_append win st1 _ _ st1' st2 [] M2 hd1' hd2)
          simpa [List.append_assoc] using this

Free moves of a whole stack

A loopStep moves the whole needle. So the one-loop lemmas about loopStep also hold for a stack, under denote.

  • step_eq, denoteOp_eq: step and step1 differ only on a split. denoteOp and denoteOp1 differ only on a split.
  • denote_of_denote1: for a program with no split, denote is denote1 with the labels read in the stack signature (liftB).
Theorem Move Result
stack_right_free a stack one needle right, into a free position accepted, draws nothing, the new needle holds the same list
stack_left_free a stack one needle left, into a free position accepted, draws nothing, the new needle holds the same list
stack_onto a stack one needle left, onto a needle that can hold loops accepted, draws nothing, the moved loops go on top
  • The same list: the transfer to the back bed reverses it, and the transfer back reverses it again.
  • leftToRight_moved: a moved stack keeps its left-to-right order.
  • leftToRight_onto: after stack_onto, left to right, the needle shows the left stack's loops, then the moved stack's. This is the merge order of runStep.
namespace FormalizeKnitting.Bridge.RM
open FormalizeKnitting.Knitout
def NotSplit : Op → Prop
  | .split _ _ _ => False
  | _ => True
theorem crateRefusal_eq {s : State} {op : Op} (h : NotSplit op) : refusal s op = crateRefusal1 s op
Proof
:= by
  cases op <;> first | exact absurd h id | rfl
theorem step_eq {s : State} {op : Op} (h : NotSplit op) : step s op = step1 s op
Proof
:= by
  unfold step step1; rw [crateRefusal_eq h]; cases crateRefusal1 s op <;> rfl
theorem denoteOp_eq (win : Window) (s : State) {op : Op} (h : NotSplit op) :
    denoteOp win s op = liftB (denoteOp1 win s op)
Proof
:= by
  cases op <;> first | exact absurd h id | rfl
theorem liftB_append (u v : BWord PlainLabel) : liftB (u ++ v) = liftB u ++ liftB v
Proof
:= List.map_append ..
theorem denote_of_denote1 (win : Window) :
    ∀ (s : State) (ops : List Op) (t : State) (M : BWord PlainLabel), (∀ op ∈ ops, NotSplit op) →
      denote1 win s ops = some (t, M) → denote win s ops = some (t, liftB 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, 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 hN' : NotSplit op := hN op List.mem_cons_self
          simp only [denote, step_eq hN', hs, hw, ite_true,
            denote_of_denote1 win s' ops t' u (fun o ho => hN o (List.mem_cons_of_mem _ ho)) hd,
            denoteOp_eq win s hN', liftB_append]
      · simp at h
theorem loopStep_notSplit (n : Int) (b : Bool) : ∀ op ∈ loopStep n b, NotSplit op
Proof
:= by
  cases b <;> simp [loopStep, NotSplit]
theorem stack_right_free (win : Window) (st : State) (n : Int) (hr : st.rack = 0)
    (hb : ∀ j, st.stk ⟨.b, j⟩ = []) (hc : st.carrier ≠ n + 1) (hf : st.stk ⟨.f, n + 1⟩ = [])
    (hin : win.inside n = true) (hin1 : win.inside (n + 1) = true) :
    ∃ st', denote win st (loopStep n true) = some (st', []) ∧ st'.rack = 0 ∧ st'.carrier = st.carrier ∧
      ∀ q, st'.stk q = if q = ⟨.f, n + 1⟩ then st.stk ⟨.f, n⟩ else if q = ⟨.f, n⟩ then [] else st.stk q
Proof
:= by
  obtain ⟨st', h, h1, h2, h3⟩ := loopStep_right_free win st n hr hb hc hf hin hin1
  exact ⟨st', denote_of_denote1 win _ _ _ _ (loopStep_notSplit n true) h, h1, h2, h3⟩
theorem stack_left_free (win : Window) (st : State) (n : Int) (hr : st.rack = 0)
    (hb : ∀ j, st.stk ⟨.b, j⟩ = []) (hc : st.carrier ≠ n) (hf : st.stk ⟨.f, n - 1⟩ = [])
    (hin : win.inside n = true) (hin1 : win.inside (n - 1) = true) :
    ∃ st', denote win st (loopStep n false) = some (st', []) ∧ st'.rack = 0 ∧ st'.carrier = st.carrier ∧
      ∀ q, st'.stk q = if q = ⟨.f, n - 1⟩ then st.stk ⟨.f, n⟩ else if q = ⟨.f, n⟩ then [] else st.stk q
Proof
:= by
  obtain ⟨st', h, h1, h2, h3⟩ := loopStep_left_free win st n hr hb hc hf hin hin1
  exact ⟨st', denote_of_denote1 win _ _ _ _ (loopStep_notSplit n false) h, h1, h2, h3⟩
theorem stack_onto (win : Window) (st : State) (n : Int) (hr : st.rack = 0)
    (hb : ∀ j, st.stk ⟨.b, j⟩ = []) (hc : st.carrier ≠ n)
    (hin : win.inside n = true) (hin1 : win.inside (n - 1) = true) :
    ∃ st', denote win st (loopStep n false) = some (st', []) ∧ st'.rack = 0 ∧ st'.carrier = st.carrier ∧
      ∀ q, st'.stk q = if q = ⟨.f, n - 1⟩ then st.stk ⟨.f, n⟩ ++ st.stk ⟨.f, n - 1⟩
        else if q = ⟨.f, n⟩ then [] else st.stk q
Proof
:= by
  obtain ⟨st', h, h1, h2, h3⟩ := Knit.loopStep_onto win st n hr hb hc hin hin1
  exact ⟨st', denote_of_denote1 win _ _ _ _ (loopStep_notSplit n false) h, h1, h2, h3⟩
theorem leftToRight_moved {st st' : State} {m n : Int} (h : st'.stk ⟨.f, m⟩ = st.stk ⟨.f, n⟩) :
    leftToRight st' ⟨.f, m⟩ = leftToRight st ⟨.f, n⟩
Proof
:= by
  simp [leftToRight, h]
theorem leftToRight_onto {st st' : State} {n : Int}
    (h : st'.stk ⟨.f, n - 1⟩ = st.stk ⟨.f, n⟩ ++ st.stk ⟨.f, n - 1⟩) :
    leftToRight st' ⟨.f, n - 1⟩ = leftToRight st ⟨.f, n - 1⟩ ++ leftToRight st ⟨.f, n⟩
Proof
:= by
  simp [leftToRight, h]

Arrange on the shadow row

arrange is the layout planner's arrange1 on the shadow row. This gives ArrangeTotal 2.

  • The shadow sh c reads every stack as one loop (shObj).
  • arrange looks at an object only to tell the yarn from a stack. scpos of a stack is cpos of a loop (scpos_sh).
  • arrange_sh: arrange1 (sh c) t writes the same program and sets the same coordinates as arrange c t.
  • arrange_row: arrange does not change the row.
  • arrangeTotal_two : ArrangeTotal 2, from arrangeTotal'_two through the shadow.
namespace FormalizeKnitting.Bridge.RM
open FormalizeKnitting.Knitout
open scoped List
def shObj : Obj → CellObj
  | .yarn => .yarn
  | .stack _ => .loop

def sh (c : Comp) : Comp1 := ⟨c.row.map shObj, c.at_, c.ops⟩
theorem shObj_eq_yarn (o : Obj) : shObj o = .yarn ↔ o = .yarn
Proof
:= by cases o <;> simp [shObj]
theorem scpos_sh (o : Obj) (x : Int) : cpos (shObj o) x = scpos o x
Proof
:= by cases o <;> rfl
theorem getD_sh (r : Row) (j : Nat) : (r.map shObj).getD j .yarn = shObj (r.getD j .yarn)
Proof
:= by
  simp only [List.getD_eq_getElem?_getD, List.getElem?_map]; cases r[j]? <;> rfl
theorem count_sh : ∀ r : Row, (r.map shObj).count .yarn = r.count .yarn
Proof
  | [] => rfl
  | .yarn :: r => by simp [shObj, count_sh r]
  | .stack _ :: r => by simp [shObj, count_sh r]
theorem compactAt_sh : ∀ (r : Row) (m : Nat), compactAt1 (r.map shObj) m = compactAt r m
Proof
  | [], _ => rfl
  | .yarn :: r, m => by simp [shObj, compactAt, compactAt1, compactAt_sh r m]
  | .stack _ :: r, m => by simp [shObj, compactAt, compactAt1, compactAt_sh r (m + 1)]
theorem moveObject_sh (c : Comp) (j : Nat) (d : Int) : moveObject1 (sh c) j d = sh (moveObject c j d)
Proof
:= by
  unfold moveObject1 moveObject sh
  by_cases h : c.row.getD j .yarn = .yarn
  · have h' : (c.row.map shObj).getD j .yarn = .yarn := by rw [getD_sh, h]; rfl
    dsimp only; rw [ite_eq_left h', ite_eq_left h]
  · have h' : ¬ (c.row.map shObj).getD j .yarn = .yarn := by rw [getD_sh, shObj_eq_yarn]; exact h
    dsimp only; rw [ite_eq_right h', ite_eq_right h]
theorem foldl_sh (P : Nat → Bool) (t : Nat → Int) :
    ∀ (L : List Nat) (x : Comp),
      L.foldl (fun c' j => if P j then moveObject1 c' j (t j) else c') (sh x) =
        sh (L.foldl (fun c' j => if P j then moveObject c' j (t j) else c') x)
Proof
  | [], _ => rfl
  | j :: L, x => by
    simp only [List.foldl_cons]
    by_cases h : P j
    · simp only [h, ite_true, moveObject_sh, foldl_sh P t L]
    · simp only [h, Bool.false_eq_true, ite_false, foldl_sh P t L]
theorem foldl_row (P : Nat → Bool) (t : Nat → Int) :
    ∀ (L : List Nat) (x : Comp), (L.foldl (fun c' j => if P j then moveObject c' j (t j) else c') x).row = x.row
Proof
  | [], _ => rfl
  | j :: L, x => by
    simp only [List.foldl_cons]
    rw [foldl_row P t L]
    by_cases h : P j
    · simp only [h, ite_true]; rfl
    · simp only [h, Bool.false_eq_true, ite_false]
theorem arrange_sh (c : Comp) (t : List Int) : arrange1 (sh c) t = (arrange c t).map sh
Proof
:= by
  have hpt : ∀ j, cpos ((sh c).row.getD j .yarn) (t.getD j 0) = scpos (c.row.getD j .yarn) (t.getD j 0) := by
    intro j; simp only [sh, getD_sh, scpos_sh]
  have hcur : ∀ j, cpos ((sh c).row.getD j .yarn) ((sh c).at_.getD j 0) = scpos (c.row.getD j .yarn) (c.at_.getD j 0) := by
    intro j; simp only [sh, getD_sh, scpos_sh]
  have hlen : (sh c).row.length = c.row.length := by simp [sh]
  unfold arrange1 arrange
  simp only [hpt, hcur, hlen]
  split_ifs with h
  · simp only [Option.map_some, Option.some.injEq]
    have h1 := foldl_sh (fun j => decide (scpos (c.row.getD j .yarn) (t.getD j 0) >
      scpos (c.row.getD j .yarn) (c.at_.getD j 0))) (fun j => t.getD j 0) (List.range c.row.length).reverse c
    have h2 := foldl_sh (fun j => decide (scpos (c.row.getD j .yarn) (t.getD j 0) <
      scpos (c.row.getD j .yarn) (c.at_.getD j 0))) (fun j => t.getD j 0) (List.range c.row.length)
    simp only [decide_eq_true_eq] at h1 h2
    rw [h1, h2]
  · rfl
theorem arrange_row {c c' : Comp} {t : List Int} (h : arrange c t = some c') : c'.row = c.row
Proof
:= by
  unfold arrange at h
  dsimp only at h
  split_ifs at h
  simp only [Option.some.injEq] at h
  subst h
  have h1 := foldl_row (fun j => decide (scpos (c.row.getD j .yarn) (t.getD j 0) >
      scpos (c.row.getD j .yarn) (c.at_.getD j 0))) (fun j => t.getD j 0) (List.range c.row.length).reverse c
  have h2 := foldl_row (fun j => decide (scpos (c.row.getD j .yarn) (t.getD j 0) <
      scpos (c.row.getD j .yarn) (c.at_.getD j 0))) (fun j => t.getD j 0) (List.range c.row.length)
  simp only [decide_eq_true_eq] at h1 h2
  rw [h2, h1]
theorem arrangeTotal_two : ArrangeTotal 2
Proof
:= by
  intro c hy hl
  have hy' : (sh c).row.count .yarn = 1 := by simp only [sh, count_sh]; exact hy
  have hl' : (sh c).at_.length = (sh c).row.length := by simp [sh, hl]
  have hlen : (sh c).row.length = c.row.length := by simp [sh]
  obtain ⟨⟨c1, h1, -, h1a, h1p⟩, ⟨c2, h2, -, h2a, h2p⟩⟩ := arrangeTotal'_two (sh c) hy' hl'
  rw [arrange_sh, hlen] at h1
  rw [arrange_sh, show (sh c).row = c.row.map shObj from rfl, compactAt_sh] at h2
  constructor
  · cases ha : arrange c (canonical 2 c.row.length) with
    | none => rw [ha] at h1; simp at h1
    | some c1' =>
      rw [ha] at h1
      simp only [Option.map_some, Option.some.injEq] at h1
      subst h1
      exact ⟨c1', rfl, arrange_row ha, by rw [← hlen]; exact h1a, h1p⟩
  · cases ha : arrange c (compactAt c.row 0) with
    | none => rw [ha] at h2; simp at h2
    | some c2' =>
      rw [ha] at h2
      simp only [Option.map_some, Option.some.injEq] at h2
      subst h2
      refine ⟨c2', rfl, arrange_row ha, ?_, h2p⟩
      have := h2a
      simp only [sh, compactAt_sh] at this
      exact this

Fragment: merge

mergeFragment_of_listFacts : MergeListFacts → FragmentFor 2 isMerge. mergeListFacts proves MergeListFacts.

From the canonical layout (spacing 2), stacks a and a + 1 are on front needles p = 3 + 2a and p + 2.

Instructions Effect Lemma
loopStep (p + 2) false the right stack moves to the free needle p + 1 stack_left_free
loopStep (p + 1) false the right stack moves onto needle p stack_onto
  • Both moves draw nothing. The merge's boxed drawing is also empty.
  • The result is laid out: needle p holds k + l loops, left stack first (leftToRight_onto).

List facts

theorem loadAt_append {A B : Row} {A' B' : List Int} (h : A.length = A'.length) (i : Int) :
    loadAt (A ++ B) (A' ++ B') i = loadAt A A' i + loadAt B B' i
Proof
:= by
  simp [loadAt, List.zip_append h]
theorem loadAt_cons (o : Obj) (r : Row) (x : Int) (a : List Int) (i : Int) :
    loadAt (o :: r) (x :: a) i = (if x = i then stackSize o else 0) + loadAt r a i
Proof
:= by
  simp [loadAt]
theorem loadAt_not_mem (r : Row) (a : List Int) (i : Int) (h : i ∉ a) : loadAt r a i = 0
Proof
:= by
  induction r generalizing a with
  | nil => simp [loadAt]
  | cons o r ih =>
    cases a with
    | nil => simp [loadAt]
    | cons x a =>
      have hx : x ≠ i := fun e => h (e ▸ List.mem_cons_self)
      have := ih a (fun hm => h (List.mem_cons_of_mem _ hm))
      simp only [loadAt] at this
      simp [loadAt, hx, this]
theorem loadAt_one (o : Obj) (x i : Int) : loadAt [o] [x] i = if x = i then stackSize o else 0
Proof
:= by
  simp [loadAt]
theorem loadAt_two (o₁ o₂ : Obj) (x₁ x₂ i : Int) :
    loadAt [o₁, o₂] [x₁, x₂] i = (if x₁ = i then stackSize o₁ else 0) + (if x₂ = i then stackSize o₂ else 0)
Proof
:= by
  simp [loadAt]
theorem canonical_getElem {n j : Nat} (h : j < (canonical 2 n).length) :
    (canonical 2 n)[j] = 3 + 2 * (j : Int)
Proof
:= by
  rw [← getD_of_lt h 0]
  exact canonical_getD_two (by rw [canonical_length] at h; exact h)
theorem mem_canonical_take {n a : Nat} {x : Int} (h : x ∈ (canonical 2 n).take a) : x + 2 ≤ 3 + 2 * (a : Int)
Proof
:= by
  obtain ⟨j, hj, rfl⟩ := List.mem_iff_getElem.mp h
  rw [List.getElem_take, canonical_getElem]
  simp only [List.length_take] at hj; omega
theorem mem_canonical_drop {n a : Nat} {x : Int} (h : x ∈ (canonical 2 n).drop a) : 3 + 2 * (a : Int) ≤ x
Proof
:= by
  obtain ⟨j, hj, rfl⟩ := List.mem_iff_getElem.mp h
  rw [List.getElem_drop, canonical_getElem]
  omega
theorem cut_two {α : Type} (l : List α) {a : Nat} (h : a + 1 < l.length) (d : α) :
    l = l.take a ++ [l.getD a d, l.getD (a + 1) d] ++ l.drop (a + 2)
Proof
:= by
  rw [← seg1_two l h d, List.append_assoc, ← List.drop_drop, List.take_append_drop, List.take_append_drop]
theorem idxOf_sh : ∀ r : Row, (r.map shObj).idxOf .yarn = r.idxOf .yarn
Proof
  | [] => rfl
  | .yarn :: r => by simp [shObj, List.idxOf_cons_self]
  | .stack _ :: r => by
    simp only [List.map_cons, shObj]
    rw [List.idxOf_cons_ne _ (by simp), List.idxOf_cons_ne _ (by simp), idxOf_sh r]
theorem yarnIdx_of {r : Row} (hy : r.count .yarn = 1) {j : Nat} (hj : j < r.length)
    (h : r.getD j .yarn = .yarn) : yarnIdx r = j
Proof
:= by
  have e : yarnIdx r = cellYarnIdx (r.map shObj) := by simp [yarnIdx, cellYarnIdx, idxOf_sh]
  rw [e]
  have hy' : (r.map shObj).count .yarn = 1 := by rw [count_sh]; exact hy
  exact ((getD_eq_yarn_iff1 hy' (by simpa using hj)).mp (by rw [getD_sh, h]; rfl)).symm
theorem yarnIdx_spec {r : Row} (hy : r.count .yarn = 1) : yarnIdx r < r.length ∧ r.getD (yarnIdx r) .yarn = .yarn
Proof
:= by
  have hm : Obj.yarn ∈ r := List.count_pos_iff.mp (by omega)
  have hl : yarnIdx r < r.length := List.idxOf_lt_length_iff.mpr hm
  refine ⟨hl, ?_⟩
  rw [getD_of_lt hl]
  exact List.getElem_idxOf hl

The fragment

theorem stackAt_getD {r : Row} {a k : Nat} (h : stackAt r a = some k) : a < r.length ∧ r.getD a .yarn = .stack k
Proof
:= by
  obtain ⟨h1, _⟩ := stackAt_some h
  have hl : a < r.length := by
    by_contra hc; rw [List.getElem?_eq_none (by omega)] at h1; simp at h1
  exact ⟨hl, by rw [List.getD_eq_getElem?_getD, h1]; rfl⟩
def MergeListFacts : Prop :=
  ∀ (r : Row) (n a k l : Nat), r.length = n → a + 1 < n → r.count .yarn = 1 → r.getD a .yarn = .stack k →
    r.getD (a + 1) .yarn = .stack l →
    (((canonical 2 n).take a ++ [3 + 2 * (a : Int)] ++ (canonical 2 n).drop (a + 2)).getD
        (yarnIdx (r.take a ++ [Obj.stack (k + l)] ++ r.drop (a + 2))) 0 = 3 + 2 * (yarnIdx r : Int)) ∧
    ∀ j, j + 1 < (r.take a ++ [Obj.stack (k + l)] ++ r.drop (a + 2)).length →
      scpos ((r.take a ++ [Obj.stack (k + l)] ++ r.drop (a + 2)).getD j .yarn)
          (((canonical 2 n).take a ++ [3 + 2 * (a : Int)] ++ (canonical 2 n).drop (a + 2)).getD j 0) <
        scpos ((r.take a ++ [Obj.stack (k + l)] ++ r.drop (a + 2)).getD (j + 1) .yarn)
          (((canonical 2 n).take a ++ [3 + 2 * (a : Int)] ++ (canonical 2 n).drop (a + 2)).getD (j + 1) 0)
theorem mergeFragment_of_listFacts (hML : MergeListFacts) : FragmentFor 2 isMerge
Proof
:= by
  intro win c c1 st s r' M hs hL hc hF hrs hcs hpre hN
  cases s with
  | x _ _ | tuck _ | knit _ _ | split _ _ | drop _ => exact absurd hs id
  | merge a =>
  obtain ⟨hy, hlen, hr, hb, hfr, hcar, hsort⟩ := hL
  have hyin : Obj.yarn ∈ c.row := List.count_pos_iff.mp (by omega)
  cases hka : stackAt c.row a with
  | none => simp [runStepB, hyin, hka] at hrs
  | some k =>
  cases hlb : stackAt c.row (a + 1) with
  | none => simp [runStepB, hyin, hka, hlb] at hrs
  | some l =>
  simp only [runStepB, hyin, ite_true, hka, hlb, Option.some.injEq, Prod.mk.injEq] at hrs
  obtain ⟨rfl, rfl⟩ := hrs
  obtain ⟨ha, hga⟩ := stackAt_getD hka
  obtain ⟨hb1, hgb⟩ := stackAt_getD hlb
  set n := c.row.length with hn
  have hpa : c.at_.getD a 0 = 3 + 2 * (a : Int) := by rw [hc]; exact canonical_getD_two ha
  have hpb : c.at_.getD (a + 1) 0 = 3 + 2 * ((a + 1 : Nat) : Int) := by rw [hc]; exact canonical_getD_two hb1
  set p : Int := 3 + 2 * (a : Int) with hp
  have hmove : (moveObject c (a + 1) (p + 1)).ops = c.ops ++ loopStep (p + 2) false := by
    simp only [moveObject, hgb, hpb]
    rw [ite_eq_right (by simp), ite_eq_right (by push_cast; omega)]
    have : (3 + 2 * ((a + 1 : Nat) : Int) - (p + 1)).toNat = 1 := by push_cast; omega
    rw [this]
    have e2 : 3 + 2 * ((a + 1 : Nat) : Int) - ((0 : Nat) : Int) = p + 2 := by push_cast; omega
    simp only [List.range_one]
    simp only [List.bind_eq_flatMap, List.pure_def, List.flatMap_cons, List.flatMap_nil, List.append_nil, e2]
  simp only [compileStep, hyin, ite_true, hka, hlb, Option.some.injEq, hpa] at hcs
  subst hcs
  simp only [emit, hmove] at hpre hN ⊢
  have hN1 : NamedIn3 win (.xfer (fN (p + 2)) (bN (p + 2))) := hN _ (by simp [loopStep])
  have hN2 : NamedIn3 win (.xfer (bN (p + 1)) (fN (p + 1 - 1))) := hN _ (by simp [loopStep])
  have i1 := hN1 (p + 2) (by simp [Op.named, fN, bN])
  have i2 := hN2 (p + 1) (by simp [Op.named, fN, bN])
  have i3 := hN2 (p + 1 - 1) (by simp [Op.named, fN, bN])
  have hyl := yarnIdx_spec hy
  set y := yarnIdx c.row with hydef
  have hya : y ≠ a := fun e => by rw [e, hga] at hyl; exact absurd hyl.2 (by simp)
  have hyb : y ≠ a + 1 := fun e => by rw [e, hgb] at hyl; exact absurd hyl.2 (by simp)
  have hcy : st.carrier = 3 + 2 * (y : Int) := by rw [hcar, hc]; exact canonical_getD_two hyl.1
  have hcan : c.at_ = c.at_.take a ++ [p, p + 2] ++ c.at_.drop (a + 2) := by
    have := cut_two c.at_ (a := a) (by rw [hc, canonical_length]; omega) 0
    have e3 : 3 + 2 * ((a + 1 : Nat) : Int) = p + 2 := by push_cast; omega
    rw [hpa, hpb, e3] at this; exact this
  have hrow := cut_two c.row (a := a) (by omega) .yarn
  rw [hga, hgb] at hrow
  have hloads : ∀ i, (st.stk ⟨.f, i⟩).length = loadAt (c.row.take a) (c.at_.take a) i +
      ((if p = i then k else 0) + (if p + 2 = i then l else 0)) + loadAt (c.row.drop (a + 2)) (c.at_.drop (a + 2)) i := by
    intro i
    rw [hfr i]
    conv_lhs => rw [hrow, hcan]
    rw [loadAt_append (by simp [hlen]; omega), loadAt_append (by simp [hlen]; omega), loadAt_two]
    simp [stackSize]
  have hA : ∀ x ∈ c.at_.take a, x + 2 ≤ p := fun x hx => by rw [hc] at hx; exact mem_canonical_take hx
  have hC : ∀ x ∈ c.at_.drop (a + 2), p + 4 ≤ x := fun x hx => by
    rw [hc] at hx; have := mem_canonical_drop hx; push_cast at this; omega
  have hp0 : st.stk ⟨.f, p + 1⟩ = [] := by
    have := hloads (p + 1)
    rw [loadAt_not_mem _ _ _ (fun h => by have := hA _ h; omega),
      loadAt_not_mem _ _ _ (fun h => by have := hC _ h; omega)] at this
    simp at this; exact List.length_eq_zero_iff.mp (by simpa using this)
  obtain ⟨st1, hd1, hr1, hc1, hk1⟩ := stack_left_free win st (p + 2) hr hb (by rw [hcy]; omega)
    (by rw [show p + 2 - 1 = p + 1 by omega]; exact hp0)
    (by simp [Window.inside]; omega) (by simp [Window.inside]; omega)
  have hb1' : ∀ j, st1.stk ⟨.b, j⟩ = [] := fun j => by rw [hk1]; simp [hb]
  obtain ⟨st2, hd2, hr2, hc2, hk2⟩ := stack_onto win st1 (p + 1) hr1 hb1' (by rw [hc1, hcy]; omega)
    (by simp [Window.inside]; omega) (by simp [Window.inside]; omega)
  have hat' : (moveObject c (a + 1) (p + 1)).at_ = c.at_.set (a + 1) (p + 1) := rfl
  have hrw' : (moveObject c (a + 1) (p + 1)).row = c.row := rfl
  simp only [hat', hrw']
  have eA : spliceL (c.at_.set (a + 1) (p + 1)) a 2 [p] = c.at_.take a ++ [p] ++ c.at_.drop (a + 2) := by
    simp only [spliceL]
    rw [List.take_set_of_le (by omega), List.drop_set_of_lt (by omega)]
  have eR : splice c.row a 2 [.stack (k + l)] = c.row.take a ++ [.stack (k + l)] ++ c.row.drop (a + 2) := rfl
  rw [eA, eR]
  have hlA : (c.row.take a).length = a := by simp; omega
  have hlA' : (c.at_.take a).length = a := by simp; omega
  have hlC : (c.at_.drop (a + 2)).length = (c.row.drop (a + 2)).length := by
    rw [List.length_drop, List.length_drop, hlen]
  have hs2 : ∀ i, st2.stk ⟨.f, i⟩ = if i = p then st.stk ⟨.f, p + 2⟩ ++ st.stk ⟨.f, p⟩
      else if i = p + 1 ∨ i = p + 2 then [] else st.stk ⟨.f, i⟩ := by
    intro i
    have e1 : p + 2 - 1 = p + 1 := by omega
    have e2 : p + 1 - 1 = p := by omega
    simp only [hk2, hk1, e1, e2, Needle.mk.injEq, true_and]
    by_cases h0 : i = p
    · rw [h0]; simp
    · by_cases h1 : i = p + 1
      · rw [h1]; simp
      · by_cases h2 : i = p + 2
        · rw [h2]; simp
        · simp only [h0, h1, h2, ite_false, or_self]
  refine ⟨?_, st2, ?_, ?_⟩
  · intro x hx
    simp only [List.mem_append, List.mem_singleton] at hx
    have hm : x ∈ c.at_ := by
      rcases hx with (hx | rfl) | hx
      · exact List.mem_of_mem_take hx
      · rw [← hpa]; exact getD_mem' (by omega)
      · exact List.mem_of_mem_drop hx
    exact hF x hm
  · rw [List.append_assoc, List.drop_left]
    simpa using denote_append win st _ _ st1 st2 [] [] hd1 hd2
  · have hcount : (c.row.take a).count .yarn + (c.row.drop (a + 2)).count .yarn = 1 := by
      have := congrArg (List.count Obj.yarn) hrow
      simp only [List.count_append] at this
      simp at this; omega
    refine ⟨by simp only [List.count_append]; simp; omega, by simp [hlen]; omega, hr2, ?_, ?_, ?_, ?_⟩
    · intro j; simp [hk2, hk1, hb]
    · intro i
      rw [loadAt_append (by simp [hlen]; omega), loadAt_append (by simp [hlen]; omega), loadAt_one, hs2]
      have hp2 := hloads (p + 2)
      have hpp := hloads p
      have hi := hloads i
      rw [loadAt_not_mem (c.row.take a) (c.at_.take a) (p + 2) (fun h => by have := hA _ h; omega),
        loadAt_not_mem (c.row.drop (a + 2)) (c.at_.drop (a + 2)) (p + 2) (fun h => by have := hC _ h; omega)] at hp2
      rw [loadAt_not_mem (c.row.drop (a + 2)) (c.at_.drop (a + 2)) p (fun h => by have := hC _ h; omega)] at hpp
      by_cases h0 : i = p
      · rw [h0, loadAt_not_mem (c.row.drop (a + 2)) (c.at_.drop (a + 2)) p (fun h => by have := hC _ h; omega)]
        simp at hp2 hpp ⊢; simp [stackSize]; omega
      · by_cases h12 : i = p + 1 ∨ i = p + 2
        · rw [ite_eq_right h0, ite_eq_left h12, loadAt_not_mem (c.row.take a) (c.at_.take a) i (fun h => by have := hA _ h; omega),
            loadAt_not_mem (c.row.drop (a + 2)) (c.at_.drop (a + 2)) i (fun h => by have := hC _ h; omega)]
          simp [Ne.symm h0]
        · rw [ite_eq_right h0, ite_eq_right h12, hi]
          simp [Ne.symm h0]; omega
    · rw [hc2, hc1, hcy, hc]
      exact (hML c.row n a k l rfl (by omega) hy hga hgb).1.symm
    · intro j hj
      rw [hc]
      exact (hML c.row n a k l rfl (by omega) hy hga hgb).2 j hj

The merge list facts

mergeListFacts : MergeListFacts. These are list facts only; no machine state occurs.

  • After the merge's splice from the canonical layout (spacing 2), object j has coordinate 3 + 2j up to the merged stack, and 3 + 2(j + 1) after it (merged_at).
  • The coordinates are still at least 2 apart. So they are in strictly increasing scpos order, for all objects.
  • The yarn is not one of the two merged stacks. So it keeps its coordinate.
namespace FormalizeKnitting.Bridge.RM
open FormalizeKnitting.Knitout FormalizeKnitting.Bridge.RM
open scoped List
theorem getD_splice_two {α : Type} (L : List α) (a : Nat) (x d : α) (ha : a + 1 < L.length) (j : Nat) :
    (L.take a ++ [x] ++ L.drop (a + 2)).getD j d =
      if j < a then L.getD j d else if j = a then x else L.getD (j + 1) d
Proof
:= by
  simp only [List.getD_eq_getElem?_getD]
  have hta : (L.take a).length = a := by simp; omega
  by_cases h1 : j < a
  · rw [ite_eq_left h1, List.append_assoc, List.getElem?_append_left (by omega), List.getElem?_take_of_lt h1]
  · rw [ite_eq_right h1, List.append_assoc, List.getElem?_append_right (by omega), hta]
    by_cases h2 : j = a
    · subst h2; simp
    · rw [ite_eq_right h2, List.singleton_append, show j - a = (j - a - 1) + 1 by omega, List.getElem?_cons_succ, List.getElem?_drop,
        show a + 2 + (j - a - 1) = j + 1 by omega]
theorem length_splice_two {α : Type} (L : List α) (a : Nat) (x : α) (ha : a + 1 < L.length) :
    (L.take a ++ [x] ++ L.drop (a + 2)).length = L.length - 1
Proof
:= by
  simp; omega
theorem merged_at (n a : Nat) (ha : a + 1 < n) (j : Nat) (hj : j < n - 1) :
    ((canonical 2 n).take a ++ [3 + 2 * (a : Int)] ++ (canonical 2 n).drop (a + 2)).getD j 0 =
      if j ≤ a then 3 + 2 * (j : Int) else 3 + 2 * ((j + 1 : Nat) : Int)
Proof
:= by
  rw [getD_splice_two _ _ _ _ (by rw [canonical_length]; exact ha)]
  by_cases h1 : j < a
  · rw [ite_eq_left h1, ite_eq_left (by omega), canonical_getD_two (by omega)]
  · by_cases h2 : j = a
    · subst h2; simp
    · rw [ite_eq_right h1, ite_eq_right h2, ite_eq_right (by omega), canonical_getD_two (by omega)]
theorem mergeListFacts : MergeListFacts
Proof
:= by
  intro r n a k l hn ha hy hga hgb
  set R := r.take a ++ [Obj.stack (k + l)] ++ r.drop (a + 2) with hR
  have hRl : R.length = n - 1 := by rw [hR, length_splice_two _ _ _ (by omega), hn]
  have hRg := getD_splice_two r a (Obj.stack (k + l)) Obj.yarn (by omega)
  have hrow := cut_two r (a := a) (by omega) .yarn
  rw [hga, hgb] at hrow
  have hcR : R.count .yarn = 1 := by
    have e := congrArg (List.count Obj.yarn) hrow
    rw [hR]
    simp only [List.count_append] at e ⊢
    simp at e ⊢; omega
  obtain ⟨hyl, hyy⟩ := yarnIdx_spec hy
  set y := yarnIdx r with hyd
  have hya : y ≠ a := fun e => by rw [e, hga] at hyy; exact absurd hyy (by simp)
  have hyb : y ≠ a + 1 := fun e => by rw [e, hgb] at hyy; exact absurd hyy (by simp)
  refine ⟨?_, ?_⟩
  · by_cases hlt : y < a
    · have hYR : yarnIdx R = y := yarnIdx_of hcR (by omega) (by rw [hRg, ite_eq_left hlt]; exact hyy)
      rw [hYR, merged_at n a (by omega) y (by omega), ite_eq_left (by omega)]
    · have hYR : yarnIdx R = y - 1 := yarnIdx_of hcR (by omega)
        (by rw [hRg, ite_eq_right (by omega), ite_eq_right (by omega), show y - 1 + 1 = y by omega]; exact hyy)
      rw [hYR, merged_at n a (by omega) (y - 1) (by omega), ite_eq_right (by omega), show y - 1 + 1 = y by omega]
  · intro j hj
    rw [hRl] at hj
    have hA := merged_at n a (by omega) j (by omega)
    have hB := merged_at n a (by omega) (j + 1) (by omega)
    have hgap : ((canonical 2 n).take a ++ [3 + 2 * (a : Int)] ++ (canonical 2 n).drop (a + 2)).getD j 0 + 2 ≤
        ((canonical 2 n).take a ++ [3 + 2 * (a : Int)] ++ (canonical 2 n).drop (a + 2)).getD (j + 1) 0 := by
      rw [hA, hB]; split_ifs <;> push_cast <;> omega
    generalize ((canonical 2 n).take a ++ [3 + 2 * (a : Int)] ++ (canonical 2 n).drop (a + 2)).getD j 0 = u at hgap
    generalize ((canonical 2 n).take a ++ [3 + 2 * (a : Int)] ++ (canonical 2 n).drop (a + 2)).getD (j + 1) 0 = v
      at hgap
    cases R.getD j .yarn <;> cases R.getD (j + 1) .yarn <;> simp only [scpos] <;> omega

The compiler accepts every step

compileTotal_any S : CompileTotal S for every spacing S. compileTotal : CompileTotal 2.

On a row with one yarn (compileStep_total):

  • runStepB and compileStep have the same conditions. compileStep also refuses an exchange of two yarns. One yarn rules it out (yarn_ne_two).
  • The two new rows are equal.
  • Each branch changes row and at_ by splices with replacement lists of equal length.
  • The program is only extended (compileStep_pres).
  • The new row has one yarn. The replaced objects and their replacement hold the same number of yarns.

The layout hypothesis of CompileTotal is not used.

namespace FormalizeKnitting.Bridge.RM
open FormalizeKnitting.Knitout FormalizeKnitting.Bridge.RM
open scoped List
theorem len_splice {α : Type} (l : List α) (f n : Nat) (N : List α) :
    (l.take f ++ N ++ l.drop (f + n)).length = min f l.length + N.length + (l.length - (f + n))
Proof
:= by
  simp; omega
theorem count_spliceL (r : Row) (f n : Nat) (N : Row) :
    (splice r f n N).count .yarn = (r.take f).count .yarn + N.count .yarn + (r.drop (f + n)).count .yarn
Proof
:= by
  simp [splice, List.count_append]; omega
theorem count_cut1 {r : Row} {a : Nat} {o : Obj} (h : r[a]? = some o) :
    r.count .yarn = (r.take a).count .yarn + [o].count .yarn + (r.drop (a + 1)).count .yarn
Proof
:= by
  conv_lhs => rw [cut1 h]
  simp [List.count_append, List.count_cons]; split_ifs <;> omega
theorem count_cut2 {r : Row} {a : Nat} {o₁ o₂ : Obj} (h₁ : r[a]? = some o₁) (h₂ : r[a + 1]? = some o₂) :
    r.count .yarn = (r.take a).count .yarn + [o₁, o₂].count .yarn + (r.drop (a + 2)).count .yarn
Proof
:= by
  conv_lhs => rw [cut2 h₁ h₂]
  simp [List.count_append, List.count_cons]; omega
theorem getElem?_of_getD {r : Row} {a : Nat} (h : a < r.length) : r[a]? = some (r.getD a .yarn)
Proof
:= by
  rw [List.getD_eq_getElem?_getD, List.getElem?_eq_getElem h]; rfl
theorem compileStep_pres (c : Comp) (s : Step) (c1 : Comp) (h : compileStep c s = some c1) :
    c.ops <+: c1.ops ∧ (c.at_.length = c.row.length → c1.at_.length = c1.row.length)
Proof
:= by
  cases s with
  | drop a =>
    simp only [compileStep] at h
    split at h
    · split at h
      · simp only [Option.some.injEq] at h; subst h
        refine ⟨List.prefix_append _ _, fun hl => ?_⟩
        simp only [List.length_eraseIdx, hl]
      · simp at h
    · simp at h
  | tuck d =>
    simp only [compileStep] at h
    split at h
    · cases d <;> simp only [Option.some.injEq] at h <;> subst h <;>
        exact ⟨List.prefix_append _ _, fun hl => by simp only [spliceL, splice, len_splice, hl]; rfl⟩
    · simp at h
  | merge a =>
    simp only [compileStep] at h
    split at h
    · split at h
      · simp only [Option.some.injEq] at h; subst h
        refine ⟨(List.prefix_append _ _).trans (List.prefix_append _ _), fun hl => ?_⟩
        simp only [spliceL, splice, len_splice, emit, moveObject, List.length_set, hl]; rfl
      · simp at h
    · simp at h
  | x a front =>
    simp only [compileStep] at h
    split at h
    · cases h1 : c.row.getD a .yarn <;> cases h2 : c.row.getD (a + 1) .yarn <;> cases front <;>
        simp only [h1, h2, Option.map_some, Option.map_none, Option.some.injEq, reduceCtorEq,
          Bool.not_true, Bool.not_false, Bool.false_eq_true, ite_true, ite_false] at h <;> subst h <;>
        refine ⟨?_, fun hl => ?_⟩
      all_goals first
        | exact (List.prefix_append _ _).trans (List.prefix_append _ _)
        | exact List.prefix_append _ _
        | (simp only [swapAt, spliceL, splice, len_splice, emit, moveObject, List.length_set, hl]; rfl)
    · simp at h
  | knit d bd =>
    simp only [compileStep] at h
    split at h
    · split at h
      · simp only [Option.some.injEq] at h; subst h
        refine ⟨List.prefix_append _ _, fun hl => ?_⟩
        cases d <;> simp only [spliceL, splice, len_splice, emit, hl, tuckRow, ite_true, reduceCtorEq,
          ite_false] <;> rfl
      · simp at h
    · simp at h
  | split d bd =>
    simp only [compileStep] at h
    split at h
    · split at h
      · simp only [Option.some.injEq] at h; subst h
        refine ⟨List.prefix_append _ _, fun hl => ?_⟩
        cases d <;> cases bd <;> simp only [spliceL, splice, len_splice, emit, hl, splitRow, ite_true,
          reduceCtorEq, ite_false] <;> rfl
      · simp at h
    · simp at h
theorem yarn_ne_two {r : Row} (hy : r.count .yarn = 1) {a : Nat} (ha : a + 1 < r.length)
    (h1 : r.getD a .yarn = .yarn) (h2 : r.getD (a + 1) .yarn = .yarn) : False
Proof
:= by
  have := count_cut2 (getElem?_of_getD (r := r) (a := a) (by omega)) (getElem?_of_getD ha)
  rw [h1, h2] at this
  simp at this; omega
theorem mk_total {c : Comp} {s : Step} {r' : Row} (H : ∃ c1, compileStep c s = some c1 ∧ c1.row = r')
    (hc : r'.count .yarn = 1) : ∃ c1, compileStep c s = some c1 ∧ c1.row = r' ∧ r'.count .yarn = 1
Proof
:=
  let ⟨c1, h1, h2⟩ := H; ⟨c1, h1, h2, hc⟩
theorem compileStep_total (c : Comp) (s : Step) (r' : Row) (M : BWord Label) (hy : c.row.count .yarn = 1)
    (h : runStepB c.row s = some (r', M)) : ∃ c1, compileStep c s = some c1 ∧ c1.row = r' ∧ r'.count .yarn = 1
Proof
:= by
  have hyin : Obj.yarn ∈ c.row := List.count_pos_iff.mp (by omega)
  have hyat : c.row[yarnIdx c.row]? = some .yarn := yarn_at hyin
  have hyl : yarnIdx c.row < c.row.length := List.idxOf_lt_length_of_mem hyin
  cases s with
  | drop a =>
    simp only [runStepB, ite_eq_left hyin] at h
    cases hk : stackAt c.row a with
    | none => simp [hk] at h
    | some k =>
      simp only [hk, Option.some.injEq, Prod.mk.injEq] at h
      obtain ⟨rfl, -⟩ := h
      refine mk_total (by simp [compileStep, hyin, hk]) ?_
      have hc := count_cut1 (stackAt_some hk).1
      have ha : a < c.row.length := (List.getElem?_eq_some_iff.mp (stackAt_some hk).1).1
      rw [List.eraseIdx_eq_take_drop_succ, List.count_append]
      simp at hc; omega
  | tuck d =>
    simp only [runStepB, ite_eq_left hyin, Option.some.injEq, Prod.mk.injEq] at h
    obtain ⟨rfl, -⟩ := h
    have hc := count_cut1 hyat
    cases d <;> refine mk_total (by simp [compileStep, hyin]) ?_ <;>
      rw [count_spliceL] <;> simp [tuckRow] at hc ⊢ <;> omega
  | merge a =>
    simp only [runStepB, ite_eq_left hyin] at h
    cases hk : stackAt c.row a with
    | none => simp [hk] at h
    | some k =>
      cases hl : stackAt c.row (a + 1) with
      | none => simp [hk, hl] at h
      | some l =>
        simp only [hk, hl, Option.some.injEq, Prod.mk.injEq] at h
        obtain ⟨rfl, -⟩ := h
        refine mk_total (by simp [compileStep, hyin, hk, hl, emit, moveObject]) ?_
        have hc := count_cut2 (stackAt_some hk).1 (stackAt_some hl).1
        rw [count_spliceL]; simp at hc ⊢; omega
  | x a front =>
    simp only [runStepB] at h
    split at h
    · rename_i hc
      simp only [Option.some.injEq, Prod.mk.injEq] at h
      obtain ⟨rfl, -⟩ := h
      have hcnt := count_cut2 (getElem?_of_getD (r := c.row) (a := a) (by omega)) (getElem?_of_getD hc.2)
      have hcnt' : (splice c.row a 2 [c.row.getD (a + 1) .yarn, c.row.getD a .yarn]).count .yarn = 1 := by
        rw [count_spliceL]; simp only [List.count_cons, List.count_nil] at hcnt ⊢; split_ifs at hcnt ⊢ <;> omega
      refine mk_total ?_ hcnt'
      cases h1 : c.row.getD a .yarn <;> cases h2 : c.row.getD (a + 1) .yarn
      · exact absurd (yarn_ne_two hy hc.2 h1 h2) id
      all_goals
        have hS : ∃ c1, compileStep c (.x a front) = some c1 := by
          cases front <;> simp only [compileStep, ite_eq_left hc, h1, h2, Option.map_some, Bool.not_true, Bool.not_false,
            Bool.false_eq_true, ite_true, ite_false] <;> exact ⟨_, rfl⟩
        obtain ⟨c1, hc1⟩ := hS
        refine ⟨c1, hc1, ?_⟩
        have hc1' := hc1
        cases front <;> simp only [compileStep, ite_eq_left hc, h1, h2, Option.map_some, Bool.not_true, Bool.not_false,
          Bool.false_eq_true, ite_true, ite_false, Option.some.injEq] at hc1' <;> subst hc1' <;>
          simp only [emit, moveObject, h1, h2]
    · simp at h
  | knit d bd =>
    simp only [runStepB] at h
    split at h
    · rename_i hc
      cases hk : stackAt c.row (besideIdx c.row d) with
      | none => simp [hk] at h
      | some k =>
        simp only [hk, Option.some.injEq, Prod.mk.injEq] at h
        obtain ⟨rfl, -⟩ := h
        refine mk_total (by simp [compileStep, hc, hk, emit]) ?_
        have hs := (stackAt_some hk).1
        cases d
        · simp only [besideIdx] at hs
          have hcnt := count_cut2 hyat hs
          simp only [firstIdx]; rw [count_spliceL]; simp [tuckRow] at hcnt ⊢; omega
        · simp only [besideIdx, hasBeside] at hs hc
          have hyat' : c.row[yarnIdx c.row - 1 + 1]? = some .yarn := by
            rw [show yarnIdx c.row - 1 + 1 = yarnIdx c.row by simp at hc; omega]; exact hyat
          have hcnt := count_cut2 hs hyat'
          simp only [firstIdx]; rw [count_spliceL]; simp [tuckRow] at hcnt ⊢; omega
    · simp at h
  | split d bd =>
    simp only [runStepB] at h
    split at h
    · rename_i hc
      cases hk : stackAt c.row (besideIdx c.row d) with
      | none => simp [hk] at h
      | some k =>
        simp only [hk, Option.some.injEq, Prod.mk.injEq] at h
        obtain ⟨rfl, -⟩ := h
        refine mk_total (by simp [compileStep, hc, hk, emit]) ?_
        have hs := (stackAt_some hk).1
        cases d
        · simp only [besideIdx] at hs
          have hcnt := count_cut2 hyat hs
          simp only [firstIdx]; rw [count_spliceL]; cases bd <;> simp [splitRow] at hcnt ⊢ <;> omega
        · simp only [besideIdx, hasBeside] at hs hc
          have hyat' : c.row[yarnIdx c.row - 1 + 1]? = some .yarn := by
            rw [show yarnIdx c.row - 1 + 1 = yarnIdx c.row by simp at hc; omega]; exact hyat
          have hcnt := count_cut2 hs hyat'
          simp only [firstIdx]; rw [count_spliceL]; cases bd <;> simp [splitRow] at hcnt ⊢ <;> omega
    · simp at h
theorem compileTotal_any (S : Nat) : CompileTotal S
Proof
:= by
  intro c s r' M hy hcan h
  obtain ⟨c1, hc1, hr, hy'⟩ := compileStep_total c s r' M hy h
  have hl : c.at_.length = c.row.length := by rw [hcan, length_canonical']
  exact ⟨c1, hc1, hr, hy', (compileStep_pres c s c1 hc1).1, (compileStep_pres c s c1 hc1).2 hl⟩
theorem compileTotal : CompileTotal 2
Proof
:= compileTotal_any 2

One free move under Laid

One step of a stack or of the yarn keeps Laid and draws nothing.

Theorem Move Instructions
stackR_step a stack one needle right loopStep x true (stack_right_free)
stackL_step a stack one needle left loopStep x false (stack_left_free)
yarnR_step the yarn one slot right one miss .R
yarnL_step the yarn one slot left one miss .L
  • The order facts are read on the shadow row r.map shObj (cp_sh, sorted_sh, sorted_unsh). So the layout planner's far_of_sorted and sorted_set apply.
  • The needle loads use loadAt. A stack of s loops puts s loops on its needle. The yarn puts 0.

Loads and the shadow

theorem loadAt_set : ∀ (r : Row) (a : List Int) (j : Nat) (y i : Int), j < r.length → a.length = r.length →
    loadAt r (a.set j y) i + (if a.getD j 0 = i then stackSize (r.getD j .yarn) else 0) =
      loadAt r a i + (if y = i then stackSize (r.getD j .yarn) else 0)
Proof
  | [], _, _, _, _, h, _ => by simp at h
  | o :: r, [], _, _, _, _, h => by simp at h
  | o :: r, x :: a, 0, y, i, _, _ => by
    simp only [List.set_cons_zero, loadAt_cons, List.getD_cons_zero]; omega
  | o :: r, x :: a, j + 1, y, i, hj, ha => by
    simp only [List.set_cons_succ, loadAt_cons, List.getD_cons_succ]
    have := loadAt_set r a j y i (by simpa using hj) (by simpa using ha)
    omega
theorem loadAt_zero : ∀ (r : Row) (a : List Int) (i : Int),
    (∀ k, k < r.length → r.getD k .yarn ≠ .yarn → a.getD k 0 ≠ i) → loadAt r a i = 0
Proof
  | [], _, _, _ => by simp [loadAt]
  | _ :: _, [], _, _ => by simp [loadAt]
  | o :: r, x :: a, i, h => by
    rw [loadAt_cons, loadAt_zero r a i (fun k hk hl => by simpa using h (k + 1) (by simp; omega) (by simpa using hl))]
    have := h 0 (by simp)
    simp only [List.getD_cons_zero] at this
    cases o with
    | yarn => simp [stackSize]
    | stack s => rw [ite_eq_right (this (by simp))]
theorem cp_sh (r : Row) (a : List Int) (k : Nat) :
    cp (r.map shObj) a k = scpos (r.getD k .yarn) (a.getD k 0)
Proof
:= by
  simp only [cp, getD_sh, scpos_sh]
theorem sorted_sh {r : Row} {a : List Int}
    (h : ∀ k, k + 1 < r.length → scpos (r.getD k .yarn) (a.getD k 0) < scpos (r.getD (k + 1) .yarn) (a.getD (k + 1) 0)) :
    ∀ k, k + 1 < (r.map shObj).length → cp (r.map shObj) a k < cp (r.map shObj) a (k + 1)
Proof
:= by
  intro k hk; rw [cp_sh, cp_sh]; exact h k (by simpa using hk)
theorem sorted_unsh {r : Row} {a : List Int}
    (h : ∀ k, k + 1 < (r.map shObj).length → cp (r.map shObj) a k < cp (r.map shObj) a (k + 1)) :
    ∀ k, k + 1 < r.length → scpos (r.getD k .yarn) (a.getD k 0) < scpos (r.getD (k + 1) .yarn) (a.getD (k + 1) 0)
Proof
:= by
  intro k hk; rw [← cp_sh, ← cp_sh]; exact h k (by simpa using hk)
theorem laid_unfold {r : Row} {a : List Int} {o : List Op} {st : State} :
    Laid ⟨r, a, o⟩ st ↔ r.count .yarn = 1 ∧ a.length = r.length ∧ st.rack = 0 ∧ (∀ j, st.stk ⟨.b, j⟩ = []) ∧
      (∀ i, (st.stk ⟨.f, i⟩).length = loadAt r a i) ∧ st.carrier = a.getD (yarnIdx r) 0 ∧
      ∀ k, k + 1 < r.length → scpos (r.getD k .yarn) (a.getD k 0) < scpos (r.getD (k + 1) .yarn) (a.getD (k + 1) 0)
Proof
:=
  Iff.rfl
theorem shObj_stack (s : Nat) : shObj (.stack s) = .loop
Proof
:= rfl
theorem getD_sh_stack {r : Row} {j s : Nat} (h : r.getD j .yarn = .stack s) : (r.map shObj).getD j .yarn = .loop
Proof
:= by
  rw [getD_sh, h]; rfl
theorem getD_sh_yarn {r : Row} {j : Nat} (h : r.getD j .yarn = .yarn) : (r.map shObj).getD j .yarn = .yarn
Proof
:= by
  rw [getD_sh, h]; rfl
theorem cp_stack {r : Row} {a : List Int} {k : Nat} (h : r.getD k .yarn ≠ .yarn) :
    cp (r.map shObj) a k = 2 * a.getD k 0
Proof
:= by
  rw [cp_sh]; cases hk : r.getD k .yarn with
  | yarn => exact absurd hk h
  | stack s => rfl

One step

theorem stack_step_common {r : Row} {a : List Int} {st st' : State} {j s : Nat} {x y : Int}
    (hL : Laid ⟨r, a, []⟩ st) (hj : j < r.length) (hl : r.getD j .yarn = .stack s) (hx : a.getD j 0 = x)
    (hprev : 0 < j → cp (r.map shObj) a (j - 1) < 2 * y)
    (hnext : j + 1 < r.length → 2 * y < cp (r.map shObj) a (j + 1))
    (hxy : x ≠ y) (hfy : loadAt r a y = 0)
    (hr' : st'.rack = 0) (hc' : st'.carrier = st.carrier)
    (hk : ∀ q, st'.stk q = if q = ⟨.f, y⟩ then st.stk ⟨.f, x⟩ else if q = ⟨.f, x⟩ then [] else st.stk q) :
    Laid ⟨r, a.set j y, []⟩ st'
Proof
:= by
  rw [laid_unfold] at hL ⊢
  obtain ⟨hy, hlen, hr, hb, hf, hc, hs0⟩ := hL
  have hs := sorted_sh hs0
  have hlenR : (r.map shObj).length = r.length := by simp
  have hj' : j < a.length := by omega
  have hfar := far_of_sorted hs (by rw [hlenR]; exact hj) (v := 2 * y) hprev (by rw [hlenR]; exact hnext)
  have hpj : cp (r.map shObj) a j = 2 * x := by rw [cp_stack (by rw [hl]; simp), hx]
  obtain ⟨hyl, hyy⟩ := yarnIdx_spec hy
  have hyj : yarnIdx r ≠ j := by intro h; rw [h, hl] at hyy; cases hyy
  have hset := fun i => loadAt_set r a j y i hj hlen
  simp only [hl, hx, stackSize] at hset
  have hz : loadAt r (a.set j y) x = 0 := loadAt_zero r _ x (fun k hk hlk hak => by
    rw [getD_set_eq a j k y 0 hj'] at hak
    by_cases hkj : k = j
    · subst hkj; simp at hak; exact hxy hak.symm
    · simp only [hkj, ite_false] at hak
      have hpk : cp (r.map shObj) a k = 2 * x := by rw [cp_stack hlk, hak]
      rcases hfar k (by rw [hlenR]; exact hk) hkj with h | h <;> omega)
  refine ⟨hy, by simp [hlen], hr', fun i => ?_, fun i => ?_, ?_, sorted_unsh (sorted_set (by rw [hlenR]; exact hlen)
    hs (by rw [hlenR]; exact hj) ?_ ?_)⟩
  · rw [hk]; simp [hb]
  · rw [hk]
    have hne : ∀ u v : Int, u ≠ v → (⟨.f, u⟩ : Needle) ≠ ⟨.f, v⟩ := fun u v h e => h (congrArg Needle.idx e)
    by_cases hiy : i = y
    · rw [hiy, ite_eq_left rfl]
      have h1 := hset y
      have h2 := hset x
      rw [ite_eq_right hxy, ite_eq_left rfl, hfy] at h1
      rw [ite_eq_left rfl, ite_eq_right (Ne.symm hxy), hz] at h2
      rw [hf x]; omega
    · by_cases hix : i = x
      · rw [hix, ite_eq_right (hne x y hxy), ite_eq_left rfl, hz]; rfl
      · rw [ite_eq_right (hne i y hiy), ite_eq_right (hne i x hix), hf i]
        have h1 := hset i
        rw [ite_eq_right (Ne.symm hix), ite_eq_right (Ne.symm hiy)] at h1
        omega
  · rw [hc', hc, getD_set_eq a j _ y 0 hj', ite_eq_right hyj]
  · rw [getD_sh_stack hl, cpos_loop]; exact hprev
  · rw [getD_sh_stack hl, cpos_loop]; exact fun h => hnext (by simpa using h)
theorem stackR_step (win : Window) (r : Row) (a : List Int) (st : State) (j s : Nat) (x : Int)
    (hL : Laid ⟨r, a, []⟩ st) (hj : j < r.length) (hl : r.getD j .yarn = .stack s) (hx : a.getD j 0 = x)
    (hnext : j + 1 < r.length → 2 * (x + 1) < cp (r.map shObj) a (j + 1))
    (hin : win.inside x = true) (hin1 : win.inside (x + 1) = true) :
    ∃ st', denote win st (loopStep x true) = some (st', []) ∧ Laid ⟨r, a.set j (x + 1), []⟩ st'
Proof
:= by
  have hL' := hL
  rw [laid_unfold] at hL'
  obtain ⟨hy, hlen, hr, hb, hf, hc, hs0⟩ := hL'
  have hs := sorted_sh hs0
  have hlenR : (r.map shObj).length = r.length := by simp
  have hpj : cp (r.map shObj) a j = 2 * x := by rw [cp_stack (by rw [hl]; simp), hx]
  have hprev : 0 < j → cp (r.map shObj) a (j - 1) < 2 * (x + 1) := fun h => by
    have := hs (j - 1) (by rw [hlenR]; omega); rw [show j - 1 + 1 = j by omega] at this; omega
  have hfar := far_of_sorted hs (by rw [hlenR]; exact hj) hprev (by rw [hlenR]; exact hnext)
  obtain ⟨hyl, hyy⟩ := yarnIdx_spec hy
  have hyj : yarnIdx r ≠ j := by intro h; rw [h, hl] at hyy; cases hyy
  have hcar : st.carrier ≠ x + 1 := by
    rw [hc]; intro h
    have hpy : cp (r.map shObj) a (yarnIdx r) = 2 * (x + 1) - 1 := by
      rw [cp_sh, hyy, h]; rfl
    rcases hfar _ (by rw [hlenR]; exact hyl) hyj with h' | h' <;> omega
  have hcnt : loadAt r a (x + 1) = 0 := loadAt_zero r a (x + 1) (fun k hk hlk hak => by
    have hkj : k ≠ j := by rintro rfl; rw [hx] at hak; omega
    have hpk : cp (r.map shObj) a k = 2 * (x + 1) := by rw [cp_stack hlk, hak]
    rcases hfar k (by rw [hlenR]; exact hk) hkj with h' | h' <;> omega)
  have hf1 : st.stk ⟨.f, x + 1⟩ = [] := List.eq_nil_of_length_eq_zero (by rw [hf]; exact hcnt)
  obtain ⟨st', hd, hr', hc', hk⟩ := stack_right_free win st x hr hb hcar hf1 hin hin1
  exact ⟨st', hd, stack_step_common hL hj hl hx hprev hnext (by omega) hcnt hr' hc' hk⟩
theorem stackL_step (win : Window) (r : Row) (a : List Int) (st : State) (j s : Nat) (x : Int)
    (hL : Laid ⟨r, a, []⟩ st) (hj : j < r.length) (hl : r.getD j .yarn = .stack s) (hx : a.getD j 0 = x)
    (hprev : 0 < j → cp (r.map shObj) a (j - 1) < 2 * (x - 1))
    (hin : win.inside x = true) (hin1 : win.inside (x - 1) = true) :
    ∃ st', denote win st (loopStep x false) = some (st', []) ∧ Laid ⟨r, a.set j (x - 1), []⟩ st'
Proof
:= by
  have hL' := hL
  rw [laid_unfold] at hL'
  obtain ⟨hy, hlen, hr, hb, hf, hc, hs0⟩ := hL'
  have hs := sorted_sh hs0
  have hlenR : (r.map shObj).length = r.length := by simp
  have hpj : cp (r.map shObj) a j = 2 * x := by rw [cp_stack (by rw [hl]; simp), hx]
  have hnext : j + 1 < r.length → 2 * (x - 1) < cp (r.map shObj) a (j + 1) := fun h => by
    have := hs j (by rw [hlenR]; exact h); omega
  have hfar := far_of_sorted hs (by rw [hlenR]; exact hj) hprev (by rw [hlenR]; exact hnext)
  obtain ⟨hyl, hyy⟩ := yarnIdx_spec hy
  have hyj : yarnIdx r ≠ j := by intro h; rw [h, hl] at hyy; cases hyy
  have hcar : st.carrier ≠ x := by
    rw [hc]; intro h
    have hpy : cp (r.map shObj) a (yarnIdx r) = 2 * x - 1 := by
      rw [cp_sh, hyy, h]; rfl
    rcases hfar _ (by rw [hlenR]; exact hyl) hyj with h' | h' <;> omega
  have hcnt : loadAt r a (x - 1) = 0 := loadAt_zero r a (x - 1) (fun k hk hlk hak => by
    have hkj : k ≠ j := by rintro rfl; rw [hx] at hak; omega
    have hpk : cp (r.map shObj) a k = 2 * (x - 1) := by rw [cp_stack hlk, hak]
    rcases hfar k (by rw [hlenR]; exact hk) hkj with h' | h' <;> omega)
  have hf1 : st.stk ⟨.f, x - 1⟩ = [] := List.eq_nil_of_length_eq_zero (by rw [hf]; exact hcnt)
  obtain ⟨st', hd, hr', hc', hk⟩ := stack_left_free win st x hr hb hcar hf1 hin hin1
  exact ⟨st', hd, stack_step_common hL hj hl hx hprev hnext (by omega) hcnt hr' hc' hk⟩
theorem yarn_step_common {r : Row} {a : List Int} {st : State} {j : Nat} {y : Int}
    (hL : Laid ⟨r, a, []⟩ st) (hj : j < r.length) (hl : r.getD j .yarn = .yarn)
    (hprev : 0 < j → cp (r.map shObj) a (j - 1) < 2 * y - 1)
    (hnext : j + 1 < r.length → 2 * y - 1 < cp (r.map shObj) a (j + 1)) :
    Laid ⟨r, a.set j y, []⟩ { st with carrier
Proof
:= y } := by
  rw [laid_unfold] at hL ⊢
  obtain ⟨hy, hlen, hr, hb, hf, hc, hs0⟩ := hL
  have hs := sorted_sh hs0
  have hlenR : (r.map shObj).length = r.length := by simp
  have hj' : j < a.length := by omega
  refine ⟨hy, by simp [hlen], hr, hb, fun i => ?_, ?_, sorted_unsh (sorted_set (by rw [hlenR]; exact hlen) hs
    (by rw [hlenR]; exact hj) ?_ ?_)⟩
  · have := loadAt_set r a j y i hj hlen
    simp only [hl, stackSize, ite_self, add_zero] at this
    rw [this]; exact hf i
  · rw [yarnIdx_of hy hj hl, getD_set_eq a j j y 0 hj']; simp
  · rw [getD_sh_yarn hl, cpos_yarn]; exact hprev
  · rw [getD_sh_yarn hl, cpos_yarn]; exact fun h => hnext (by simpa using h)
theorem denote_single_miss {win : Window} {st st' : State} {d : Dir} {n : Needle}
    (h : denote1 win st [.miss d n] = some (st', [])) : denote win st [.miss d n] = some (st', [])
Proof
:=
  denote_of_denote1 win st _ st' [] (by simp [NotSplit]) h
theorem yarnR_step (win : Window) (r : Row) (a : List Int) (st : State) (j : Nat) (x : Int)
    (hL : Laid ⟨r, a, []⟩ st) (hj : j < r.length) (hl : r.getD j .yarn = .yarn) (hx : a.getD j 0 = x)
    (hnext : j + 1 < r.length → 2 * (x + 1) - 1 < cp (r.map shObj) a (j + 1)) (hin : win.inside x = true) :
    ∃ st', denote win st [.miss .R (fN x)] = some (st', []) ∧ Laid ⟨r, a.set j (x + 1), []⟩ st'
Proof
:= by
  have hL' := hL
  rw [laid_unfold] at hL'
  obtain ⟨hy, hlen, hr, hb, hf, hc, hs0⟩ := hL'
  have hs := sorted_sh hs0
  have hlenR : (r.map shObj).length = r.length := by simp
  have hpj : cp (r.map shObj) a j = 2 * x - 1 := by rw [cp_sh, hl, hx]; rfl
  have hprev : 0 < j → cp (r.map shObj) a (j - 1) < 2 * (x + 1) - 1 := fun h => by
    have := hs (j - 1) (by rw [hlenR]; omega); rw [show j - 1 + 1 = j by omega] at this; omega
  have hfar := far_of_sorted hs (by rw [hlenR]; exact hj) hprev (by rw [hlenR]; exact hnext)
  have hcar : st.carrier = x := by rw [hc, yarnIdx_of hy hj hl, hx]
  have hcnt : loadAt r a x = 0 := loadAt_zero r a x (fun k hk hlk hak => by
    have hkj : k ≠ j := by rintro rfl; exact hlk hl
    have hpk : cp (r.map shObj) a k = 2 * x := by rw [cp_stack hlk, hak]
    rcases hfar k (by rw [hlenR]; exact hk) hkj with h' | h' <;> omega)
  have hf1 : st.stk ⟨.f, x⟩ = [] := List.eq_nil_of_length_eq_zero (by rw [hf]; exact hcnt)
  have hstep : step1 st (.miss .R (fN x)) = .ok { st with carrier := x + 1 } := by
    refine step1_ok.mpr ⟨?_, ?_⟩
    · simp [validCrate, crateRefusal1, linRefusal, erase, slot, arrivesFrom, hr, hcar, crateExtra1, fN]
    · simp [apply, leavesTo, slot, hr, fN]
  have hw : windowOk win st (.miss .R (fN x)) = true := by simp [windowOk, slot, fN, hin]
  refine ⟨_, denote_single_miss ?_, yarn_step_common hL hj hl hprev hnext⟩
  rw [denote1_single hstep hw, miss_free win st .R (fN x) (by simp [frontAt, slot, fN, hf1])
    (by simp [backAt, slot, fN, hb])]
theorem yarnL_step (win : Window) (r : Row) (a : List Int) (st : State) (j : Nat) (x : Int)
    (hL : Laid ⟨r, a, []⟩ st) (hj : j < r.length) (hl : r.getD j .yarn = .yarn) (hx : a.getD j 0 = x)
    (hprev : 0 < j → cp (r.map shObj) a (j - 1) < 2 * (x - 1) - 1) (hin : win.inside (x - 1) = true) :
    ∃ st', denote win st [.miss .L (fN (x - 1))] = some (st', []) ∧ Laid ⟨r, a.set j (x - 1), []⟩ st'
Proof
:= by
  have hL' := hL
  rw [laid_unfold] at hL'
  obtain ⟨hy, hlen, hr, hb, hf, hc, hs0⟩ := hL'
  have hs := sorted_sh hs0
  have hlenR : (r.map shObj).length = r.length := by simp
  have hpj : cp (r.map shObj) a j = 2 * x - 1 := by rw [cp_sh, hl, hx]; rfl
  have hnext : j + 1 < r.length → 2 * (x - 1) - 1 < cp (r.map shObj) a (j + 1) := fun h => by
    have := hs j (by rw [hlenR]; exact h); omega
  have hfar := far_of_sorted hs (by rw [hlenR]; exact hj) hprev (by rw [hlenR]; exact hnext)
  have hcar : st.carrier = x := by rw [hc, yarnIdx_of hy hj hl, hx]
  have hcnt : loadAt r a (x - 1) = 0 := loadAt_zero r a (x - 1) (fun k hk hlk hak => by
    have hkj : k ≠ j := by rintro rfl; exact hlk hl
    have hpk : cp (r.map shObj) a k = 2 * (x - 1) := by rw [cp_stack hlk, hak]
    rcases hfar k (by rw [hlenR]; exact hk) hkj with h' | h' <;> omega)
  have hf1 : st.stk ⟨.f, x - 1⟩ = [] := List.eq_nil_of_length_eq_zero (by rw [hf]; exact hcnt)
  have hstep : step1 st (.miss .L (fN (x - 1))) = .ok { st with carrier := x - 1 } := by
    refine step1_ok.mpr ⟨?_, ?_⟩
    · simp [validCrate, crateRefusal1, linRefusal, erase, slot, arrivesFrom, hr, hcar, crateExtra1, fN]
    · simp [apply, leavesTo, slot, hr, fN]
  have hw : windowOk win st (.miss .L (fN (x - 1))) = true := by simp [windowOk, slot, fN, hin]
  refine ⟨_, denote_single_miss ?_, yarn_step_common hL hj hl hprev hnext⟩
  rw [denote1_single hstep hw, miss_free win st .L (fN (x - 1)) (by simp [frontAt, slot, fN, hf1])
    (by simp [backAt, slot, fN, hb])]

Walks and one whole moveObject under Laid

moveObject_free: one moveObject is accepted by step, draws nothing under denote, and ends laid out. The condition: the destination is strictly between the object's neighbours in the shadow cp order.

  • walkStackR, walkStackL: a stack moves m needles right or left, one step at a time.
  • walkYarnR, walkYarnL: the yarn moves m slots right or left, one miss at a time.
  • moveObject_ops: the instructions that moveObject appends.
namespace FormalizeKnitting.Bridge.RM
open FormalizeKnitting.Knitout FormalizeKnitting.Bridge.RM
open scoped List
theorem laid_len {r : Row} {a : List Int} {o : List Op} {st : State} (h : Laid ⟨r, a, o⟩ st) :
    a.length = r.length
Proof
:= h.2.1
theorem cp_set_ne' {r : Row} {a : List Int} {j k : Nat} {v : Int} (hj : j < a.length) (hk : k ≠ j) :
    cp (r.map shObj) (a.set j v) k = cp (r.map shObj) a k
Proof
:= cp_set_ne hj hk
theorem walkStackR (win : Window) (r : Row) (a : List Int) (st : State) (j s : Nat) (x : Int)
    (hL : Laid ⟨r, a, []⟩ st) (hj : j < r.length) (hl : r.getD j .yarn = .stack s) (hx : a.getD j 0 = x) :
    ∀ m : Nat, (j + 1 < r.length → 2 * (x + m) < cp (r.map shObj) a (j + 1)) →
      (∀ k < m, win.inside (x + k) = true ∧ win.inside (x + k + 1) = true) →
      ∃ st', denote win st ((List.range m).flatMap fun k : Nat => loopStep (x + (k : Int)) true) =
        some (st', []) ∧ Laid ⟨r, a.set j (x + m), []⟩ st'
Proof
  | 0, _, _ => by
    have hj' : j < a.length := by have := laid_len hL; omega
    have e : a.set j x = a := by rw [← hx]; exact set_getD_self a j 0 hj'
    refine ⟨st, by simp [denote], ?_⟩
    rw [show x + ((0 : Nat) : Int) = x by simp, e]; exact hL
  | m + 1, hn, hin => by
    obtain ⟨st1, hd1, hL1⟩ := walkStackR win r a st j s x hL hj hl hx m
      (fun h => by have := hn h; push_cast at this; omega) (fun k hk => hin k (by omega))
    have hj' : j < a.length := by have := laid_len hL; omega
    obtain ⟨st2, hd2, hL2⟩ := stackR_step win r (a.set j (x + m)) st1 j s (x + m) hL1 hj hl
      (by rw [getD_set_eq a j j _ 0 hj', ite_eq_left rfl])
      (fun h => by rw [cp_set_ne' hj' (show j + 1 ≠ j by omega)]; have := hn h; push_cast at this; omega)
      (hin m (by omega)).1 (hin m (by omega)).2
    refine ⟨st2, ?_, ?_⟩
    · simp only [List.range_succ, List.flatMap_append, List.flatMap_cons, List.flatMap_nil, List.append_nil]
      simpa using denote_append win st _ _ st1 st2 [] [] hd1 hd2
    · rw [List.set_set] at hL2
      have e : x + ((m + 1 : Nat) : Int) = x + m + 1 := by push_cast; omega
      rw [e]; exact hL2
theorem walkStackL (win : Window) (r : Row) (a : List Int) (st : State) (j s : Nat) (x : Int)
    (hL : Laid ⟨r, a, []⟩ st) (hj : j < r.length) (hl : r.getD j .yarn = .stack s) (hx : a.getD j 0 = x) :
    ∀ m : Nat, (0 < j → cp (r.map shObj) a (j - 1) < 2 * (x - m)) →
      (∀ k < m, win.inside (x - k) = true ∧ win.inside (x - k - 1) = true) →
      ∃ st', denote win st ((List.range m).flatMap fun k : Nat => loopStep (x - (k : Int)) false) =
        some (st', []) ∧ Laid ⟨r, a.set j (x - m), []⟩ st'
Proof
  | 0, _, _ => by
    have hj' : j < a.length := by have := laid_len hL; omega
    have e : a.set j x = a := by rw [← hx]; exact set_getD_self a j 0 hj'
    refine ⟨st, by simp [denote], ?_⟩
    rw [show x - ((0 : Nat) : Int) = x by simp, e]; exact hL
  | m + 1, hp, hin => by
    obtain ⟨st1, hd1, hL1⟩ := walkStackL win r a st j s x hL hj hl hx m
      (fun h => by have := hp h; push_cast at this; omega) (fun k hk => hin k (by omega))
    have hj' : j < a.length := by have := laid_len hL; omega
    obtain ⟨st2, hd2, hL2⟩ := stackL_step win r (a.set j (x - m)) st1 j s (x - m) hL1 hj hl
      (by rw [getD_set_eq a j j _ 0 hj', ite_eq_left rfl])
      (fun h => by rw [cp_set_ne' hj' (show j - 1 ≠ j by omega)]; have := hp h; push_cast at this; omega)
      (hin m (by omega)).1 (hin m (by omega)).2
    refine ⟨st2, ?_, ?_⟩
    · simp only [List.range_succ, List.flatMap_append, List.flatMap_cons, List.flatMap_nil, List.append_nil]
      simpa using denote_append win st _ _ st1 st2 [] [] hd1 hd2
    · rw [List.set_set] at hL2
      have e : x - ((m + 1 : Nat) : Int) = x - m - 1 := by push_cast; omega
      rw [e]; exact hL2
theorem walkYarnR (win : Window) (r : Row) (a : List Int) (st : State) (j : Nat) (x : Int)
    (hL : Laid ⟨r, a, []⟩ st) (hj : j < r.length) (hl : r.getD j .yarn = .yarn) (hx : a.getD j 0 = x) :
    ∀ m : Nat, (j + 1 < r.length → 2 * (x + m) - 1 < cp (r.map shObj) a (j + 1)) →
      (∀ k < m, win.inside (x + k) = true) →
      ∃ st', denote win st ((List.range m).map fun k : Nat => Op.miss .R (fN (x + (k : Int)))) =
        some (st', []) ∧ Laid ⟨r, a.set j (x + m), []⟩ st'
Proof
  | 0, _, _ => by
    have hj' : j < a.length := by have := laid_len hL; omega
    have e : a.set j x = a := by rw [← hx]; exact set_getD_self a j 0 hj'
    refine ⟨st, by simp [denote], ?_⟩
    rw [show x + ((0 : Nat) : Int) = x by simp, e]; exact hL
  | m + 1, hn, hin => by
    obtain ⟨st1, hd1, hL1⟩ := walkYarnR win r a st j x hL hj hl hx m
      (fun h => by have := hn h; push_cast at this; omega) (fun k hk => hin k (by omega))
    have hj' : j < a.length := by have := laid_len hL; omega
    obtain ⟨st2, hd2, hL2⟩ := yarnR_step win r (a.set j (x + m)) st1 j (x + m) hL1 hj hl
      (by rw [getD_set_eq a j j _ 0 hj', ite_eq_left rfl])
      (fun h => by rw [cp_set_ne' hj' (show j + 1 ≠ j by omega)]; have := hn h; push_cast at this; omega)
      (hin m (by omega))
    refine ⟨st2, ?_, ?_⟩
    · simp only [List.range_succ, List.map_append, List.map_cons, List.map_nil]
      simpa using denote_append win st _ _ st1 st2 [] [] hd1 hd2
    · rw [List.set_set] at hL2
      have e : x + ((m + 1 : Nat) : Int) = x + m + 1 := by push_cast; omega
      rw [e]; exact hL2
theorem walkYarnL (win : Window) (r : Row) (a : List Int) (st : State) (j : Nat) (x : Int)
    (hL : Laid ⟨r, a, []⟩ st) (hj : j < r.length) (hl : r.getD j .yarn = .yarn) (hx : a.getD j 0 = x) :
    ∀ m : Nat, (0 < j → cp (r.map shObj) a (j - 1) < 2 * (x - m) - 1) →
      (∀ k < m, win.inside (x - 1 - k) = true) →
      ∃ st', denote win st ((List.range m).map fun k : Nat => Op.miss .L (fN (x - 1 - (k : Int)))) =
        some (st', []) ∧ Laid ⟨r, a.set j (x - m), []⟩ st'
Proof
  | 0, _, _ => by
    have hj' : j < a.length := by have := laid_len hL; omega
    have e : a.set j x = a := by rw [← hx]; exact set_getD_self a j 0 hj'
    refine ⟨st, by simp [denote], ?_⟩
    rw [show x - ((0 : Nat) : Int) = x by simp, e]; exact hL
  | m + 1, hp, hin => by
    obtain ⟨st1, hd1, hL1⟩ := walkYarnL win r a st j x hL hj hl hx m
      (fun h => by have := hp h; push_cast at this; omega) (fun k hk => hin k (by omega))
    have hj' : j < a.length := by have := laid_len hL; omega
    have e1 : x - m - 1 = x - 1 - m := by omega
    obtain ⟨st2, hd2, hL2⟩ := yarnL_step win r (a.set j (x - m)) st1 j (x - m) hL1 hj hl
      (by rw [getD_set_eq a j j _ 0 hj', ite_eq_left rfl])
      (fun h => by rw [cp_set_ne' hj' (show j - 1 ≠ j by omega)]; have := hp h; push_cast at this; omega)
      (by rw [e1]; exact hin m (by omega))
    rw [e1] at hd2
    refine ⟨st2, ?_, ?_⟩
    · simp only [List.range_succ, List.map_append, List.map_cons, List.map_nil]
      simpa using denote_append win st _ _ st1 st2 [] [] hd1 hd2
    · rw [List.set_set, e1] at hL2
      have e : x - ((m + 1 : Nat) : Int) = x - 1 - m := by push_cast; omega
      rw [e]; exact hL2
theorem moveObject_ops (c : Comp) (j : Nat) (dest : Int) :
    (moveObject c j dest).ops = c.ops ++
      (if c.row.getD j .yarn = .yarn then
        (if c.at_.getD j 0 < dest then
          (List.range (dest - c.at_.getD j 0).toNat).map (fun k : Nat => Op.miss .R (fN (c.at_.getD j 0 + (k : Int))))
         else (List.range (c.at_.getD j 0 - dest).toNat).map
          (fun k : Nat => Op.miss .L (fN (c.at_.getD j 0 - 1 - (k : Int)))))
      else if c.at_.getD j 0 < dest then
        (List.range (dest - c.at_.getD j 0).toNat).flatMap (fun k : Nat => loopStep (c.at_.getD j 0 + (k : Int)) true)
      else (List.range (c.at_.getD j 0 - dest).toNat).flatMap
        (fun k : Nat => loopStep (c.at_.getD j 0 - (k : Int)) false))
Proof
:= by
  show c.ops ++ _ = _
  congr 1
  unfold yarnTo
  split_ifs <;> simp [flatMap_single, List.flatMap_map]
theorem moveObject_free (win : Window) (c : Comp) (st : State) (j : Nat) (dest : Int)
    (hL : Laid c st) (hj : j < c.row.length)
    (hprev : 0 < j → cp (c.row.map shObj) c.at_ (j - 1) < cpos ((c.row.map shObj).getD j .yarn) dest)
    (hnext : j + 1 < c.row.length → cpos ((c.row.map shObj).getD j .yarn) dest < cp (c.row.map shObj) c.at_ (j + 1))
    (hN : ∀ op ∈ (moveObject c j dest).ops, NamedIn3 win op) :
    (∃ st', denote win st ((moveObject c j dest).ops.drop c.ops.length) = some (st', []) ∧
      Laid (moveObject c j dest) st') ∧
    (dest = c.at_.getD j 0 ∨ (win.lo + 2 ≤ dest ∧ dest + 2 < win.lo + win.w))
Proof
:= by
  obtain ⟨r, a, o⟩ := c
  have hL0 : Laid ⟨r, a, []⟩ st := hL
  have hfin : ∀ st', Laid ⟨r, a.set j dest, []⟩ st' → Laid (moveObject ⟨r, a, o⟩ j dest) st' := fun _ h => h
  have hN' := fun op h => hN op (by rw [moveObject_ops]; exact List.mem_append_right _ h)
  rw [moveObject_ops, List.drop_left]
  simp only at hj hprev hnext hN' ⊢
  generalize hx : a.getD j 0 = x at hN' ⊢
  cases ho : r.getD j .yarn with
  | yarn =>
    rw [getD_sh_yarn ho, cpos_yarn] at hprev hnext
    rw [ho, ite_eq_left rfl] at hN'
    rw [ite_eq_left rfl]
    by_cases hlt : x < dest
    · rw [ite_eq_left hlt] at hN' ⊢
      obtain ⟨m, hm⟩ : ∃ m : Nat, (dest - x).toNat = m := ⟨_, rfl⟩
      rw [hm] at hN' ⊢
      obtain ⟨st', hd, hL'⟩ := walkYarnR win r a st j x hL0 hj ho hx m (fun h => by have := hnext h; omega)
        (fun k hk => inside_of_named (hN' _ (List.mem_map.mpr ⟨k, List.mem_range.mpr hk, rfl⟩))
          (by simp [Op.named, fN]))
      refine ⟨⟨st', hd, hfin _ (by rwa [show x + (m : Int) = dest by omega] at hL')⟩, Or.inr ?_⟩
      have := hN' _ (List.mem_map.mpr ⟨m - 1, List.mem_range.mpr (by omega), rfl⟩) (x + ((m - 1 : Nat) : Int))
        (by simp [Op.named, fN])
      omega
    · rw [ite_eq_right hlt] at hN' ⊢
      obtain ⟨m, hm⟩ : ∃ m : Nat, (x - dest).toNat = m := ⟨_, rfl⟩
      rw [hm] at hN' ⊢
      obtain ⟨st', hd, hL'⟩ := walkYarnL win r a st j x hL0 hj ho hx m (fun h => by have := hprev h; omega)
        (fun k hk => inside_of_named (hN' _ (List.mem_map.mpr ⟨k, List.mem_range.mpr hk, rfl⟩))
          (by simp [Op.named, fN]))
      refine ⟨⟨st', hd, hfin _ (by rwa [show x - (m : Int) = dest by omega] at hL')⟩, ?_⟩
      rcases Nat.eq_zero_or_pos m with h0 | h0
      · left; omega
      · right
        have := hN' _ (List.mem_map.mpr ⟨m - 1, List.mem_range.mpr (by omega), rfl⟩)
          (x - 1 - ((m - 1 : Nat) : Int)) (by simp [Op.named, fN])
        omega
  | stack s =>
    rw [getD_sh_stack ho, cpos_loop] at hprev hnext
    rw [ho, ite_eq_right (by simp)] at hN'
    rw [ite_eq_right (by simp)]
    by_cases hlt : x < dest
    · rw [ite_eq_left hlt] at hN' ⊢
      obtain ⟨m, hm⟩ : ∃ m : Nat, (dest - x).toNat = m := ⟨_, rfl⟩
      rw [hm] at hN' ⊢
      have hmem : ∀ k < m, Op.xfer (bN (x + k)) (fN (x + k + 1)) ∈
          (List.range m).flatMap (fun k : Nat => loopStep (x + (k : Int)) true) := fun k hk =>
        List.mem_flatMap.mpr ⟨k, List.mem_range.mpr hk, by simp [loopStep]⟩
      obtain ⟨st', hd, hL'⟩ := walkStackR win r a st j s x hL0 hj ho hx m (fun h => by have := hnext h; omega)
        (fun k hk => ⟨inside_of_named (hN' _ (hmem k hk)) (by simp [Op.named, fN, bN]),
          inside_of_named (hN' _ (hmem k hk)) (by simp [Op.named, fN, bN])⟩)
      refine ⟨⟨st', hd, hfin _ (by rwa [show x + (m : Int) = dest by omega] at hL')⟩, Or.inr ?_⟩
      have := hN' _ (hmem (m - 1) (by omega)) (x + ((m - 1 : Nat) : Int) + 1) (by simp [Op.named, fN, bN])
      omega
    · rw [ite_eq_right hlt] at hN' ⊢
      obtain ⟨m, hm⟩ : ∃ m : Nat, (x - dest).toNat = m := ⟨_, rfl⟩
      rw [hm] at hN' ⊢
      have hmem : ∀ k < m, Op.xfer (bN (x - k)) (fN (x - k - 1)) ∈
          (List.range m).flatMap (fun k : Nat => loopStep (x - (k : Int)) false) := fun k hk =>
        List.mem_flatMap.mpr ⟨k, List.mem_range.mpr hk, by simp [loopStep]⟩
      obtain ⟨st', hd, hL'⟩ := walkStackL win r a st j s x hL0 hj ho hx m (fun h => by have := hprev h; omega)
        (fun k hk => ⟨inside_of_named (hN' _ (hmem k hk)) (by simp [Op.named, fN, bN]),
          inside_of_named (hN' _ (hmem k hk)) (by simp [Op.named, fN, bN])⟩)
      refine ⟨⟨st', hd, hfin _ (by rwa [show x - (m : Int) = dest by omega] at hL')⟩, ?_⟩
      rcases Nat.eq_zero_or_pos m with h0 | h0
      · left; omega
      · right
        have := hN' _ (hmem (m - 1) (by omega)) (x - ((m - 1 : Nat) : Int) - 1) (by simp [Op.named, fN, bN])
        omega

Arrange draws nothing

arrangeFree : ArrangeFree. From a laid-out state, arrange's moves are accepted, draw nothing, and end laid out.

  • arrange c t is arrange1 (sh c) t read back (arrange_sh).
  • So the two folds run on the shadow. The layout planner's ar1, ar2, char1, char2 and their step lemmas apply. The order argument is the same: the objects that move right go first, rightmost first; then the objects that move left, leftmost first.
  • Inv1, Inv2: the invariants of the two folds. Their state part is Laid of the stack state ⟨c.row, c''.at_, c''.ops⟩.
  • move_step: each move is moveObject_free through moveObject_sh.
  • fold1_free, fold2_free: the two folds keep Inv1 and Inv2.
namespace FormalizeKnitting.Bridge.RM
open FormalizeKnitting.Knitout FormalizeKnitting.Bridge.RM
open scoped List
theorem move_step (win : Window) (r : Row) (A : List Int) (O : List Op) (st1 : State) (m : Nat) (d : Int)
    (hL : Laid ⟨r, A, O⟩ st1) (hm : m < r.length)
    (hprev : 0 < m → cp (r.map shObj) A (m - 1) < cpos ((r.map shObj).getD m .yarn) d)
    (hnext : m + 1 < r.length → cpos ((r.map shObj).getD m .yarn) d < cp (r.map shObj) A (m + 1))
    (hF : Fits1 win ⟨r.map shObj, A, O⟩)
    (hN : ∀ op ∈ (moveObject1 ⟨r.map shObj, A, O⟩ m d).ops, NamedIn3 win op) :
    Fits1 win (moveObject1 ⟨r.map shObj, A, O⟩ m d) ∧ ∃ st2,
      denote win st1 ((moveObject1 ⟨r.map shObj, A, O⟩ m d).ops.drop O.length) = some (st2, []) ∧
      Laid ⟨r, (moveObject1 ⟨r.map shObj, A, O⟩ m d).at_, (moveObject1 ⟨r.map shObj, A, O⟩ m d).ops⟩ st2
Proof
:= by
  have e : moveObject1 ⟨r.map shObj, A, O⟩ m d = sh (moveObject ⟨r, A, O⟩ m d) := moveObject_sh ⟨r, A, O⟩ m d
  rw [e] at hN ⊢
  obtain ⟨⟨st2, hd, hL2⟩, hfit⟩ := moveObject_free win ⟨r, A, O⟩ st1 m d hL hm hprev hnext hN
  refine ⟨fits_set (c' := ⟨r.map shObj, A, O⟩) hF (by have := laid_len hL; simp; omega) hfit, st2, hd, hL2⟩
def Inv1 (win : Window) (c : Comp) (t : List Int) (st : State) (c'' : Comp1) (m : Nat) : Prop :=
  c''.row = (sh c).row ∧ (sh c).ops <+: c''.ops ∧ char1 (sh c) t c'' m ∧ Fits1 win c'' ∧
    ∃ st', denote win st (c''.ops.drop c.ops.length) = some (st', []) ∧ Laid ⟨c.row, c''.at_, c''.ops⟩ st'

def Inv2 (win : Window) (c : Comp) (t : List Int) (st : State) (c'' : Comp1) (m : Nat) : Prop :=
  c''.row = (sh c).row ∧ (sh c).ops <+: c''.ops ∧ char2 (sh c) t c'' m ∧ Fits1 win c'' ∧
    ∃ st', denote win st (c''.ops.drop c.ops.length) = some (st', []) ∧ Laid ⟨c.row, c''.at_, c''.ops⟩ st'
theorem orig_sorted {c : Comp} {st : State} (hL : Laid c st) :
    ∀ k, k + 1 < (sh c).row.length → cp (sh c).row (sh c).at_ k < cp (sh c).row (sh c).at_ (k + 1)
Proof
:=
  sorted_sh hL.2.2.2.2.2.2
theorem sh_row_length (c : Comp) : (sh c).row.length = c.row.length
Proof
:= by simp [sh]
theorem inv1_step {win : Window} {c : Comp} {t : List Int} {st : State} (hL : Laid c st)
    (hsT : ∀ j, j + 1 < (sh c).row.length → cp (sh c).row t j < cp (sh c).row t (j + 1)) {c' : Comp1} {m : Nat}
    (hm : m < (sh c).row.length) (hI : Inv1 win c t st c' (m + 1))
    (hN : ∀ op ∈ (ar1 (sh c) t c' m).ops, NamedIn3 win op) :
    Inv1 win c t st (ar1 (sh c) t c' m) m
Proof
:= by
  obtain ⟨hrow, hpre, hch, hF, st1, hd1, hL1⟩ := hI
  have hlen : c'.at_.length = (sh c).row.length := by rw [sh_row_length]; exact laid_len hL1
  have hS := orig_sorted hL
  suffices H : Fits1 win (ar1 (sh c) t c' m) ∧ ∃ st2, denote win st1
      ((ar1 (sh c) t c' m).ops.drop c'.ops.length) = some (st2, []) ∧
      Laid ⟨c.row, (ar1 (sh c) t c' m).at_, (ar1 (sh c) t c' m).ops⟩ st2 by
    obtain ⟨hF2, st2, hd2, hL2⟩ := H
    refine ⟨(ar1_row _ t c' m).trans hrow, hpre.trans (ar1_prefix _ t c' m), char_step1 hlen hm hch, hF2, st2, ?_,
      hL2⟩
    have hpre' : c.ops <+: c'.ops := hpre
    rw [drop_trans hpre' (ar1_prefix _ t c' m)]
    simpa using denote_append win st _ _ st1 st2 [] [] hd1 hd2
  have hN' := hN
  unfold ar1 at hN' ⊢
  split_ifs with hP
  · have hprev : 0 < m → cp c'.row c'.at_ (m - 1) < cpos (c'.row.getD m .yarn) (t.getD m 0) := fun h => by
      have e : cp (sh c).row c'.at_ (m - 1) = cp (sh c).row (sh c).at_ (m - 1) := by
        simp only [cp]; rw [hch (m - 1) (by omega), ite_eq_right (fun h' => by omega)]
      rw [hrow, e]
      have := hS (m - 1) (by omega); rw [show m - 1 + 1 = m by omega] at this
      exact lt_trans this hP
    have hnext : m + 1 < c'.row.length → cpos (c'.row.getD m .yarn) (t.getD m 0) < cp c'.row c'.at_ (m + 1) := by
      intro h
      rw [hrow] at h ⊢
      have ht := hsT m h
      have hv : cp (sh c).row c'.at_ (m + 1) = cpos ((sh c).row.getD (m + 1) .yarn) (c'.at_.getD (m + 1) 0) := rfl
      rw [hv, hch (m + 1) h]
      by_cases hP1 : cp (sh c).row (sh c).at_ (m + 1) < cp (sh c).row t (m + 1)
      · rw [ite_eq_left ⟨le_refl _, hP1⟩]; exact ht
      · rw [ite_eq_right (fun h' => hP1 h'.2)]
        exact lt_of_lt_of_le ht (not_lt.mp hP1)
    obtain ⟨R, A, O⟩ := c'
    simp only at hrow
    subst hrow
    exact move_step win c.row A O st1 m (t.getD m 0) hL1 (by simpa [sh] using hm) hprev
      (fun h => hnext (by simpa [sh] using h)) hF (by rwa [ite_eq_left hP] at hN')
  · exact ⟨hF, st1, by simp [denote], hL1⟩
theorem inv2_step {win : Window} {c : Comp} {t : List Int} {st : State} (hL : Laid c st)
    (hsT : ∀ j, j + 1 < (sh c).row.length → cp (sh c).row t j < cp (sh c).row t (j + 1)) {c' : Comp1} {m : Nat}
    (hm : m < (sh c).row.length) (hI : Inv2 win c t st c' m)
    (hN : ∀ op ∈ (ar2 (sh c) t c' m).ops, NamedIn3 win op) :
    Inv2 win c t st (ar2 (sh c) t c' m) (m + 1)
Proof
:= by
  obtain ⟨hrow, hpre, hch, hF, st1, hd1, hL1⟩ := hI
  have hlen : c'.at_.length = (sh c).row.length := by rw [sh_row_length]; exact laid_len hL1
  have hS := orig_sorted hL
  suffices H : Fits1 win (ar2 (sh c) t c' m) ∧ ∃ st2, denote win st1
      ((ar2 (sh c) t c' m).ops.drop c'.ops.length) = some (st2, []) ∧
      Laid ⟨c.row, (ar2 (sh c) t c' m).at_, (ar2 (sh c) t c' m).ops⟩ st2 by
    obtain ⟨hF2, st2, hd2, hL2⟩ := H
    refine ⟨(ar2_row _ t c' m).trans hrow, hpre.trans (ar2_prefix _ t c' m), char_step2 hlen hm hch, hF2, st2, ?_,
      hL2⟩
    have hpre' : c.ops <+: c'.ops := hpre
    rw [drop_trans hpre' (ar2_prefix _ t c' m)]
    simpa using denote_append win st _ _ st1 st2 [] [] hd1 hd2
  have hN' := hN
  unfold ar2 at hN' ⊢
  split_ifs with hP
  · have hprev : 0 < m → cp c'.row c'.at_ (m - 1) < cpos (c'.row.getD m .yarn) (t.getD m 0) := fun h => by
      rw [hrow]
      have ht := hsT (m - 1) (by omega); rw [show m - 1 + 1 = m by omega] at ht
      have hv : cp (sh c).row c'.at_ (m - 1) = cpos ((sh c).row.getD (m - 1) .yarn) (c'.at_.getD (m - 1) 0) := rfl
      rw [hv, hch (m - 1) (by omega)]
      split_ifs with hQ
      · exact ht
      · have e : cp (sh c).row (sh c).at_ (m - 1) = cp (sh c).row t (m - 1) := by
          rcases lt_trichotomy (cp (sh c).row (sh c).at_ (m - 1)) (cp (sh c).row t (m - 1)) with h1 | h1 | h1
          · exact absurd (Or.inl h1) hQ
          · exact h1
          · exact absurd (Or.inr ⟨by omega, h1⟩) hQ
        show cp (sh c).row (sh c).at_ (m - 1) < _
        rw [e]; exact ht
    have hnext : m + 1 < c'.row.length → cpos (c'.row.getD m .yarn) (t.getD m 0) < cp c'.row c'.at_ (m + 1) := by
      intro h
      rw [hrow] at h ⊢
      have hv : cp (sh c).row c'.at_ (m + 1) = cpos ((sh c).row.getD (m + 1) .yarn) (c'.at_.getD (m + 1) 0) := rfl
      rw [hv, hch (m + 1) h]
      by_cases hP1 : cp (sh c).row (sh c).at_ (m + 1) < cp (sh c).row t (m + 1)
      · rw [ite_eq_left (Or.inl hP1)]; exact hsT m h
      · rw [ite_eq_right (fun h' => h'.elim hP1 (fun h'' => by omega))]
        exact lt_trans hP (hS m h)
    obtain ⟨R, A, O⟩ := c'
    simp only at hrow
    subst hrow
    exact move_step win c.row A O st1 m (t.getD m 0) hL1 (by simpa [sh] using hm) hprev
      (fun h => hnext (by simpa [sh] using h)) hF (by rwa [ite_eq_left hP] at hN')
  · exact ⟨hF, st1, by simp [denote], hL1⟩
theorem fold1_free {win : Window} {c : Comp} {t : List Int} {st : State} (hL : Laid c st)
    (hsT : ∀ j, j + 1 < (sh c).row.length → cp (sh c).row t j < cp (sh c).row t (j + 1)) :
    ∀ m, m ≤ (sh c).row.length → ∀ c', Inv1 win c t st c' m →
      (∀ op ∈ ((List.range m).reverse.foldl (ar1 (sh c) t) c').ops, NamedIn3 win op) →
      Inv1 win c t st ((List.range m).reverse.foldl (ar1 (sh c) t) c') 0
Proof
  | 0, _, c', h, _ => by simpa using h
  | m + 1, hm, c', h, hN => by
    have e : (List.range (m + 1)).reverse = m :: (List.range m).reverse := by simp [List.range_succ]
    rw [e, List.foldl_cons] at hN ⊢
    have hpre := (foldl_row_prefix (ar1 (sh c) t) (fun c' j => ⟨ar1_row _ t c' j, ar1_prefix _ t c' j⟩)
      (List.range m).reverse (ar1 (sh c) t c' m)).2
    exact fold1_free hL hsT m (by omega) _ (inv1_step hL hsT (by omega) h (fun op ho => hN op (hpre.subset ho))) hN
theorem fold2_free {win : Window} {c : Comp} {t : List Int} {st : State} (hL : Laid c st)
    (hsT : ∀ j, j + 1 < (sh c).row.length → cp (sh c).row t j < cp (sh c).row t (j + 1)) :
    ∀ k s, s + k = (sh c).row.length → ∀ c', Inv2 win c t st c' s →
      (∀ op ∈ ((List.range' s k).foldl (ar2 (sh c) t) c').ops, NamedIn3 win op) →
      Inv2 win c t st ((List.range' s k).foldl (ar2 (sh c) t) c') (sh c).row.length
Proof
  | 0, s, hs, c', h, _ => by simp only [List.range'_zero, List.foldl_nil]; rw [← hs]; simpa using h
  | k + 1, s, hs, c', h, hN => by
    rw [List.range'_succ, List.foldl_cons] at hN ⊢
    have hpre := (foldl_row_prefix (ar2 (sh c) t) (fun c' j => ⟨ar2_row _ t c' j, ar2_prefix _ t c' j⟩)
      (List.range' (s + 1) k) (ar2 (sh c) t c' s)).2
    exact fold2_free hL hsT k (s + 1) (by omega) _
      (inv2_step hL hsT (by omega) h (fun op ho => hN op (hpre.subset ho))) hN
theorem arrangeFree : ArrangeFree
Proof
:= by
  intro win c c' t st hL hF ha _ hN
  have hrow' : c'.row = c.row := arrange_row ha
  have ha' : arrange1 (sh c) t = some (sh c') := by rw [arrange_sh, ha]; rfl
  rw [arrange1_def] at ha'
  split_ifs at ha' with hcond
  obtain ⟨_, hall⟩ := hcond
  have hsT := sorted_of_all hall
  simp only [Option.some.injEq] at ha'
  set c1 := (List.range (sh c).row.length).reverse.foldl (ar1 (sh c) t) (sh c) with hc1
  have hN2 : ∀ op ∈ ((List.range (sh c).row.length).foldl (ar2 (sh c) t) c1).ops, NamedIn3 win op := by
    rw [ha']; exact hN
  have hpre2 := (foldl_row_prefix (ar2 (sh c) t) (fun c' j => ⟨ar2_row _ t c' j, ar2_prefix _ t c' j⟩)
    (List.range (sh c).row.length) c1).2
  have h0 : Inv1 win c t st (sh c) (sh c).row.length :=
    ⟨rfl, List.prefix_refl _, fun i hi => by rw [ite_eq_right (fun h => by omega)], hF, st, by simp [denote, sh], hL⟩
  obtain ⟨hr1, hp1, hch1, hF1, st1, hd1, hL1⟩ :=
    fold1_free hL hsT (sh c).row.length (le_refl _) (sh c) h0 (fun op ho => hN2 op (hpre2.subset ho))
  have h2 : Inv2 win c t st c1 0 := by
    refine ⟨hr1, hp1, fun i hi => ?_, hF1, st1, hd1, hL1⟩
    rw [hch1 i hi]
    by_cases hP : cp (sh c).row (sh c).at_ i < cp (sh c).row t i
    · rw [ite_eq_left ⟨Nat.zero_le _, hP⟩, ite_eq_left (Or.inl hP)]
    · rw [ite_eq_right (fun h => hP h.2), ite_eq_right (fun h => h.elim hP (fun h' => by omega))]
  rw [List.range_eq_range'] at hN2
  obtain ⟨_, _, _, hF2, st2, hd2, hL2⟩ := fold2_free hL hsT (sh c).row.length 0 (by omega) c1 h2 hN2
  rw [← List.range_eq_range', ha'] at hF2 hd2 hL2
  refine ⟨hF2, st2, hd2, ?_⟩
  obtain ⟨r', a', o'⟩ := c'
  simp only at hrow'
  subst hrow'
  exact hL2

Reading a laid-out stack machine

The reading lemmas for stacks, and the splice lemmas that give Laid and Fits again after a step.

Under Laid c st with c.at_ = canonical 2 n, object j is at position 3 + 2j:

Object At position 3 + 2j Strands
a stack of k k loops on front needle 3 + 2j 2k
the yarn the carrier in slot 3 + 2j 1
  • Every other position is empty (laid_front_off, segW_off).
  • strandsBefore_canon: the strands left of object m's position are offset c.row m.
  • order_splice, laid_splice, fits_splice: order, Laid and Fits after a splice of the row.
  • stackAt_some, stackAt_none: what stackAt tells about the row.

Loads of the canonical layout

def canonFrom (m n : Nat) : List Int := (List.range n).map fun j => 3 + 2 * ((m + j : Nat) : Int)
theorem canonFrom_succ (m n : Nat) : canonFrom m (n + 1) = (3 + 2 * (m : Int)) :: canonFrom (m + 1) n
Proof
:= by
  unfold canonFrom
  rw [List.range_succ_eq_map, List.map_cons, List.map_map]
  congr 1
  simp
  intro a _; omega
theorem canonical_two_eq (n : Nat) : canonical 2 n = canonFrom 0 n
Proof
:= by
  apply List.ext_getElem (by rw [canonical_length]; simp [canonFrom])
  intro j h1 h2
  have := canonical_getD_two (n := n) (j := j) (by rw [canonical_length] at h1; exact h1)
  rw [getD_of_lt h1] at this; rw [this]; simp [canonFrom]
theorem loadAt_nil (a : List Int) (i : Int) : loadAt [] a i = 0
Proof
:= by simp [loadAt]
theorem loadAt_canonFrom_off : ∀ (r : Row) (m : Nat) (i : Int), (∀ j : Nat, i ≠ 3 + 2 * ((m + j : Nat) : Int)) →
    loadAt r (canonFrom m r.length) i = 0
Proof
  | [], _, _, _ => loadAt_nil _ _
  | o :: r, m, i, h => by
    rw [List.length_cons, canonFrom_succ, loadAt_cons, loadAt_canonFrom_off r (m + 1) i (fun j => by
      have := h (j + 1); push_cast at this ⊢; omega)]
    have := h 0; simp at this; rw [ite_eq_right (Ne.symm this)]
theorem loadAt_canonFrom_at : ∀ (r : Row) (m j : Nat),
    loadAt r (canonFrom m r.length) (3 + 2 * ((m + j : Nat) : Int)) = stackSize (r.getD j .yarn)
Proof
  | [], _, _ => by simp [loadAt_nil, stackSize]
  | o :: r, m, 0 => by
    rw [List.length_cons, canonFrom_succ, loadAt_cons, loadAt_canonFrom_off r (m + 1) _ (fun j => by push_cast; omega)]
    simp
  | o :: r, m, j + 1 => by
    rw [List.length_cons, canonFrom_succ, loadAt_cons, ite_eq_right (by push_cast; omega)]
    have := loadAt_canonFrom_at r (m + 1) j
    rw [show m + 1 + j = m + (j + 1) by omega] at this
    rw [this]; simp
theorem loadAt_canon_at (r : Row) (j : Nat) :
    loadAt r (canonical 2 r.length) (3 + 2 * (j : Int)) = stackSize (r.getD j .yarn)
Proof
:= by
  rw [canonical_two_eq]; have := loadAt_canonFrom_at r 0 j; simpa using this
theorem loadAt_canon_off (r : Row) (i : Int) (hi : ∀ j : Nat, i ≠ 3 + 2 * (j : Int)) :
    loadAt r (canonical 2 r.length) i = 0
Proof
:= by
  rw [canonical_two_eq]; exact loadAt_canonFrom_off r 0 i (fun j => by simpa using hi j)
theorem loadAt_spliceL (r : Row) (a : List Int) (hl : r.length = a.length) (f len : Nat) (N : Row)
    (NA : List Int) (hN : N.length = NA.length) (i : Int) :
    loadAt (spliceL r f len N) (spliceL a f len NA) i + loadAt ((r.drop f).take len) ((a.drop f).take len) i =
      loadAt r a i + loadAt N NA i
Proof
:= by
  have e1 : r = r.take f ++ ((r.drop f).take len ++ r.drop (f + len)) := by
    rw [← List.drop_drop, List.take_append_drop, List.take_append_drop]
  have e2 : a = a.take f ++ ((a.drop f).take len ++ a.drop (f + len)) := by
    rw [← List.drop_drop, List.take_append_drop, List.take_append_drop]
  have h1 : loadAt r a i = loadAt (r.take f) (a.take f) i + (loadAt ((r.drop f).take len) ((a.drop f).take len) i +
      loadAt (r.drop (f + len)) (a.drop (f + len)) i) := by
    conv_lhs => rw [e1, e2]
    rw [loadAt_append (by simp [hl]), loadAt_append (by simp [hl])]
  unfold spliceL
  rw [loadAt_append (by simp [hl, hN]), loadAt_append (by simp [hl]), h1]
  omega

One yarn

theorem two_yarns {r : Row} {i j : Nat} (hij : i < j) (hj : j < r.length) (hi : r[i]'(by omega) = .yarn)
    (hj' : r[j] = .yarn) : 2 ≤ r.count .yarn
Proof
:= by
  have e : r = r.take j ++ r.drop j := (List.take_append_drop j r).symm
  have h1 : Obj.yarn ∈ r.take j := by
    rw [List.mem_iff_getElem]; exact ⟨i, by simp; omega, by simp [hi]⟩
  have h2 : Obj.yarn ∈ r.drop j := by
    rw [List.mem_iff_getElem]; exact ⟨0, by simp; omega, by simp [hj']⟩
  have := List.count_append (a := Obj.yarn) (l₁ := r.take j) (l₂ := r.drop j)
  rw [← e] at this
  have c1 := List.count_pos_iff.mpr h1
  have c2 := List.count_pos_iff.mpr h2
  omega
theorem yarnIdx_lt {r : Row} (hy : r.count .yarn = 1) : yarnIdx r < r.length
Proof
:=
  List.idxOf_lt_length_iff.mpr (List.count_pos_iff.mp (by omega))
theorem getD_eq_yarn_iff {r : Row} (hy : r.count .yarn = 1) {j : Nat} (hj : j < r.length) :
    r.getD j .yarn = .yarn ↔ j = yarnIdx r
Proof
:= by
  have hlt := yarnIdx_lt hy
  have hget : r[yarnIdx r] = .yarn := List.getElem_idxOf hlt
  constructor
  · intro h
    have h' : r[j] = .yarn := by simpa [List.getD_eq_getElem?_getD, hj] using h
    by_contra hne
    rcases Nat.lt_or_gt_of_ne hne with hlt' | hgt
    · have := two_yarns hlt' hlt h' hget; omega
    · have := two_yarns hgt hj hget h'; omega
  · rintro rfl; simp [List.getD_eq_getElem?_getD, hlt, hget]
theorem getD_yarnIdx (r : Row) (hy : r.count .yarn = 1) : r.getD (yarnIdx r) .yarn = .yarn
Proof
:=
  (getD_eq_yarn_iff hy (yarnIdx_lt hy)).mpr rfl
theorem count_splice (a : Obj) (r : Row) (f len : Nat) (N : Row) :
    (spliceL r f len N).count a = r.count a - ((r.drop f).take len).count a + N.count a
Proof
:= by
  have e : r = r.take f ++ ((r.drop f).take len ++ r.drop (f + len)) := by
    rw [← List.drop_drop, List.take_append_drop, List.take_append_drop]
  have := congrArg (List.count a) e
  simp only [List.count_append] at this
  simp only [spliceL, List.count_append]; omega
theorem splice_eq (r : Row) (f len : Nat) (N : Row) : splice r f len N = spliceL r f len N
Proof
:= rfl

The reading lemmas

section Read
variable {c : Comp} {st : State}
theorem laid_carrier (hL : Laid c st) (hc : c.at_ = canonical 2 c.row.length) :
    st.carrier = 3 + 2 * (yarnIdx c.row : Int)
Proof
:= by
  rw [hL.2.2.2.2.2.1, hc, canonical_getD_two (yarnIdx_lt hL.1)]
theorem laid_front_at (hL : Laid c st) (hc : c.at_ = canonical 2 c.row.length) (j : Nat) :
    (st.stk ⟨.f, 3 + 2 * (j : Int)⟩).length = stackSize (c.row.getD j .yarn)
Proof
:= by
  rw [hL.2.2.2.2.1, hc, loadAt_canon_at]
theorem laid_front_off (hL : Laid c st) (hc : c.at_ = canonical 2 c.row.length) (i : Int)
    (hi : ∀ j : Nat, i ≠ 3 + 2 * (j : Int)) : st.stk ⟨.f, i⟩ = []
Proof
:= by
  rw [← List.length_eq_zero_iff, hL.2.2.2.2.1, hc, loadAt_canon_off _ _ hi]
theorem laid_front_yarn (hL : Laid c st) (hc : c.at_ = canonical 2 c.row.length) :
    st.stk ⟨.f, 3 + 2 * (yarnIdx c.row : Int)⟩ = []
Proof
:= by
  rw [← List.length_eq_zero_iff, laid_front_at hL hc, getD_yarnIdx _ hL.1]; rfl
theorem stackSize_of_ge {r : Row} {j : Nat} (h : r.length ≤ j) : stackSize (r.getD j .yarn) = 0
Proof
:= by
  rw [getD_of_ge h]; rfl
theorem segW_canon (hL : Laid c st) (hc : c.at_ = canonical 2 c.row.length) {j : Nat} (hj : j < c.row.length) :
    segW st (3 + 2 * (j : Int)) = (c.row.getD j .yarn).width
Proof
:= by
  rw [segW_eq]
  have hb : backAt st (3 + 2 * (j : Int)) = 0 := by simp [backAt, hL.2.2.2.1]
  rw [hb, frontAt, laid_front_at hL hc, yarnAt, laid_carrier hL hc]
  by_cases hy : j = yarnIdx c.row
  · subst hy
    rw [getD_yarnIdx _ hL.1, ite_eq_left rfl]; rfl
  · rw [ite_eq_right (by omega)]
    cases h : c.row.getD j .yarn with
    | yarn => exact absurd ((getD_eq_yarn_iff hL.1 hj).mp h) hy
    | stack k => simp [stackSize, Obj.width]
theorem segW_off (hL : Laid c st) (hc : c.at_ = canonical 2 c.row.length) (i : Int)
    (hi : ∀ j : Nat, j < c.row.length → i ≠ 3 + 2 * (j : Int)) : segW st i = 0
Proof
:= by
  rw [segW_eq]
  have hb : backAt st i = 0 := by simp [backAt, hL.2.2.2.1]
  have hy : yarnAt st i = 0 := by
    simp only [yarnAt, laid_carrier hL hc]
    rw [ite_eq_right (fun h => hi _ (yarnIdx_lt hL.1) h.symm)]
  have hf : frontAt st i = 0 := by
    unfold frontAt
    by_cases h : ∃ j : Nat, i = 3 + 2 * (j : Int)
    · obtain ⟨j, rfl⟩ := h
      have hj : c.row.length ≤ j := by
        by_contra h'; exact hi j (by omega) rfl
      rw [laid_front_at hL hc, stackSize_of_ge hj]
    · simp only [not_exists] at h; rw [laid_front_off hL hc i h]; rfl
  omega
theorem offset_succ (r : Row) {m : Nat} (hm : m < r.length) :
    offset r (m + 1) = offset r m + (r.getD m .yarn).width
Proof
:= by
  unfold offset rowWidth
  rw [List.take_add_one, List.map_append, List.sum_append, List.getElem?_eq_getElem hm]
  simp [List.getD_eq_getElem?_getD, List.getElem?_eq_getElem hm]
theorem strandsBefore_canon (hL : Laid c st) (hc : c.at_ = canonical 2 c.row.length)
    (win : Window) (hlo : win.lo ≤ 3) : ∀ m : Nat, m ≤ c.row.length →
      strandsBefore win st (3 + 2 * (m : Int)) = offset c.row m
Proof
  | 0, _ => by
    have := sb_add win st (le_refl win.lo) (3 - win.lo).toNat
    rw [show win.lo + ((3 - win.lo).toNat : Int) = 3 by omega, sb_lo] at this
    rw [show (3 : Int) + 2 * ((0 : Nat) : Int) = 3 by simp, this]
    simp only [offset, List.take_zero, Nat.zero_add]
    rw [Finset.sum_eq_zero]; · rfl
    intro t ht
    simp only [Finset.mem_range] at ht
    exact segW_off hL hc _ (fun j _ => by omega)
  | m + 1, hm => by
    have ih := strandsBefore_canon hL hc win hlo m (by omega)
    have := sb_add win st (i := 3 + 2 * (m : Int)) (by omega) 2
    rw [show 3 + 2 * (m : Int) + ((2 : Nat) : Int) = 3 + 2 * ((m + 1 : Nat) : Int) by push_cast; omega] at this
    rw [this, ih, offset_succ _ (by omega)]
    simp only [Finset.sum_range_succ, Finset.sum_range_zero, Nat.zero_add]
    rw [show 3 + 2 * (m : Int) + ((0 : Nat) : Int) = 3 + 2 * (m : Int) by simp, segW_canon hL hc (by omega),
      segW_off hL hc _ (fun j _ => by push_cast; omega), Nat.add_zero]
theorem fits_lo {win : Window} (hF : Fits win c) (hc : c.at_ = canonical 2 c.row.length)
    (hn : 0 < c.row.length) : win.lo ≤ 1
Proof
:= by
  have hlen : 0 < c.at_.length := by rw [hc, canonical_length]; exact hn
  have hv : c.at_[0] = 3 := by
    have := canonical_getD_two (n := c.row.length) hn
    rw [← hc, getD_of_lt hlen] at this; simpa using this
  have := hF _ (List.getElem_mem hlen); rw [hv] at this; omega
theorem fits_canon {win : Window} (hF : Fits win c) (hc : c.at_ = canonical 2 c.row.length)
    {j : Nat} (hj : j < c.row.length) : win.lo + 2 ≤ 3 + 2 * (j : Int) ∧ 3 + 2 * (j : Int) + 2 < win.lo + win.w
Proof
:= by
  have hlen : j < c.at_.length := by rw [hc, canonical_length]; exact hj
  have hv : c.at_[j] = 3 + 2 * (j : Int) := by
    have := canonical_getD_two (n := c.row.length) hj
    rw [← hc, getD_of_lt hlen] at this; exact this
  have := hF _ (List.getElem_mem hlen); rw [hv] at this; exact this

Splices: order, Laid, Fits

theorem scpos_lo (o : Obj) (c : Int) : 2 * c - 1 ≤ scpos o c
Proof
:= by cases o <;> simp [scpos]
theorem scpos_hi (o : Obj) (c : Int) : scpos o c ≤ 2 * c
Proof
:= by cases o <;> simp [scpos]
theorem order_splice (r : Row) (f len : Nat) (N : Row) (NA : List Int) (hf : f + len ≤ r.length)
    (hN : N.length = NA.length)
    (hin : ∀ t, t + 1 < N.length → scpos (N.getD t .yarn) (NA.getD t 0) < scpos (N.getD (t + 1) .yarn) (NA.getD (t + 1) 0))
    (hleft : 0 < f → 0 < N.length →
      scpos (r.getD (f - 1) .yarn) (3 + 2 * ((f - 1 : Nat) : Int)) < scpos (N.getD 0 .yarn) (NA.getD 0 0))
    (hright : f + len < r.length → 0 < N.length →
      scpos (N.getD (N.length - 1) .yarn) (NA.getD (N.length - 1) 0) <
        scpos (r.getD (f + len) .yarn) (3 + 2 * ((f + len : Nat) : Int))) :
    ∀ j, j + 1 < (spliceL r f len N).length →
      scpos ((spliceL r f len N).getD j .yarn) ((spliceL (canonical 2 r.length) f len NA).getD j 0) <
        scpos ((spliceL r f len N).getD (j + 1) .yarn) ((spliceL (canonical 2 r.length) f len NA).getD (j + 1) 0)
Proof
:= by
  intro j hj
  have hfc : f + len ≤ (canonical 2 r.length).length := by rw [canonical_length]; exact hf
  rw [length_spliceL _ _ _ _ hf] at hj
  rw [getD_spliceL _ _ _ _ _ hf, getD_spliceL _ _ _ _ _ hf, getD_spliceL _ _ _ _ _ hfc, getD_spliceL _ _ _ _ _ hfc,
    ← hN]
  have old : ∀ i, i < r.length → 2 * (3 + 2 * (i : Int)) - 1 ≤ scpos (r.getD i .yarn) ((canonical 2 r.length).getD i 0) ∧
      scpos (r.getD i .yarn) ((canonical 2 r.length).getD i 0) ≤ 2 * (3 + 2 * (i : Int)) := by
    intro i hi; rw [canonical_getD_two hi]; exact ⟨scpos_lo _ _, scpos_hi _ _⟩
  by_cases h1 : j + 1 < f
  · simp only [show j < f by omega, h1, ite_true]
    have a := old j (by omega); have b := old (j + 1) (by omega); push_cast at a b; omega
  by_cases h2 : j + 1 = f
  · simp only [show j < f by omega, h1, ite_true, ite_false]
    by_cases hm : 0 < N.length
    · simp only [show j + 1 < f + N.length by omega, ite_true, show j + 1 - f = 0 by omega]
      have := hleft (by omega) hm
      rw [show f - 1 = j by omega] at this
      rw [canonical_getD_two (n := r.length) (j := j) (by omega)]; exact this
    · simp only [show ¬ (j + 1 < f + N.length) by omega, ite_false]
      have a := old j (by omega); have b := old (j + 1 - N.length + len) (by omega)
      rw [show j + 1 - N.length + len = f + len by omega] at b ⊢
      push_cast at a b; omega
  by_cases h3 : j + 1 < f + N.length
  · simp only [show ¬ (j < f) by omega, show j < f + N.length by omega, h1, h3, ite_true, ite_false]
    have := hin (j - f) (by omega)
    rw [show j - f + 1 = j + 1 - f by omega] at this; exact this
  by_cases h4 : j + 1 = f + N.length
  · simp only [show ¬ (j < f) by omega, show j < f + N.length by omega, h1, h3, ite_true, ite_false]
    have hm : 0 < N.length := by omega
    have := hright (by omega) hm
    rw [show j - f = N.length - 1 by omega, show j + 1 - N.length + len = f + len by omega,
      canonical_getD_two (n := r.length) (j := f + len) (by omega)]
    exact this
  · simp only [show ¬ (j < f) by omega, show ¬ (j < f + N.length) by omega, h1, h3, ite_false]
    have a := old (j - N.length + len) (by omega); have b := old (j + 1 - N.length + len) (by omega)
    rw [show j + 1 - N.length + len = j - N.length + len + 1 by omega] at b ⊢
    push_cast at a b; omega
theorem laid_splice {c : Comp} {st st' : State} (hL : Laid c st) (hc : c.at_ = canonical 2 c.row.length)
    (f len : Nat) (N : Row) (NA : List Int) (ops : List Op) (hf : f + len ≤ c.row.length) (hN : N.length = NA.length)
    (hy : (spliceL c.row f len N).count .yarn = 1) (hrack : st'.rack = 0) (hback : ∀ j, st'.stk ⟨.b, j⟩ = [])
    (hfront : ∀ i, (st'.stk ⟨.f, i⟩).length +
      loadAt ((c.row.drop f).take len) (((canonical 2 c.row.length).drop f).take len) i =
        (st.stk ⟨.f, i⟩).length + loadAt N NA i)
    (hcar : st'.carrier = (spliceL (canonical 2 c.row.length) f len NA).getD (yarnIdx (spliceL c.row f len N)) 0)
    (hin : ∀ t, t + 1 < N.length → scpos (N.getD t .yarn) (NA.getD t 0) < scpos (N.getD (t + 1) .yarn) (NA.getD (t + 1) 0))
    (hleft : 0 < f → 0 < N.length →
      scpos (c.row.getD (f - 1) .yarn) (3 + 2 * ((f - 1 : Nat) : Int)) < scpos (N.getD 0 .yarn) (NA.getD 0 0))
    (hright : f + len < c.row.length → 0 < N.length →
      scpos (N.getD (N.length - 1) .yarn) (NA.getD (N.length - 1) 0) <
        scpos (c.row.getD (f + len) .yarn) (3 + 2 * ((f + len : Nat) : Int))) :
    Laid ⟨spliceL c.row f len N, spliceL (canonical 2 c.row.length) f len NA, ops⟩ st'
Proof
:= by
  have hl : c.row.length = (canonical 2 c.row.length).length := (canonical_length _).symm
  refine ⟨hy, ?_, hrack, hback, ?_, hcar, order_splice c.row f len N NA hf hN hin hleft hright⟩
  · simp only
    rw [length_spliceL _ _ _ _ hf, length_spliceL _ _ _ _ (by rw [← hl]; exact hf), ← hl, hN]
  · intro i
    have h1 := hfront i
    have h2 := loadAt_spliceL c.row (canonical 2 c.row.length) hl f len N NA hN i
    have h3 := hL.2.2.2.2.1 i
    rw [hc] at h3
    show _ = loadAt (spliceL c.row f len N) (spliceL (canonical 2 c.row.length) f len NA) i
    omega
theorem fits_splice {win : Window} {c : Comp} (hF : Fits win c) (f len : Nat) (NA : List Int) (row : Row)
    (ops : List Op) (hc : c.at_ = canonical 2 c.row.length)
    (hNA : ∀ x ∈ NA, win.lo + 2 ≤ x ∧ x + 2 < win.lo + win.w) :
    Fits win ⟨row, spliceL (canonical 2 c.row.length) f len NA, ops⟩
Proof
:= by
  intro x hx
  simp only [spliceL, List.mem_append] at hx
  rcases hx with (hx | hx) | hx
  · exact hF x (by rw [hc]; exact List.mem_of_mem_take hx)
  · exact hNA x hx
  · exact hF x (by rw [hc]; exact List.mem_of_mem_drop hx)
theorem loadAt_seg_one (r : Row) {f : Nat} (hf : f < r.length) (i : Int) :
    loadAt ((r.drop f).take 1) (((canonical 2 r.length).drop f).take 1) i =
      if 3 + 2 * (f : Int) = i then stackSize (r.getD f .yarn) else 0
Proof
:= by
  rw [seg1_one _ hf .yarn, seg1_one _ (by rw [canonical_length]; exact hf) 0, canonical_getD_two hf, loadAt_cons,
    loadAt_nil, Nat.add_zero]
theorem loadAt_seg_two (r : Row) {f : Nat} (hf : f + 1 < r.length) (i : Int) :
    loadAt ((r.drop f).take 2) (((canonical 2 r.length).drop f).take 2) i =
      (if 3 + 2 * (f : Int) = i then stackSize (r.getD f .yarn) else 0) +
        (if 3 + 2 * ((f + 1 : Nat) : Int) = i then stackSize (r.getD (f + 1) .yarn) else 0)
Proof
:= by
  rw [seg1_two _ hf .yarn, seg1_two _ (by rw [canonical_length]; exact hf) 0, canonical_getD_two (by omega : f < r.length),
    canonical_getD_two hf, loadAt_cons, loadAt_cons, loadAt_nil, Nat.add_zero]
theorem stackAt_some {r : Row} {a k : Nat} (h : stackAt r a = some k) :
    a < r.length ∧ r.getD a .yarn = .stack k ∧ 0 < k
Proof
:= by
  unfold stackAt at h
  cases hr : r[a]? with
  | none => rw [hr] at h; simp at h
  | some o =>
    rw [hr] at h
    cases o with
    | yarn => simp at h
    | stack k' =>
      simp only at h
      split at h
      · simp at h; subst h
        refine ⟨?_, ?_, by assumption⟩
        · exact (List.getElem?_eq_some_iff.mp hr).1
        · simp [List.getD_eq_getElem?_getD, hr]
      · simp at h
theorem stackAt_none {r : Row} {a : Nat} (h : stackAt r a = none) (k : Nat) (hk : 0 < k) :
    r.getD a .yarn ≠ .stack k
Proof
:= by
  intro he
  unfold stackAt at h
  by_cases ha : a < r.length
  · rw [getD_of_lt ha] at he
    rw [List.getElem?_eq_getElem ha, he] at h; simp [hk] at h
  · rw [getD_of_ge (by omega)] at he; simp at he

Fragment: drop and tuck

drop_frag : FragmentFor 2 isDrop and tuck_frag : FragmentFor 2 isTuck, for every stack size.

  • Drop of a stack of k: one drop on a needle that holds k loops. It draws k caps at the needle's first strand. By the reading lemma, that strand is offset r a.
  • Tuck: one tuck on the front needle beside the carrier. It draws one tuck d box at offset r (yarnIdx r).
  • denote_single: one instruction with no split, under denote.
namespace FormalizeKnitting.Bridge.RM.Frag
open FormalizeKnitting.Knitout
theorem denote_single {win : Window} {s : State} {op : Op} (hns : NotSplit op) (h : validCrate s op)
    (hw : windowOk win s op = true) : denote win s [op] = some (apply s op, liftB (denoteOp1 win s op))
Proof
:=
  denote_of_denote1 win s [op] _ _ (fun o ho => by simp at ho; subst ho; exact hns) (denote1_single_op h hw)
theorem yarn_mem {r : Row} (hy : r.count .yarn = 1) : Obj.yarn ∈ r
Proof
:= List.count_pos_iff.mp (by omega)
theorem liftB_plainB (u : MWord) : liftB (plainB u) = plainB u
Proof
:= by
  simp [liftB, plainB, List.map_map, Function.comp_def]

Drop

theorem drop_frag : FragmentFor 2 isDrop
Proof
:= by
  intro win c c1 st s r' M hs hL hc hF hrs hcs hpre hN
  cases s with
  | x _ _ => exact hs.elim
  | tuck _ => exact hs.elim
  | merge _ => exact hs.elim
  | knit _ _ => exact hs.elim
  | split _ _ => exact hs.elim
  | drop a =>
  have hy := hL.1
  have hym := yarn_mem hy
  have hyl := yarnIdx_lt hy
  set y := yarnIdx c.row with hydef
  cases hk : stackAt c.row a with
  | none => simp [runStepB, hym, hk] at hrs
  | some k =>
  simp only [runStepB, hym, ite_true, hk, Option.some.injEq, Prod.mk.injEq] at hrs
  obtain ⟨rfl, rfl⟩ := hrs
  obtain ⟨ha, hga, hk0⟩ := stackAt_some hk
  have hpa : c.at_.getD a 0 = 3 + 2 * (a : Int) := by rw [hc]; exact canonical_getD_two ha
  simp only [compileStep, hym, ite_true, hk, Option.some.injEq, hpa] at hcs
  subst hcs
  set p : Int := 3 + 2 * (a : Int) with hpdef
  have hay : a ≠ y := fun h => by rw [h, getD_yarnIdx _ hy] at hga; exact absurd hga (by simp)
  have hn3 := hN (.drop (fN p)) (by simp) p (by simp [Op.named, fN])
  have hlo := fits_lo hF hc (by omega)
  have hcar : st.carrier = 3 + 2 * (y : Int) := laid_carrier hL hc
  have hlen : (st.stk ⟨.f, p⟩).length = k := by rw [laid_front_at hL hc, hga]; rfl
  refine ⟨?_, ?_⟩
  · intro x hx
    exact hF x (List.mem_of_mem_eraseIdx hx)
  refine ⟨apply st (.drop (fN p)), ?_, ?_⟩
  · have hne : (st.stk ⟨.f, p⟩).length ≠ 0 := by omega
    have hv : validCrate st (.drop (fN p)) := by
      simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, fN, hne]
    rw [List.drop_left, denote_single (op := Op.drop (fN p)) trivial hv (by
      simp only [windowOk, slot, fN]; exact inside_of (by omega) (by omega))]
    congr 1
    have hsb : strandsBefore win st p = offset c.row a := strandsBefore_canon hL hc win (by omega) a (by omega)
    have hya : yarnAt st p = 0 := by simp only [yarnAt, hcar]; rw [ite_eq_right (by omega)]
    simp only [denoteOp1, slot, fN, hsb, hya, hlen, liftB, plainB, List.map_map]
    simp [Function.comp_def]
  · show Laid ⟨c.row.eraseIdx a, c.at_.eraseIdx a, c.ops ++ _⟩ _
    rw [eraseIdx_spliceL, eraseIdx_spliceL, hc]
    have hy' : (spliceL c.row a 1 []).count .yarn = 1 := by
      rw [count_splice, seg1_one _ ha .yarn, hga]; simp [hy]
    have hlen' : (spliceL c.row a 1 []).length = c.row.length - 1 := by
      rw [length_spliceL _ _ _ _ (by omega)]; simp
    have hyi : yarnIdx (spliceL c.row a 1 []) = if a < y then y - 1 else y := by
      apply yarnIdx_of hy' (by rw [hlen']; split <;> omega)
      rw [getD_spliceL _ _ _ _ _ (by omega)]
      split
      · rw [ite_eq_right (by omega), ite_eq_right (by simp; omega), show y - 1 - [].length + 1 = y by simp; omega]
        exact getD_yarnIdx _ hy
      · rw [ite_eq_left (by omega)]; exact getD_yarnIdx _ hy
    apply laid_splice hL hc a 1 [] [] _ (by omega) rfl hy'
    · exact hL.2.2.1
    · intro j; simp [apply, fN, hL.2.2.2.1]
    · intro i
      rw [loadAt_seg_one _ ha, hga, loadAt_nil]
      by_cases hi : i = p
      · subst hi
        rw [ite_eq_left hpdef.symm]
        simp [apply, fN, hlen, stackSize]
      · have hst : (apply st (.drop (fN p))).stk ⟨.f, i⟩ = st.stk ⟨.f, i⟩ := by
          simp [apply, fN, hi]
        rw [hst, ite_eq_right (Ne.symm hi)]
    · rw [hyi, getD_spliceL _ _ _ _ _ (by rw [canonical_length]; omega)]
      show st.carrier = _
      rw [hcar]
      split
      · rw [ite_eq_right (by omega), ite_eq_right (by simp; omega), show y - 1 - [].length + 1 = y by simp; omega,
          canonical_getD_two hyl]
      · rw [ite_eq_left (by omega), canonical_getD_two hyl]
    · intro t ht; simp at ht
    · intro _ h; simp at h
    · intro _ h; simp at h

Tuck

theorem tuck_frag : FragmentFor 2 isTuck
Proof
:= by
  intro win c c1 st s r' M hs hL hc hF hrs hcs hpre hN
  cases s with
  | x _ _ => exact hs.elim
  | drop _ => exact hs.elim
  | merge _ => exact hs.elim
  | knit _ _ => exact hs.elim
  | split _ _ => exact hs.elim
  | tuck d =>
  have hy := hL.1
  have hym := yarn_mem hy
  have hyl := yarnIdx_lt hy
  set y := yarnIdx c.row with hydef
  have hcc : c.at_.getD y 0 = 3 + 2 * (y : Int) := by rw [hc]; exact canonical_getD_two hyl
  simp only [runStepB, hym, ite_true, Option.some.injEq, Prod.mk.injEq, ← hydef] at hrs
  obtain ⟨rfl, rfl⟩ := hrs
  have hlo := fits_lo hF hc (by omega)
  have hfit := fits_canon hF hc hyl
  have hcar : st.carrier = 3 + 2 * (y : Int) := laid_carrier hL hc
  have hfy : st.stk ⟨.f, 3 + 2 * (y : Int)⟩ = [] := laid_front_yarn hL hc
  have hsb : strandsBefore win st (3 + 2 * (y : Int)) = offset c.row y :=
    strandsBefore_canon hL hc win (by omega) y (by omega)
  have hseg : ∀ i, loadAt ((c.row.drop y).take 1) (((canonical 2 c.row.length).drop y).take 1) i = 0 := by
    intro i; rw [loadAt_seg_one _ hyl, getD_yarnIdx _ hy]; split <;> rfl
  have hy1 : ((c.row.drop y).take 1).count .yarn = 1 := by rw [seg1_one _ hyl .yarn, getD_yarnIdx _ hy]; simp
  cases d with
  | R =>
    simp only [compileStep, hym, ite_true, Option.some.injEq, ← hydef, hcc] at hcs
    subst hcs
    set cc : Int := 3 + 2 * (y : Int) with hccdef
    have hn3 := hN (.tuck .R (fN cc)) (by simp) cc (by simp [Op.named, fN])
    refine ⟨?_, ?_⟩
    · show Fits win ⟨_, spliceL c.at_ y 1 [cc, cc + 1], _⟩
      rw [hc]; apply fits_splice hF _ _ _ _ _ hc
      intro x hx; simp at hx; omega
    refine ⟨apply st (.tuck .R (fN cc)), ?_, ?_⟩
    · rw [List.drop_left, denote_single (op := Op.tuck .R (fN cc)) trivial (tuck_valid (by rw [hcar]; rfl)) (by
        simp only [windowOk, slot, fN]; exact inside_of (by omega) (by omega))]
      congr 1
      have hF0 : frontAt st cc = 0 := by simp [frontAt, hfy]
      have hK0 : backAt st cc = 0 := by simp [backAt, hL.2.2.2.1]
      simp only [denoteOp1, slot, fN, arrivesFrom, hF0, hK0, hsb, swapB_nil (Or.inr rfl),
        List.nil_append, List.append_nil, Nat.add_zero]
      rfl
    · show Laid ⟨spliceL c.row y 1 (tuckRow .R), spliceL c.at_ y 1 [cc, cc + 1], c.ops ++ _⟩ _
      rw [hc]
      have hy' : (spliceL c.row y 1 (tuckRow .R)).count .yarn = 1 := by
        rw [count_splice, hy1]; simp [hy, tuckRow]
      have hl' : y + 1 < (spliceL c.row y 1 (tuckRow .R)).length := by
        rw [length_spliceL _ _ _ _ (by omega)]; simp [tuckRow]; omega
      have hyi : yarnIdx (spliceL c.row y 1 (tuckRow .R)) = y + 1 := by
        apply yarnIdx_of hy' hl'
        rw [getD_spliceL _ _ _ _ _ (by omega)]; simp [tuckRow]
      apply laid_splice hL hc y 1 (tuckRow .R) [cc, cc + 1] _ (by omega) rfl hy'
      · exact hL.2.2.1
      · intro j; simp [apply, fN, hL.2.2.2.1]
      · intro i
        rw [hseg i]
        by_cases hi : i = cc
        · subst hi
          simp [apply, fN, hfy, tuckRow, loadAt, stackSize]
        · have hst : (apply st (.tuck .R (fN cc))).stk ⟨.f, i⟩ = st.stk ⟨.f, i⟩ := by
            simp [apply, fN, hi]
          rw [hst]
          simp [tuckRow, loadAt, Ne.symm hi, stackSize]
      · rw [hyi, getD_spliceL _ _ _ _ _ (by rw [canonical_length]; omega)]
        simp [apply, fN, slot, leavesTo, hL.2.2.1]
      · intro t ht; obtain rfl : t = 0 := by simp [tuckRow] at ht; omega
        simp [scpos, tuckRow]; omega
      · intro _ _; refine lt_of_le_of_lt (scpos_hi _ _) ?_; simp [scpos, tuckRow]; omega
      · intro _ _; refine lt_of_lt_of_le ?_ (scpos_lo _ _); simp [scpos, tuckRow]; omega
  | L =>
    simp only [compileStep, hym, ite_true, Option.some.injEq, ← hydef, hcc] at hcs
    subst hcs
    set cc : Int := 3 + 2 * (y : Int) with hccdef
    have hn3 := hN (.tuck .L (fN (cc - 1))) (by simp) (cc - 1) (by simp [Op.named, fN])
    have hoff : st.stk ⟨.f, cc - 1⟩ = [] := laid_front_off hL hc (cc - 1) (fun j => by omega)
    refine ⟨?_, ?_⟩
    · show Fits win ⟨_, spliceL c.at_ y 1 [cc - 1, cc - 1], _⟩
      rw [hc]; apply fits_splice hF _ _ _ _ _ hc
      intro x hx; simp at hx; omega
    refine ⟨apply st (.tuck .L (fN (cc - 1))), ?_, ?_⟩
    · rw [List.drop_left, denote_single (op := Op.tuck .L (fN (cc - 1))) trivial (tuck_valid (by rw [hcar]; simp [arrivesFrom])) (by
        simp only [windowOk, slot, fN]; exact inside_of (by omega) (by omega))]
      congr 1
      have hF0 : frontAt st (cc - 1) = 0 := by simp [frontAt, hoff]
      have hK0 : backAt st (cc - 1) = 0 := by simp [backAt, hL.2.2.2.1]
      have ea : arrivesFrom .L (cc - 1) = cc := by simp [arrivesFrom]
      simp only [denoteOp1, slot, fN, ea, hF0, hK0, hsb, swapB_nil (Or.inl rfl),
        List.nil_append, List.append_nil, Nat.sub_zero]
      rfl
    · show Laid ⟨spliceL c.row y 1 (tuckRow .L), spliceL c.at_ y 1 [cc - 1, cc - 1], c.ops ++ _⟩ _
      rw [hc]
      have hy' : (spliceL c.row y 1 (tuckRow .L)).count .yarn = 1 := by
        rw [count_splice, hy1]; simp [hy, tuckRow]
      have hl' : y < (spliceL c.row y 1 (tuckRow .L)).length := by
        rw [length_spliceL _ _ _ _ (by omega)]; simp [tuckRow]; omega
      have hyi : yarnIdx (spliceL c.row y 1 (tuckRow .L)) = y := by
        apply yarnIdx_of hy' hl'
        rw [getD_spliceL _ _ _ _ _ (by omega)]; simp [tuckRow]
      apply laid_splice hL hc y 1 (tuckRow .L) [cc - 1, cc - 1] _ (by omega) rfl hy'
      · exact hL.2.2.1
      · intro j; simp [apply, fN, hL.2.2.2.1]
      · intro i
        rw [hseg i]
        by_cases hi : i = cc - 1
        · subst hi
          simp [apply, fN, hoff, tuckRow, loadAt, stackSize]
        · have hst : (apply st (.tuck .L (fN (cc - 1)))).stk ⟨.f, i⟩ = st.stk ⟨.f, i⟩ := by
            simp [apply, fN, hi]
          rw [hst]
          simp [tuckRow, loadAt, Ne.symm hi, stackSize]
      · rw [hyi, getD_spliceL _ _ _ _ _ (by rw [canonical_length]; omega)]
        simp [apply, fN, slot, leavesTo, hL.2.2.1]
      · intro t ht; obtain rfl : t = 0 := by simp [tuckRow] at ht; omega
        simp [scpos, tuckRow]
      · intro _ _; refine lt_of_le_of_lt (scpos_hi _ _) ?_; simp [scpos, tuckRow]; omega
      · intro _ _; refine lt_of_lt_of_le ?_ (scpos_lo _ _); simp [scpos, tuckRow]; omega

Fragment: knit

knit_frag : FragmentFor 2 isKnit, for both directions, both beds and every stack size k.

  • The stack is already on one needle c1. No loops are gathered.
  • The carrier moves by misses over empty positions to the side of c1 that it arrives from. The misses draw nothing (missR_walk, missL_walk).
  • Knit.knit_block: knitOps on a needle that holds k loops draws one box knit d bd k at the strands left of c1.
  • By the reading lemma, those strands are offset r (firstIdx r d).
namespace FormalizeKnitting.Bridge.RM.Frag
open FormalizeKnitting.Knitout
theorem bind_coe_map (f : Int → Op) : ∀ l : List Nat,
    (l >>= fun a => (pure (a : Int) : List Int)).map f = l.map (fun t : Nat => f t)
Proof
  | [] => rfl
  | x :: xs => by
    have := bind_coe_map f xs
    show f x :: (xs >>= fun a => (pure (a : Int) : List Int)).map f = f x :: xs.map _
    rw [this]
theorem knitOps_eq (d : Dir) (bd : Bed) (c1 : Int) : knitOps d bd c1 = Knit.knitOps1 d bd c1
Proof
:= rfl
theorem yarnTo_notSplit (a b : Int) : ∀ op ∈ yarnTo a b, NotSplit op
Proof
:= by
  intro op hop
  unfold yarnTo at hop
  split at hop <;> simp only [List.mem_map] at hop <;> obtain ⟨_, _, rfl⟩ := hop <;> trivial
theorem knitOps_notSplit (d : Dir) (bd : Bed) (c1 : Int) : ∀ op ∈ Knit.knitOps1 d bd c1, NotSplit op
Proof
:= by
  intro op hop
  cases bd <;> simp [Knit.knitOps1] at hop
  · subst hop; trivial
  · rcases hop with h | h | h <;> subst h <;> trivial
theorem liftB_knit (d : Dir) (bd : Bed) (k i : Nat) :
    liftB [BEv.box (PlainLabel.knit d bd k) i] = [BEv.box (Label.knit d bd k) i]
Proof
:= rfl
theorem knit_frag : FragmentFor 2 isKnit
Proof
:= by
  intro win c c1 st s r' M hs hL hc hF hrs hcs hpre hN
  cases s with
  | x _ _ => exact hs.elim
  | drop _ => exact hs.elim
  | merge _ => exact hs.elim
  | tuck _ => exact hs.elim
  | split _ _ => exact hs.elim
  | knit d bd =>
  have hy := hL.1
  have hym := yarn_mem hy
  have hyl := yarnIdx_lt hy
  set y := yarnIdx c.row with hydef
  have hlo := fits_lo hF hc (by omega)
  have hcar : st.carrier = 3 + 2 * (y : Int) := laid_carrier hL hc
  have hr : st.rack = 0 := hL.2.2.1
  have hb : ∀ j, st.stk ⟨.b, j⟩ = [] := hL.2.2.2.1
  have hys : c.at_.getD (yarnIdx c.row) 0 = 3 + 2 * (y : Int) := by rw [hc]; exact canonical_getD_two hyl
  cases hk : stackAt c.row (besideIdx c.row d) with
  | none => simp [runStepB, hk] at hrs
  | some k =>
  obtain ⟨hbl, hga, hk0⟩ := stackAt_some hk
  have hbyl : besideIdx c.row d ≠ y := by
    intro h; rw [h, getD_yarnIdx _ hy] at hga; exact absurd hga (by simp)
  have hhb : hasBeside c.row d = true := by
    cases d <;> simp [hasBeside, besideIdx] at hbl hbyl ⊢ <;> omega
  simp only [runStepB, hym, hhb, and_self, ite_true, hk, Option.some.injEq, Prod.mk.injEq] at hrs
  obtain ⟨rfl, rfl⟩ := hrs
  have hbc : c.at_.getD (besideIdx c.row d) 0 = 3 + 2 * ((besideIdx c.row d : Nat) : Int) := by
    rw [hc]; exact canonical_getD_two hbl
  simp only [compileStep, hym, hhb, and_self, ite_true, hk, Option.some.injEq, hbc, hys] at hcs
  subst hcs
  have hsbc := strandsBefore_canon hL hc win (by omega)
  have hfront := laid_front_at hL hc
  have hoff := laid_front_off hL hc
  cases d with
  | R =>
    have e1 : besideIdx c.row .R = y + 1 := rfl
    have e2 : firstIdx c.row .R = y := rfl
    simp only [e1, e2] at hga hbl hN hpre ⊢
    set cc : Int := 3 + 2 * (y : Int) with hccdef
    have ec1 : 3 + 2 * ((y + 1 : Nat) : Int) = cc + 2 := by push_cast; omega
    simp only [ec1] at hN hpre ⊢
    have hn3 := hN (.knit .R ⟨bd, cc + 2⟩) (List.mem_append_right _ (List.mem_append_right _ (by cases bd <;> simp [knitOps]))) (cc + 2) (by simp [Op.named])
    have hfit := fits_canon hF hc hbl
    push_cast at hfit
    refine ⟨?_, ?_⟩
    · show Fits win ⟨_, spliceL c.at_ y 2 [cc + 2, cc + 2 + 1], _⟩
      rw [hc]; apply fits_splice hF _ _ _ _ _ hc
      intro x hx; simp at hx; omega
    have hyt : yarnTo cc (cc + 2) = (List.range 2).map fun t : Nat => Op.miss .R (fN (cc + t)) := by
      unfold yarnTo; rw [ite_eq_left (by omega), show (cc + 2 - cc).toNat = 2 by omega, bind_coe_map]
    have hY := Knit.missR_walk win st cc hr hcar hb 2 (fun t ht => by
      refine ⟨?_, inside_of (by omega) (by omega)⟩
      by_cases h0 : t = 0
      · subst h0; simpa using laid_front_yarn hL hc
      · exact hoff _ (fun j => by omega))
    set sY : State := { st with carrier := cc + ((2 : Nat) : Int) } with hsY
    have hkk' : (st.stk ⟨.f, cc + 2⟩).length = k := by
      rw [← ec1, hfront, hga]; rfl
    have hkk : (sY.stk ⟨.f, cc + 2⟩).length = k := hkk'
    obtain ⟨sF, hdK, rF, bF, cF, nF, tF⟩ := Knit.knit_block win sY .R bd (cc + 2) k hr hb
      (by simp [hsY, arrivesFrom]) hkk hk0 (inside_of (by omega) (by omega)) (by omega)
    have hsb : strandsBefore win sY (cc + 2) = offset c.row y := by
      have e := sb_add win sY (i := cc) (by omega) 2
      rw [show cc + ((2 : Nat) : Int) = cc + 2 by simp] at e
      rw [e]
      have hB : strandsBefore win sY cc = strandsBefore win st cc := by
        apply sb_congr' win (by omega)
        intro p _ hp
        rw [segW_eq, segW_eq]
        simp only [yarnAt, frontAt, backAt, hsY, hcar]
        rw [ite_eq_right (by push_cast; omega), ite_eq_right (by omega)]
      rw [hB, hccdef, hsbc y (by omega)]
      simp only [Finset.sum_range_succ, Finset.sum_range_zero, Nat.zero_add]
      rw [segW_eq, segW_eq]
      simp only [yarnAt, frontAt, backAt, hsY, hr, hb, sub_zero]
      rw [ite_eq_right (by push_cast; omega), ite_eq_right (by push_cast; omega)]
      have h0 : st.stk ⟨.f, 3 + 2 * (y : Int) + ((0 : Nat) : Int)⟩ = [] := by simpa using laid_front_yarn hL hc
      have h1 : st.stk ⟨.f, 3 + 2 * (y : Int) + ((1 : Nat) : Int)⟩ = [] := hoff _ (fun j => by push_cast; omega)
      rw [h0, h1]; rfl
    rw [hsb] at hdK
    refine ⟨sF, ?_, ?_⟩
    · show denote win st ((c.ops ++ (yarnTo cc (cc + 2) ++ knitOps .R bd (cc + 2))).drop c.ops.length) = _
      rw [List.drop_left, knitOps_eq]
      have hY' : denote1 win st (yarnTo cc (cc + 2)) = some (sY, []) := by rw [hyt]; exact hY
      have := denote1_append win st _ _ sY sF [] _ hY' hdK
      rw [denote_of_denote1 win st _ sF _ (fun op hop => by
        rcases List.mem_append.mp hop with h | h
        · exact yarnTo_notSplit _ _ op h
        · exact knitOps_notSplit _ _ _ op h) this]
      rfl
    · show Laid ⟨spliceL c.row y 2 (tuckRow .R), spliceL c.at_ y 2 [cc + 2, cc + 2 + 1], _⟩ sF
      rw [hc]
      have hseg2 : ((c.row.drop y).take 2).count .yarn = 1 := by
        rw [seg1_two _ hbl .yarn, getD_yarnIdx _ hy, hga]; simp
      have hy' : (spliceL c.row y 2 (tuckRow .R)).count .yarn = 1 := by
        rw [count_splice, hseg2]; simp [hy, tuckRow]
      have hl' : y + 1 < (spliceL c.row y 2 (tuckRow .R)).length := by
        rw [length_spliceL _ _ _ _ (by omega)]; simp [tuckRow]; omega
      have hyi : yarnIdx (spliceL c.row y 2 (tuckRow .R)) = y + 1 := by
        apply yarnIdx_of hy' hl'
        rw [getD_spliceL _ _ _ _ _ (by omega)]; simp [tuckRow]
      apply laid_splice hL hc y 2 (tuckRow .R) [cc + 2, cc + 2 + 1] _ hbl rfl hy' rF bF
      · intro i
        rw [loadAt_seg_two _ hbl, getD_yarnIdx _ hy, hga, ec1]
        by_cases hi : i = cc + 2
        · subst hi
          rw [nF]; simp [tuckRow, loadAt, stackSize, hkk']; omega
        · rw [tF i hi]
          simp [tuckRow, loadAt, stackSize, Ne.symm hi]; rfl
      · rw [hyi, getD_spliceL _ _ _ _ _ (by rw [canonical_length]; omega)]
        rw [cF]; simp [leavesTo]
      · intro t ht; obtain rfl : t = 0 := by simp [tuckRow] at ht; omega
        simp [scpos, tuckRow]; omega
      · intro _ _; refine lt_of_le_of_lt (scpos_hi _ _) ?_; simp [scpos, tuckRow]; omega
      · intro _ _; refine lt_of_lt_of_le ?_ (scpos_lo _ _); simp [scpos, tuckRow]; omega
  | L =>
    have e1 : besideIdx c.row .L = y - 1 := rfl
    have e2 : firstIdx c.row .L = y - 1 := rfl
    have hy1 : 1 ≤ y := by
      by_contra h0
      have : besideIdx c.row .L = y := by rw [e1]; omega
      exact hbyl this
    simp only [e1, e2] at hga hbl hN hpre ⊢
    set cc : Int := 3 + 2 * (y : Int) with hccdef
    have ec1 : 3 + 2 * ((y - 1 : Nat) : Int) = cc - 2 := by push_cast [hy1]; omega
    simp only [ec1] at hN hpre ⊢
    have hn3 := hN (.knit .L ⟨bd, cc - 2⟩) (List.mem_append_right _ (List.mem_append_right _ (by cases bd <;> simp [knitOps]))) (cc - 2) (by simp [Op.named])
    have hfit := fits_canon hF hc hbl
    rw [ec1] at hfit
    refine ⟨?_, ?_⟩
    · show Fits win ⟨_, spliceL c.at_ (y - 1) 2 [cc - 2, cc - 2], _⟩
      rw [hc]; apply fits_splice hF _ _ _ _ _ hc
      intro x hx; simp at hx; omega
    have hyt : yarnTo cc (cc - 2 + 1) = (List.range 1).map fun t : Nat => Op.miss .L (fN (cc - 1 - t)) := by
      unfold yarnTo; rw [ite_eq_right (by omega), show (cc - (cc - 2 + 1)).toNat = 1 by omega, bind_coe_map]
    have hY := Knit.missL_walk win st cc hr hcar hb 1 (fun t ht => by
      refine ⟨hoff _ (fun j => by omega), inside_of (by omega) (by omega)⟩)
    set sY : State := { st with carrier := cc - ((1 : Nat) : Int) } with hsY
    have hkk' : (st.stk ⟨.f, cc - 2⟩).length = k := by
      rw [← ec1, hfront, hga]; rfl
    have hkk : (sY.stk ⟨.f, cc - 2⟩).length = k := hkk'
    obtain ⟨sF, hdK, rF, bF, cF, nF, tF⟩ := Knit.knit_block win sY .L bd (cc - 2) k hr hb
      (by simp [hsY, arrivesFrom]; omega) hkk hk0 (inside_of (by omega) (by omega)) (by omega)
    have hsb : strandsBefore win sY (cc - 2) = offset c.row (y - 1) := by
      have hB : strandsBefore win sY (cc - 2) = strandsBefore win st (cc - 2) := by
        apply sb_congr' win (by omega)
        intro p _ hp
        rw [segW_eq, segW_eq]
        simp only [yarnAt, frontAt, backAt, hsY, hcar]
        rw [ite_eq_right (by push_cast; omega), ite_eq_right (by omega)]
      rw [hB, ← ec1, hsbc (y - 1) (by omega)]
    rw [hsb] at hdK
    refine ⟨sF, ?_, ?_⟩
    · show denote win st ((c.ops ++ (yarnTo cc (cc - 2 + 1) ++ knitOps .L bd (cc - 2))).drop c.ops.length) = _
      rw [List.drop_left, knitOps_eq]
      have hY' : denote1 win st (yarnTo cc (cc - 2 + 1)) = some (sY, []) := by rw [hyt]; exact hY
      have := denote1_append win st _ _ sY sF [] _ hY' hdK
      rw [denote_of_denote1 win st _ sF _ (fun op hop => by
        rcases List.mem_append.mp hop with h | h
        · exact yarnTo_notSplit _ _ op h
        · exact knitOps_notSplit _ _ _ op h) this]
      rfl
    · show Laid ⟨spliceL c.row (y - 1) 2 (tuckRow .L), spliceL c.at_ (y - 1) 2 [cc - 2, cc - 2], _⟩ sF
      rw [hc]
      have hbl2 : y - 1 + 1 < c.row.length := by omega
      have ey : y - 1 + 1 = y := by omega
      have hseg2 : ((c.row.drop (y - 1)).take 2).count .yarn = 1 := by
        rw [seg1_two _ hbl2 .yarn, ey, getD_yarnIdx _ hy, hga]; simp
      have hy' : (spliceL c.row (y - 1) 2 (tuckRow .L)).count .yarn = 1 := by
        rw [count_splice, hseg2]; simp [hy, tuckRow]
      have hl' : y - 1 < (spliceL c.row (y - 1) 2 (tuckRow .L)).length := by
        rw [length_spliceL _ _ _ _ (by omega)]; simp [tuckRow]; omega
      have hyi : yarnIdx (spliceL c.row (y - 1) 2 (tuckRow .L)) = y - 1 := by
        apply yarnIdx_of hy' hl'
        rw [getD_spliceL _ _ _ _ _ (by omega)]; simp [tuckRow]
      apply laid_splice hL hc (y - 1) 2 (tuckRow .L) [cc - 2, cc - 2] _ (by omega) rfl hy' rF bF
      · intro i
        rw [loadAt_seg_two _ hbl2, ey, getD_yarnIdx _ hy, hga, ec1]
        have ecy : 3 + 2 * ((y : Nat) : Int) = cc := rfl
        rw [ecy]
        by_cases hi : i = cc - 2
        · subst hi
          rw [nF]; simp [tuckRow, loadAt, stackSize, hkk']; omega
        · rw [tF i hi]
          simp [tuckRow, loadAt, stackSize, Ne.symm hi]; rfl
      · rw [hyi, getD_spliceL _ _ _ _ _ (by rw [canonical_length]; omega)]
        rw [cF]; simp [leavesTo]
      · intro t ht; obtain rfl : t = 0 := by simp [tuckRow] at ht; omega
        simp [scpos, tuckRow]
      · intro _ _; refine lt_of_le_of_lt (scpos_hi _ _) ?_; simp [scpos, tuckRow]; omega
      · intro _ _; refine lt_of_lt_of_le ?_ (scpos_lo _ _); simp [scpos, tuckRow]; omega

Fragment: the split instructions on a stack

splitR_mid (direction R) and splitL_mid (direction L) give the effect of splitOps d bd c1.

Start: front needle c1 holds k ≥ 1 loops, the carrier is on the side it arrives from, rack 0, back bed empty.

  • splitOps d bd c1 is accepted by step.
  • It draws exactly one box splitK d bd k at the strands left of c1.
  • The new loop and the old stack end on front needles c1 and c1 + 1.
bd Front needle c1 Front needle c1 + 1
.f the new loop the old stack
.b the old stack the new loop
  • post3: the parking moves (rack 1, the back needle onto the next front needle, rack 0) draw nothing.
namespace FormalizeKnitting.Bridge.RM.Frag
open FormalizeKnitting.Knitout
theorem post3 (win : Window) (s : State) (c1 : Int) (hr : s.rack = 0) (hb : ∀ j, j ≠ c1 → s.stk ⟨.b, j⟩ = [])
    (hcar : s.carrier ≠ c1 + 1) (hf1 : s.stk ⟨.f, c1 + 1⟩ = []) (hin1 : win.inside (c1 + 1) = true) :
    ∃ s', denote1 win s [.rack 1, .xfer (bN c1) (fN (c1 + 1)), .rack 0] = some (s', []) ∧ s'.rack = 0 ∧
      s'.carrier = s.carrier ∧ ∀ q, s'.stk q = if q = ⟨.f, c1 + 1⟩ then (s.stk ⟨.b, c1⟩).reverse
        else if q = ⟨.b, c1⟩ then [] else s.stk q
Proof
:= by
  set s5 := apply s (.rack 1) with hs5
  set s6 := apply s5 (.xfer (bN c1) (fN (c1 + 1))) with hs6
  have e5s : s5.stk = s.stk := rfl
  have e5r : s5.rack = 1 := rfl
  have k6 : ∀ q, s6.stk q = if q = ⟨.f, c1 + 1⟩ then (s.stk ⟨.b, c1⟩).reverse
      else if q = ⟨.b, c1⟩ then [] else s.stk q := by
    intro q; simp only [hs6, apply, upd_apply, xferStack, e5s, fN, bN]
    by_cases h : q = ⟨.f, c1 + 1⟩
    · subst h; simp [hf1]
    · simp [h]
  have b6 : ∀ j, s6.stk ⟨.b, j⟩ = [] := by
    intro j; rw [k6]; by_cases h : j = c1
    · subst h; simp
    · simp [h, hb j h]
  have v5 : validCrate s (.rack 1) := by simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, hr]
  have w5 : windowOk win s (.rack 1) = true := by
    simp only [windowOk, List.all_eq_true, List.mem_range, Bool.or_eq_true, List.isEmpty_iff]
    intro k _
    by_cases h : win.lo + (k : Int) = c1
    · right; rw [h]; exact hin1
    · left; exact hb _ h
  have d5 : denoteOp1 win s (.rack 1) = [] := by
    apply rackBraid_nil
    intro k _
    rw [ite_eq_right (by rw [hr]; omega)]
    by_cases h : win.lo + (k : Int) - 1 - s.rack = c1
    · right
      have e : win.lo + (k : Int) = c1 + 1 := by rw [hr] at h; omega
      rw [e]; simp only [yarnAt, frontAt, hf1]; simp [hcar]
    · left; rw [hb _ h]; rfl
  have v6 : validCrate s5 (.xfer (bN c1) (fN (c1 + 1))) := by
    simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, fN, bN, slot, aligned, e5r]
  have w6 : windowOk win s5 (.xfer (bN c1) (fN (c1 + 1))) = true := by
    simp only [windowOk, slot, fN, bN, e5r, Bool.and_self]; exact hin1
  have v7 : validCrate s6 (.rack 0) := by
    simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, hs6, apply, e5r]
  have w7 : windowOk win s6 (.rack 0) = true := by
    simp only [windowOk, List.all_eq_true, List.mem_range, Bool.or_eq_true, List.isEmpty_iff]
    intro k _; left; exact b6 _
  have e6r : s6.rack = 1 := rfl
  have d7 : denoteOp1 win s6 (.rack 0) = [] := by
    apply rackBraid_nil
    intro k _
    rw [ite_eq_left (by rw [e6r]; omega)]
    right; simp [backAt, b6]
  refine ⟨apply s6 (.rack 0), ?_, rfl, rfl, fun q => k6 q⟩
  rw [denote1_cons_v _ v5 w5, denote1_cons_v _ v6 w6, denote1_single_op v7 w7, d5, d7]
  rfl
theorem denote_cons_split {win : Window} {s t : State} {op : Op} {ops : List Op} {u : BWord Label}
    (h : refusal s op = none) (hw : windowOk win s op = true)
    (hrest : denote win (apply s op) ops = some (t, u)) :
    denote win s (op :: ops) = some (t, denoteOp win s op ++ u)
Proof
:= by
  simp [denote, step, h, hw, hrest]
theorem denote_pre {win : Window} {s s1 t : State} {a b : List Op} {u : BWord Label}
    (ha : denote1 win s a = some (s1, [])) (hns : ∀ op ∈ a, NotSplit op) (hb : denote win s1 b = some (t, u)) :
    denote win s (a ++ b) = some (t, u)
Proof
:= by
  have := denote_append win s a b s1 t [] u (by simpa [liftB] using denote_of_denote1 win s a s1 [] hns ha) hb
  simpa using this
theorem splitR_mid (win : Window) (s : State) (bd : Bed) (c1 : Int) (k : Nat) (hr : s.rack = 0)
    (hb : ∀ j, s.stk ⟨.b, j⟩ = []) (hcar : s.carrier = c1) (hk : (s.stk ⟨.f, c1⟩).length = k) (hk0 : 0 < k)
    (hf1 : s.stk ⟨.f, c1 + 1⟩ = []) (hlo : win.lo + 1 ≤ c1) (hhi : c1 + 4 < win.lo + win.w) :
    ∃ s', denote win s (splitOps .R bd c1) =
        some (s', [.box (.splitK .R bd k) (strandsBefore win s c1)]) ∧
      s'.rack = 0 ∧ (∀ j, s'.stk ⟨.b, j⟩ = []) ∧ s'.carrier = c1 + 2 ∧
      (s'.stk ⟨.f, c1⟩).length = (if bd = .f then 1 else k) ∧
      (s'.stk ⟨.f, c1 + 1⟩).length = (if bd = .f then k else 1) ∧
      ∀ i, i ≠ c1 → i ≠ c1 + 1 → s'.stk ⟨.f, i⟩ = s.stk ⟨.f, i⟩
Proof
:= by
  have hne : (s.stk ⟨.f, c1⟩).length ≠ 0 := by omega
  have in0 : win.inside c1 = true := inside_of (by omega) (by omega)
  have in1 : win.inside (c1 + 1) = true := inside_of (by omega) (by omega)
  cases bd with
  | f =>
    set s3 := apply s (.split .R ⟨.f, c1⟩ ⟨.b, c1⟩) with hs3
    have k3 : ∀ q, s3.stk q = if q = ⟨.f, c1⟩ then [s.fresh] else if q = ⟨.b, c1⟩ then
        (s.stk ⟨.f, c1⟩).reverse else s.stk q := by
      intro q; simp only [hs3, apply, upd_apply, xferStack, hb, List.append_nil]
      by_cases h : q = ⟨.b, c1⟩
      · subst h; simp
      · simp [h]
    have e3r : s3.rack = 0 := hr
    have e3c : s3.carrier = c1 + 1 := by simp [hs3, apply, slot, leavesTo, hr]
    set s4 := apply s3 (.miss .R (fN (c1 + 1))) with hs4
    have e4c : s4.carrier = c1 + 2 := by simp [hs4, apply, slot, fN, leavesTo, e3r]; omega
    have e4s : s4.stk = s3.stk := rfl
    have v4 : validCrate s3 (.miss .R (fN (c1 + 1))) := by
      simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, fN, slot, arrivesFrom, e3c, e3r]
    have w4 : windowOk win s3 (.miss .R (fN (c1 + 1))) = true := by simp only [windowOk, slot, fN]; exact in1
    have b3 : ∀ j, j ≠ c1 → s3.stk ⟨.b, j⟩ = [] := by intro j h; simp [k3, h, hb]
    have d4 : denoteOp1 win s3 (.miss .R (fN (c1 + 1))) = [] :=
      miss_free _ _ _ _ (by simp [frontAt, slot, fN, k3, hf1]) (by
        simp only [backAt, slot, fN, e3r]; rw [b3 _ (by omega)]; rfl)
    obtain ⟨s7, hd7, r7, c7, k7⟩ := post3 win s4 c1 e3r b3 (by rw [e4c]; omega)
      (by rw [e4s, k3]; simp [hf1]) in1
    refine ⟨s7, ?_, r7, ?_, by rw [c7, e4c], ?_, ?_, ?_⟩
    · have hsplit : refusal s (.split .R ⟨.f, c1⟩ ⟨.b, c1⟩) = none := by
        simp [refusal, linRefusal, extraRefusal, erase, slot, arrivesFrom, aligned, hcar, hr, hne]
      have hw : windowOk win s (.split .R ⟨.f, c1⟩ ⟨.b, c1⟩) = true := by
        simp only [windowOk, slot, hr, Int.add_zero, Bool.and_self]; exact in0
      have hpost : denote1 win s3 (.miss .R (fN (c1 + 1)) :: [.rack 1, .xfer (bN c1) (fN (c1 + 1)), .rack 0]) =
          some (s7, []) := by
        rw [denote1_cons_v _ v4 w4, hd7, d4]; rfl
      have hpostF := denote_of_denote1 win s3 _ s7 [] (by
        intro op hop; simp at hop; rcases hop with h | h | h | h <;> subst h <;> trivial) hpost
      show denote win s (.split .R ⟨.f, c1⟩ ⟨.b, c1⟩ :: .miss .R (fN (c1 + 1)) ::
        [.rack 1, .xfer (bN c1) (fN (c1 + 1)), .rack 0]) = _
      rw [denote_cons_split hsplit hw hpostF]
      have hK : backAt s c1 = 0 := by simp [backAt, hb]
      simp only [denoteOp, slot, arrivesFrom, hK, hk, swapBlocks_right_zero]
      simp [plainB, liftB]
    · intro j; rw [k7]
      by_cases h : j = c1
      · subst h; simp
      · simp [h]; exact b3 j h
    · rw [k7]; simp [e4s, k3]
    · rw [k7]; simp [e4s, k3, hk]
    · intro i h0 h1
      rw [k7]; simp [h1, e4s, k3, h0]
  | b =>
    set sX := apply s (.xfer (fN c1) (bN c1)) with hsX
    have kX : ∀ q, sX.stk q = if q = ⟨.b, c1⟩ then (s.stk ⟨.f, c1⟩).reverse else if q = ⟨.f, c1⟩ then []
        else s.stk q := by
      intro q; simp only [hsX, apply, upd_apply, xferStack, hb, List.append_nil, fN, bN]
    have eXr : sX.rack = 0 := hr
    have eXc : sX.carrier = c1 := hcar
    have vX : validCrate s (.xfer (fN c1) (bN c1)) := by
      simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, slot, aligned, hr, fN, bN]
    have wX : windowOk win s (.xfer (fN c1) (bN c1)) = true := by
      simp only [windowOk, slot, hr, fN, bN, Int.add_zero, Bool.and_self]; exact in0
    have hneX : (sX.stk ⟨.b, c1⟩).length ≠ 0 := by rw [kX, ite_eq_left rfl, List.length_reverse]; exact hne
    set s3 := apply sX (.split .R ⟨.b, c1⟩ ⟨.f, c1⟩) with hs3
    have k3 : ∀ q, s3.stk q = if q = ⟨.b, c1⟩ then [sX.fresh] else if q = ⟨.f, c1⟩ then
        s.stk ⟨.f, c1⟩ else s.stk q := by
      intro q; simp only [hs3, apply, upd_apply, xferStack, kX]
      by_cases h : q = ⟨.f, c1⟩
      · subst h; simp
      · by_cases h' : q = ⟨.b, c1⟩
        · subst h'; simp
        · simp [h, h']
    have e3r : s3.rack = 0 := hr
    have e3c : s3.carrier = c1 + 1 := by simp [hs3, apply, slot, leavesTo, eXr]
    set s4 := apply s3 (.miss .R (fN (c1 + 1))) with hs4
    have e4c : s4.carrier = c1 + 2 := by simp [hs4, apply, slot, fN, leavesTo, e3r]; omega
    have e4s : s4.stk = s3.stk := rfl
    have v4 : validCrate s3 (.miss .R (fN (c1 + 1))) := by
      simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, fN, slot, arrivesFrom, e3c, e3r]
    have w4 : windowOk win s3 (.miss .R (fN (c1 + 1))) = true := by simp only [windowOk, slot, fN]; exact in1
    have b3 : ∀ j, j ≠ c1 → s3.stk ⟨.b, j⟩ = [] := by intro j h; simp [k3, h, hb]
    have d4 : denoteOp1 win s3 (.miss .R (fN (c1 + 1))) = [] :=
      miss_free _ _ _ _ (by simp [frontAt, slot, fN, k3, hf1]) (by
        simp only [backAt, slot, fN, e3r]; rw [b3 _ (by omega)]; rfl)
    obtain ⟨s7, hd7, r7, c7, k7⟩ := post3 win s4 c1 e3r b3 (by rw [e4c]; omega)
      (by rw [e4s, k3]; simp [hf1]) in1
    refine ⟨s7, ?_, r7, ?_, by rw [c7, e4c], ?_, ?_, ?_⟩
    · have hsplit : refusal sX (.split .R ⟨.b, c1⟩ ⟨.f, c1⟩) = none := by
        simp [refusal, linRefusal, extraRefusal, erase, slot, arrivesFrom, aligned, eXc, eXr, hneX]
      have hw : windowOk win sX (.split .R ⟨.b, c1⟩ ⟨.f, c1⟩) = true := by
        simp only [windowOk, slot, eXr, Int.add_zero, Bool.and_self]; exact in0
      have hpost : denote1 win s3 (.miss .R (fN (c1 + 1)) :: [.rack 1, .xfer (bN c1) (fN (c1 + 1)), .rack 0]) =
          some (s7, []) := by
        rw [denote1_cons_v _ v4 w4, hd7, d4]; rfl
      have hpostF := denote_of_denote1 win s3 _ s7 [] (by
        intro op hop; simp at hop; rcases hop with h | h | h | h <;> subst h <;> trivial) hpost
      show denote win s ([.xfer (fN c1) (bN c1)] ++ (.split .R ⟨.b, c1⟩ ⟨.f, c1⟩ :: .miss .R (fN (c1 + 1)) ::
        [.rack 1, .xfer (bN c1) (fN (c1 + 1)), .rack 0])) = _
      rw [denote_pre (denote1_single_op vX wX) (by intro op hop; simp at hop; subst hop; trivial)
        (denote_cons_split hsplit hw hpostF)]
      have hF : frontAt sX c1 = 0 := by simp [frontAt, kX]
      have hsbX : strandsBefore win sX c1 = strandsBefore win s c1 := by
        apply sb_congr' win (by omega)
        intro p _ hp
        rw [segW_eq, segW_eq]
        simp only [yarnAt, frontAt, backAt, eXc, eXr, hr, kX, Int.sub_zero, hcar]
        simp [show p ≠ c1 by omega]
      have hl : (sX.stk ⟨.b, c1⟩).length = k := by rw [kX]; simp [hk]
      rw [← hsX]
      simp only [denoteOp, slot, eXr, arrivesFrom, hF, hl, hsbX, Int.add_zero,
        swapBlocks_right_zero]
      simp [plainB, liftB]
    · intro j; rw [k7]
      by_cases h : j = c1
      · subst h; simp
      · simp [h]; exact b3 j h
    · rw [k7]; simp [e4s, k3, hk]
    · rw [k7]; simp [e4s, k3]
    · intro i h0 h1
      rw [k7]; simp [h1, e4s, k3, h0]
theorem splitL_mid (win : Window) (s : State) (bd : Bed) (c1 : Int) (k : Nat) (hr : s.rack = 0)
    (hb : ∀ j, s.stk ⟨.b, j⟩ = []) (hcar : s.carrier = c1 + 1) (hk : (s.stk ⟨.f, c1⟩).length = k) (hk0 : 0 < k)
    (hf1 : s.stk ⟨.f, c1 + 1⟩ = []) (hlo : win.lo + 1 ≤ c1) (hhi : c1 + 4 < win.lo + win.w) :
    ∃ s', denote win s (splitOps .L bd c1) =
        some (s', [.box (.splitK .L bd k) (strandsBefore win s c1)]) ∧
      s'.rack = 0 ∧ (∀ j, s'.stk ⟨.b, j⟩ = []) ∧ s'.carrier = c1 ∧
      (s'.stk ⟨.f, c1⟩).length = (if bd = .f then 1 else k) ∧
      (s'.stk ⟨.f, c1 + 1⟩).length = (if bd = .f then k else 1) ∧
      ∀ i, i ≠ c1 → i ≠ c1 + 1 → s'.stk ⟨.f, i⟩ = s.stk ⟨.f, i⟩
Proof
:= by
  have hne : (s.stk ⟨.f, c1⟩).length ≠ 0 := by omega
  have in0 : win.inside c1 = true := inside_of (by omega) (by omega)
  have in1 : win.inside (c1 + 1) = true := inside_of (by omega) (by omega)
  cases bd with
  | f =>
    set s3 := apply s (.split .L ⟨.f, c1⟩ ⟨.b, c1⟩) with hs3
    have k3 : ∀ q, s3.stk q = if q = ⟨.f, c1⟩ then [s.fresh] else if q = ⟨.b, c1⟩ then
        (s.stk ⟨.f, c1⟩).reverse else s.stk q := by
      intro q; simp only [hs3, apply, upd_apply, xferStack, hb, List.append_nil]
      by_cases h : q = ⟨.b, c1⟩
      · subst h; simp
      · simp [h]
    have e3r : s3.rack = 0 := hr
    have e3c : s3.carrier = c1 := by simp [hs3, apply, slot, leavesTo, hr]
    have b3 : ∀ j, j ≠ c1 → s3.stk ⟨.b, j⟩ = [] := by intro j h; simp [k3, h, hb]
    obtain ⟨s7, hd7, r7, c7, k7⟩ := post3 win s3 c1 e3r b3 (by rw [e3c]; omega)
      (by rw [k3]; simp [hf1]) in1
    refine ⟨s7, ?_, r7, ?_, by rw [c7, e3c], ?_, ?_, ?_⟩
    · have hsplit : refusal s (.split .L ⟨.f, c1⟩ ⟨.b, c1⟩) = none := by
        simp [refusal, linRefusal, extraRefusal, erase, slot, arrivesFrom, aligned, hcar, hr, hne]
      have hw : windowOk win s (.split .L ⟨.f, c1⟩ ⟨.b, c1⟩) = true := by
        simp only [windowOk, slot, hr, Int.add_zero, Bool.and_self]; exact in0
      have hpostF := denote_of_denote1 win s3 _ s7 [] (by
        intro op hop; simp at hop; rcases hop with h | h | h <;> subst h <;> trivial) hd7
      show denote win s (.split .L ⟨.f, c1⟩ ⟨.b, c1⟩ :: [.rack 1, .xfer (bN c1) (fN (c1 + 1)), .rack 0]) = _
      rw [denote_cons_split hsplit hw hpostF]
      have hK : backAt s c1 = 0 := by simp [backAt, hb]
      have hF : frontAt s c1 = 2 * k := by simp [frontAt, hk]
      have hsb1 : strandsBefore win s (c1 + 1) = strandsBefore win s c1 + 2 * k := by
        rw [sb_succ win s (by omega), segW_eq, hK, hF]
        simp [yarnAt, hcar]
      simp only [denoteOp, slot, arrivesFrom, hK, hF, hk, hsb1, swapBlocks_left_zero,
        Nat.sub_zero, Nat.add_sub_cancel]
      simp [plainB, liftB]
    · intro j; rw [k7]
      by_cases h : j = c1
      · subst h; simp
      · simp [h]; exact b3 j h
    · rw [k7]; simp [k3]
    · rw [k7]; simp [k3, hk]
    · intro i h0 h1
      rw [k7]; simp [h1, k3, h0]
  | b =>
    set sX := apply s (.xfer (fN c1) (bN c1)) with hsX
    have kX : ∀ q, sX.stk q = if q = ⟨.b, c1⟩ then (s.stk ⟨.f, c1⟩).reverse else if q = ⟨.f, c1⟩ then []
        else s.stk q := by
      intro q; simp only [hsX, apply, upd_apply, xferStack, hb, List.append_nil, fN, bN]
    have eXr : sX.rack = 0 := hr
    have eXc : sX.carrier = c1 + 1 := hcar
    have vX : validCrate s (.xfer (fN c1) (bN c1)) := by
      simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, slot, aligned, hr, fN, bN]
    have wX : windowOk win s (.xfer (fN c1) (bN c1)) = true := by
      simp only [windowOk, slot, hr, fN, bN, Int.add_zero, Bool.and_self]; exact in0
    have hneX : (sX.stk ⟨.b, c1⟩).length ≠ 0 := by rw [kX, ite_eq_left rfl, List.length_reverse]; exact hne
    set s3 := apply sX (.split .L ⟨.b, c1⟩ ⟨.f, c1⟩) with hs3
    have k3 : ∀ q, s3.stk q = if q = ⟨.b, c1⟩ then [sX.fresh] else if q = ⟨.f, c1⟩ then
        s.stk ⟨.f, c1⟩ else s.stk q := by
      intro q; simp only [hs3, apply, upd_apply, xferStack, kX]
      by_cases h : q = ⟨.f, c1⟩
      · subst h; simp
      · by_cases h' : q = ⟨.b, c1⟩
        · subst h'; simp
        · simp [h, h']
    have e3r : s3.rack = 0 := hr
    have e3c : s3.carrier = c1 := by simp [hs3, apply, slot, leavesTo, eXr]
    have b3 : ∀ j, j ≠ c1 → s3.stk ⟨.b, j⟩ = [] := by intro j h; simp [k3, h, hb]
    obtain ⟨s7, hd7, r7, c7, k7⟩ := post3 win s3 c1 e3r b3 (by rw [e3c]; omega)
      (by rw [k3]; simp [hf1]) in1
    refine ⟨s7, ?_, r7, ?_, by rw [c7, e3c], ?_, ?_, ?_⟩
    · have hsplit : refusal sX (.split .L ⟨.b, c1⟩ ⟨.f, c1⟩) = none := by
        simp [refusal, linRefusal, extraRefusal, erase, slot, arrivesFrom, aligned, eXc, eXr, hneX]
      have hw : windowOk win sX (.split .L ⟨.b, c1⟩ ⟨.f, c1⟩) = true := by
        simp only [windowOk, slot, eXr, Int.add_zero, Bool.and_self]; exact in0
      have hpostF := denote_of_denote1 win s3 _ s7 [] (by
        intro op hop; simp at hop; rcases hop with h | h | h <;> subst h <;> trivial) hd7
      show denote win s ([.xfer (fN c1) (bN c1)] ++ (.split .L ⟨.b, c1⟩ ⟨.f, c1⟩ ::
        [.rack 1, .xfer (bN c1) (fN (c1 + 1)), .rack 0])) = _
      rw [denote_pre (denote1_single_op vX wX) (by intro op hop; simp at hop; subst hop; trivial)
        (denote_cons_split hsplit hw hpostF)]
      have hF : frontAt sX c1 = 0 := by simp [frontAt, kX]
      have hK : backAt sX c1 = 2 * k := by simp [backAt, eXr, kX, hk]
      have hsbX : strandsBefore win sX c1 = strandsBefore win s c1 := by
        apply sb_congr' win (by omega)
        intro p _ hp
        rw [segW_eq, segW_eq]
        simp only [yarnAt, frontAt, backAt, eXc, eXr, hr, kX, Int.sub_zero, hcar]
        simp [show p ≠ c1 by omega]
      have hsb1 : strandsBefore win sX (c1 + 1) = strandsBefore win s c1 + 2 * k := by
        rw [sb_succ win sX (by omega), segW_eq, hK, hF, hsbX]
        simp [yarnAt, eXc]
      have hl : (sX.stk ⟨.b, c1⟩).length = k := by rw [kX]; simp [hk]
      rw [← hsX]
      simp only [denoteOp, slot, eXr, arrivesFrom, hF, hK, hl, hsb1, Int.add_zero, swapBlocks_left_zero,
        Nat.add_sub_cancel, Nat.sub_zero]
      simp [plainB, liftB]
    · intro j; rw [k7]
      by_cases h : j = c1
      · subst h; simp
      · simp [h]; exact b3 j h
    · rw [k7]; simp [k3, hk]
    · rw [k7]; simp [k3]
    · intro i h0 h1
      rw [k7]; simp [h1, k3, h0]

Fragment: split

split_frag : FragmentFor 2 isSplit, for both directions, both beds and every stack size k.

  • The carrier moves to the side of the stack's needle c1 that it arrives from. This draws nothing.
  • splitR_mid, splitL_mid: then one box splitK d bd k at offset r (firstIdx r d).
  • The new loop and the old stack end on front needles c1 and c1 + 1. This is splitRow d bd k at the compiler's new coordinates.
namespace FormalizeKnitting.Bridge.RM.Frag
open FormalizeKnitting.Knitout
theorem splitOps_notSplit_post (d : Dir) (bd : Bed) (c1 : Int) :
    Op.xfer (bN c1) (fN (c1 + 1)) ∈ splitOps d bd c1
Proof
:= by
  cases d <;> cases bd <;> simp [splitOps]
theorem stack_scpos {r : Row} (hy : r.count .yarn = 1) {j : Nat} (hj : j < r.length) (hne : j ≠ yarnIdx r)
    (x : Int) : scpos (r.getD j .yarn) x = 2 * x
Proof
:= by
  cases h : r.getD j .yarn with
  | yarn => exact absurd ((getD_eq_yarn_iff hy hj).mp h) hne
  | stack k => rfl
theorem split_frag : FragmentFor 2 isSplit
Proof
:= by
  intro win c c1 st s r' M hs hL hc hF hrs hcs hpre hN
  cases s with
  | x _ _ => exact hs.elim
  | drop _ => exact hs.elim
  | merge _ => exact hs.elim
  | tuck _ => exact hs.elim
  | knit _ _ => exact hs.elim
  | split d bd =>
  have hy := hL.1
  have hym := yarn_mem hy
  have hyl := yarnIdx_lt hy
  set y := yarnIdx c.row with hydef
  have hlo := fits_lo hF hc (by omega)
  have hcar : st.carrier = 3 + 2 * (y : Int) := laid_carrier hL hc
  have hr : st.rack = 0 := hL.2.2.1
  have hb : ∀ j, st.stk ⟨.b, j⟩ = [] := hL.2.2.2.1
  have hys : c.at_.getD (yarnIdx c.row) 0 = 3 + 2 * (y : Int) := by rw [hc]; exact canonical_getD_two hyl
  cases hk : stackAt c.row (besideIdx c.row d) with
  | none => simp [runStepB, hk] at hrs
  | some k =>
  obtain ⟨hbl, hga, hk0⟩ := stackAt_some hk
  have hbyl : besideIdx c.row d ≠ y := by
    intro h; rw [h, getD_yarnIdx _ hy] at hga; exact absurd hga (by simp)
  have hhb : hasBeside c.row d = true := by
    cases d <;> simp [hasBeside, besideIdx] at hbl hbyl ⊢ <;> omega
  simp only [runStepB, hym, hhb, and_self, ite_true, hk, Option.some.injEq, Prod.mk.injEq] at hrs
  obtain ⟨rfl, rfl⟩ := hrs
  have hbc : c.at_.getD (besideIdx c.row d) 0 = 3 + 2 * ((besideIdx c.row d : Nat) : Int) := by
    rw [hc]; exact canonical_getD_two hbl
  simp only [compileStep, hym, hhb, and_self, ite_true, hk, Option.some.injEq, hbc, hys] at hcs
  subst hcs
  have hsbc := strandsBefore_canon hL hc win (by omega)
  have hfront := laid_front_at hL hc
  have hoff := laid_front_off hL hc
  cases d with
  | R =>
    have e1 : besideIdx c.row .R = y + 1 := rfl
    have e2 : firstIdx c.row .R = y := rfl
    simp only [e1, e2] at hga hbl hN hpre ⊢
    set cc : Int := 3 + 2 * (y : Int) with hccdef
    have ec1 : 3 + 2 * ((y + 1 : Nat) : Int) = cc + 2 := by push_cast; omega
    simp only [ec1] at hN hpre ⊢
    have hn3 := hN (.xfer (bN (cc + 2)) (fN (cc + 2 + 1)))
      (List.mem_append_right _ (List.mem_append_right _ (splitOps_notSplit_post _ _ _))) (cc + 2 + 1)
      (by simp [Op.named, fN])
    have hfit := fits_canon hF hc hbl
    push_cast at hfit
    refine ⟨?_, ?_⟩
    · show Fits win ⟨_, spliceL c.at_ y 2 [cc + 2, cc + 2 + 1, cc + 2 + 2], _⟩
      rw [hc]; apply fits_splice hF _ _ _ _ _ hc
      intro x hx; simp at hx; omega
    have hyt : yarnTo cc (cc + 2) = (List.range 2).map fun t : Nat => Op.miss .R (fN (cc + t)) := by
      unfold yarnTo; rw [ite_eq_left (by omega), show (cc + 2 - cc).toNat = 2 by omega, bind_coe_map]
    have hY := Knit.missR_walk win st cc hr hcar hb 2 (fun t ht => by
      refine ⟨?_, inside_of (by omega) (by omega)⟩
      by_cases h0 : t = 0
      · subst h0; simpa using laid_front_yarn hL hc
      · exact hoff _ (fun j => by omega))
    set sY : State := { st with carrier := cc + ((2 : Nat) : Int) } with hsY
    have hkk' : (st.stk ⟨.f, cc + 2⟩).length = k := by
      rw [← ec1, hfront, hga]; rfl
    have hf3 : st.stk ⟨.f, cc + 2 + 1⟩ = [] := hoff _ (fun j => by omega)
    obtain ⟨sF, hdK, rF, bF, cF, nF, mF, tF⟩ := splitR_mid win sY bd (cc + 2) k hr hb
      (by simp [hsY]) hkk' hk0 hf3 (by omega) (by omega)
    have hsb : strandsBefore win sY (cc + 2) = offset c.row y := by
      have e := sb_add win sY (i := cc) (by omega) 2
      rw [show cc + ((2 : Nat) : Int) = cc + 2 by simp] at e
      rw [e]
      have hB : strandsBefore win sY cc = strandsBefore win st cc := by
        apply sb_congr' win (by omega)
        intro p _ hp
        rw [segW_eq, segW_eq]
        simp only [yarnAt, frontAt, backAt, hsY, hcar]
        rw [ite_eq_right (by push_cast; omega), ite_eq_right (by omega)]
      rw [hB, hccdef, hsbc y (by omega)]
      simp only [Finset.sum_range_succ, Finset.sum_range_zero, Nat.zero_add]
      rw [segW_eq, segW_eq]
      simp only [yarnAt, frontAt, backAt, hsY, hr, hb, sub_zero]
      rw [ite_eq_right (by push_cast; omega), ite_eq_right (by push_cast; omega)]
      have h0 : st.stk ⟨.f, 3 + 2 * (y : Int) + ((0 : Nat) : Int)⟩ = [] := by simpa using laid_front_yarn hL hc
      have h1 : st.stk ⟨.f, 3 + 2 * (y : Int) + ((1 : Nat) : Int)⟩ = [] := hoff _ (fun j => by push_cast; omega)
      rw [h0, h1]; rfl
    rw [hsb] at hdK
    refine ⟨sF, ?_, ?_⟩
    · show denote win st ((c.ops ++ (yarnTo cc (cc + 2) ++ splitOps .R bd (cc + 2))).drop c.ops.length) = _
      rw [List.drop_left]
      have hY' : denote1 win st (yarnTo cc (cc + 2)) = some (sY, []) := by rw [hyt]; exact hY
      exact denote_pre hY' (yarnTo_notSplit _ _) hdK
    · show Laid ⟨spliceL c.row y 2 (splitRow .R bd k), spliceL c.at_ y 2 [cc + 2, cc + 2 + 1, cc + 2 + 2], _⟩ sF
      rw [hc]
      have hseg2 : ((c.row.drop y).take 2).count .yarn = 1 := by
        rw [seg1_two _ hbl .yarn, getD_yarnIdx _ hy, hga]; simp
      have hy' : (spliceL c.row y 2 (splitRow .R bd k)).count .yarn = 1 := by
        rw [count_splice, hseg2]; cases bd <;> simp [hy, splitRow]
      have hl' : y + 2 < (spliceL c.row y 2 (splitRow .R bd k)).length := by
        rw [length_spliceL _ _ _ _ (by omega)]; cases bd <;> simp [splitRow] <;> omega
      have hyi : yarnIdx (spliceL c.row y 2 (splitRow .R bd k)) = y + 2 := by
        apply yarnIdx_of hy' hl'
        rw [getD_spliceL _ _ _ _ _ (by omega)]; cases bd <;> simp [splitRow]
      apply laid_splice hL hc y 2 (splitRow .R bd k) [cc + 2, cc + 2 + 1, cc + 2 + 2] _ hbl
        (by cases bd <;> rfl) hy' rF bF
      · intro i
        rw [loadAt_seg_two _ hbl, getD_yarnIdx _ hy, hga, ec1]
        by_cases hi : i = cc + 2
        · subst hi
          rw [hkk']
          cases bd <;> simp [splitRow, loadAt, stackSize, nF]; omega
        · by_cases hi1 : i = cc + 2 + 1
          · subst hi1
            rw [hf3]
            cases bd <;> simp [splitRow, loadAt, stackSize, mF]
          · rw [tF i hi hi1]
            cases bd <;> simp [splitRow, loadAt, stackSize, Ne.symm hi, Ne.symm hi1] <;> rfl
      · rw [hyi, getD_spliceL _ _ _ _ _ (by rw [canonical_length]; omega)]
        rw [cF]; cases bd <;> simp
      · intro t ht
        have : t = 0 ∨ t = 1 := by cases bd <;> simp [splitRow] at ht <;> omega
        rcases this with rfl | rfl <;> cases bd <;> simp [scpos, splitRow] <;> omega
      · intro _ _; refine lt_of_le_of_lt (scpos_hi _ _) ?_; cases bd <;> simp [scpos, splitRow] <;> omega
      · intro h2 _
        rw [stack_scpos hy h2 (by omega)]
        cases bd <;> simp [scpos, splitRow] <;> omega
  | L =>
    have e1 : besideIdx c.row .L = y - 1 := rfl
    have e2 : firstIdx c.row .L = y - 1 := rfl
    have hy1 : 1 ≤ y := by
      by_contra h0
      have : besideIdx c.row .L = y := by rw [e1]; omega
      exact hbyl this
    simp only [e1, e2] at hga hbl hN hpre ⊢
    set cc : Int := 3 + 2 * (y : Int) with hccdef
    have ec1 : 3 + 2 * ((y - 1 : Nat) : Int) = cc - 2 := by push_cast [hy1]; omega
    simp only [ec1] at hN hpre ⊢
    have hn3 := hN (.xfer (bN (cc - 2)) (fN (cc - 2 + 1)))
      (List.mem_append_right _ (List.mem_append_right _ (splitOps_notSplit_post _ _ _))) (cc - 2 + 1)
      (by simp [Op.named, fN])
    have hfit := fits_canon hF hc hbl
    rw [ec1] at hfit
    refine ⟨?_, ?_⟩
    · show Fits win ⟨_, spliceL c.at_ (y - 1) 2 [cc - 2, cc - 2, cc - 2 + 1], _⟩
      rw [hc]; apply fits_splice hF _ _ _ _ _ hc
      intro x hx; simp at hx; omega
    have hyt : yarnTo cc (cc - 2 + 1) = (List.range 1).map fun t : Nat => Op.miss .L (fN (cc - 1 - t)) := by
      unfold yarnTo; rw [ite_eq_right (by omega), show (cc - (cc - 2 + 1)).toNat = 1 by omega, bind_coe_map]
    have hY := Knit.missL_walk win st cc hr hcar hb 1 (fun t ht => by
      refine ⟨hoff _ (fun j => by omega), inside_of (by omega) (by omega)⟩)
    set sY : State := { st with carrier := cc - ((1 : Nat) : Int) } with hsY
    have hkk' : (st.stk ⟨.f, cc - 2⟩).length = k := by
      rw [← ec1, hfront, hga]; rfl
    have hf3 : st.stk ⟨.f, cc - 2 + 1⟩ = [] := hoff _ (fun j => by omega)
    obtain ⟨sF, hdK, rF, bF, cF, nF, mF, tF⟩ := splitL_mid win sY bd (cc - 2) k hr hb
      (by simp [hsY]; omega) hkk' hk0 hf3 (by omega) (by omega)
    have hsb : strandsBefore win sY (cc - 2) = offset c.row (y - 1) := by
      have hB : strandsBefore win sY (cc - 2) = strandsBefore win st (cc - 2) := by
        apply sb_congr' win (by omega)
        intro p _ hp
        rw [segW_eq, segW_eq]
        simp only [yarnAt, frontAt, backAt, hsY, hcar]
        rw [ite_eq_right (by push_cast; omega), ite_eq_right (by omega)]
      rw [hB, ← ec1, hsbc (y - 1) (by omega)]
    rw [hsb] at hdK
    refine ⟨sF, ?_, ?_⟩
    · show denote win st ((c.ops ++ (yarnTo cc (cc - 2 + 1) ++ splitOps .L bd (cc - 2))).drop c.ops.length) = _
      rw [List.drop_left]
      have hY' : denote1 win st (yarnTo cc (cc - 2 + 1)) = some (sY, []) := by rw [hyt]; exact hY
      exact denote_pre hY' (yarnTo_notSplit _ _) hdK
    · show Laid ⟨spliceL c.row (y - 1) 2 (splitRow .L bd k), spliceL c.at_ (y - 1) 2 [cc - 2, cc - 2, cc - 2 + 1], _⟩ sF
      rw [hc]
      have hbl2 : y - 1 + 1 < c.row.length := by omega
      have ey : y - 1 + 1 = y := by omega
      have hseg2 : ((c.row.drop (y - 1)).take 2).count .yarn = 1 := by
        rw [seg1_two _ hbl2 .yarn, ey, getD_yarnIdx _ hy, hga]; simp
      have hy' : (spliceL c.row (y - 1) 2 (splitRow .L bd k)).count .yarn = 1 := by
        rw [count_splice, hseg2]; cases bd <;> simp [hy, splitRow]
      have hl' : y - 1 < (spliceL c.row (y - 1) 2 (splitRow .L bd k)).length := by
        rw [length_spliceL _ _ _ _ (by omega)]; cases bd <;> simp [splitRow] <;> omega
      have hyi : yarnIdx (spliceL c.row (y - 1) 2 (splitRow .L bd k)) = y - 1 := by
        apply yarnIdx_of hy' hl'
        rw [getD_spliceL _ _ _ _ _ (by omega)]; cases bd <;> simp [splitRow]
      apply laid_splice hL hc (y - 1) 2 (splitRow .L bd k) [cc - 2, cc - 2, cc - 2 + 1] _ (by omega)
        (by cases bd <;> rfl) hy' rF bF
      · intro i
        rw [loadAt_seg_two _ hbl2, ey, getD_yarnIdx _ hy, hga, ec1]
        have ecy : 3 + 2 * ((y : Nat) : Int) = cc := rfl
        rw [ecy]
        by_cases hi : i = cc - 2
        · subst hi
          rw [hkk']
          cases bd <;> simp [splitRow, loadAt, stackSize, nF]; omega
        · by_cases hi1 : i = cc - 2 + 1
          · subst hi1
            rw [hf3]
            cases bd <;> simp [splitRow, loadAt, stackSize, mF]
          · rw [tF i hi hi1]
            cases bd <;> simp [splitRow, loadAt, stackSize, Ne.symm hi, Ne.symm hi1] <;> rfl
      · rw [hyi, getD_spliceL _ _ _ _ _ (by rw [canonical_length]; omega)]
        rw [cF]; cases bd <;> simp
      · intro t ht
        have : t = 0 ∨ t = 1 := by cases bd <;> simp [splitRow] at ht <;> omega
        rcases this with rfl | rfl <;> cases bd <;> simp [scpos, splitRow]
      · intro _ _; refine lt_of_le_of_lt (scpos_hi _ _) ?_; cases bd <;> simp [scpos, splitRow] <;> omega
      · intro _ _; refine lt_of_lt_of_le ?_ (scpos_lo _ _); cases bd <;> simp [scpos, splitRow] <;> omega

Fragment: exchange, by the kinds of the two objects

x_frag_of_kinds gets FragmentFor 2 isX from three kinds of exchange.

  • XFrag P: FragmentFor 2 isX for the exchanges whose two objects satisfy P.
Kind Condition on objects a, a + 1 Proof
IsYS object a is the yarn xYS
IsSY object a + 1 is the yarn xSY
IsSS neither object is the yarn xSS
namespace FormalizeKnitting.Bridge.RM.Frag
open FormalizeKnitting.Knitout
def XFrag (P : Obj → Obj → Prop) : Prop :=
  ∀ (win : Window) (c c1 : Comp) (st : State) (a : Nat) (front : Bool) (r' : Row) (M : BWord Label),
    P (c.row.getD a .yarn) (c.row.getD (a + 1) .yarn) →
    Laid c st → c.at_ = canonical 2 c.row.length → Fits win c → runStepB c.row (.x a front) = some (r', M) →
    compileStep c (.x a front) = some c1 → c.ops <+: c1.ops → (∀ op ∈ c1.ops, NamedIn3 win op) →
    Fits win c1 ∧ ∃ st', denote win st (c1.ops.drop c.ops.length) = some (st', M) ∧ Laid c1 st'

def IsYS (o1 _o2 : Obj) : Prop := o1 = .yarn

def IsSY (_o1 o2 : Obj) : Prop := o2 = .yarn

def IsSS (o1 o2 : Obj) : Prop := o1 ≠ .yarn ∧ o2 ≠ .yarn
theorem x_frag_of_kinds (hYS : XFrag IsYS) (hSY : XFrag IsSY) (hSS : XFrag IsSS) : FragmentFor 2 isX
Proof
:= by
  intro win c c1 st s r' M hs
  cases s with
  | x a front =>
    by_cases h1 : c.row.getD a .yarn = .yarn
    · exact hYS win c c1 st a front r' M h1
    · by_cases h2 : c.row.getD (a + 1) .yarn = .yarn
      · exact hSY win c c1 st a front r' M h2
      · exact hSS win c c1 st a front r' M ⟨h1, h2⟩
  | tuck _ => exact hs.elim
  | merge _ => exact hs.elim
  | knit _ _ => exact hs.elim
  | split _ _ => exact hs.elim
  | drop _ => exact hs.elim

Fragment: yarn–stack exchange

xYS : XFrag IsYS. The yarn is at cc. A stack of k is at cc + 2. The carrier moves three slots right.

front Instructions Drawing
false three misses; they cross the stack's 2k strands swapBlocks off 1 (2k) false
true the stack goes to the back needle across, three misses, the stack comes back swapBlocks off 1 (2k) true
namespace FormalizeKnitting.Bridge.RM.Frag
open FormalizeKnitting.Knitout
theorem sb_two_free (win : Window) (st s : State) (cc : Int) (hlo : win.lo ≤ cc)
    (hagree : ∀ p, win.lo ≤ p → p < cc → segW s p = segW st p) (h0 : segW s cc = 0) (h1 : segW s (cc + 1) = 0) :
    strandsBefore win s (cc + 2) = strandsBefore win st cc
Proof
:= by
  have e := sb_add win s (i := cc) hlo 2
  rw [show cc + ((2 : Nat) : Int) = cc + 2 by simp] at e
  rw [e, sb_congr' win hlo hagree]
  simp [Finset.sum_range_succ, h0, h1]
theorem xYS : XFrag IsYS
Proof
:= by
  intro win c c1 st a front r' M hP hL hc hF hrs hcs hpre hN
  have hy := hL.1
  simp only [IsYS] at hP
  by_cases ha : a + 1 < c.row.length
  swap
  · simp [runStepB, ha] at hrs
  have hya : a = yarnIdx c.row := (getD_eq_yarn_iff hy (by omega)).mp hP
  obtain ⟨k, hk⟩ : ∃ k, c.row.getD (a + 1) .yarn = .stack k := by
    cases h : c.row.getD (a + 1) .yarn with
    | yarn => exact absurd ((getD_eq_yarn_iff hy ha).mp h) (by omega)
    | stack k => exact ⟨k, rfl⟩
  have hym := yarn_mem hy
  simp only [runStepB, hym, ha, and_self, ite_true, Option.some.injEq, Prod.mk.injEq, hP, hk] at hrs
  obtain ⟨rfl, rfl⟩ := hrs
  set cc : Int := 3 + 2 * (a : Int) with hccdef
  have hp : c.at_.getD a 0 = cc := by rw [hc]; exact canonical_getD_two (by omega)
  have hq : c.at_.getD (a + 1) 0 = cc + 2 := by rw [hc, canonical_getD_two ha]; push_cast; omega
  have hlen : a + 1 < c.at_.length := by rw [hc, canonical_length]; exact ha
  simp only [compileStep, hym, ha, and_self, ite_true, hP, hk, hp, hq, Option.map_some,
    Option.some.injEq, emit, show cc + 2 + 1 = cc + 3 by omega, Exch.yarnTo_R3] at hcs
  subst hcs
  have hat : swapAt (c.at_.set a (cc + 3)) a 0 = spliceL c.at_ a 2 [cc + 2, cc + 3] := by
    unfold swapAt
    rw [Exch.spliceL_set _ _ _ _ _ _ (le_refl a) (by omega), Exch.getD_set_ne _ _ _ _ _ (by omega),
      Exch.getD_set_eq _ _ _ _ (by omega), hq]
  simp only [hat] at hpre hN ⊢
  have hn3 := hN (.miss .R (fN (cc + 2))) (by cases front <;> simp) (cc + 2) (by simp [Op.named, fN])
  have hlo := fits_lo hF hc (by omega)
  have hfit := fits_canon hF hc (show a < c.row.length by omega)
  have hcar : st.carrier = cc := by rw [laid_carrier hL hc, ← hya]
  have hfy : st.stk ⟨.f, cc⟩ = [] := by have := laid_front_yarn hL hc; rw [← hya] at this; exact this
  have hf1 : st.stk ⟨.f, cc + 1⟩ = [] := laid_front_off hL hc _ (fun j => by omega)
  have ec : 3 + 2 * ((a + 1 : Nat) : Int) = cc + 2 := by push_cast; omega
  have hkk : (st.stk ⟨.f, cc + 2⟩).length = k := by rw [← ec, laid_front_at hL hc, hk]; rfl
  have hsb : strandsBefore win st cc = offset c.row a := strandsBefore_canon hL hc win (by omega) a (by omega)
  have hr := hL.2.2.1
  have hb := hL.2.2.2.1
  have ins : ∀ z, win.lo + 1 ≤ z → z + 2 ≤ win.lo + win.w → win.inside z = true := fun z h1 h2 => inside_of h1 h2
  have hfits : Fits win ⟨splice c.row a 2 [.stack k, .yarn], spliceL c.at_ a 2 [cc + 2, cc + 3], []⟩ := by
    rw [hc]; apply fits_splice hF _ _ _ _ _ hc
    intro x hx; simp at hx; omega
  have hlaid : ∀ (sF : State) (ops : List Op), sF.rack = 0 → (∀ q, sF.stk q = st.stk q) → sF.carrier = cc + 3 →
      Laid ⟨splice c.row a 2 [.stack k, .yarn], spliceL c.at_ a 2 [cc + 2, cc + 3], ops⟩ sF := by
    intro sF ops rF kF cF
    rw [splice_eq, hc]
    have hseg2 : ((c.row.drop a).take 2).count .yarn = 1 := by rw [seg1_two _ ha .yarn, hP, hk]; simp
    have hy' : (spliceL c.row a 2 [.stack k, .yarn]).count .yarn = 1 := by
      rw [count_splice, hseg2]; simp [hy]
    have hl' : a + 1 < (spliceL c.row a 2 [.stack k, .yarn]).length := by
      rw [length_spliceL _ _ _ _ (by omega)]; simp; omega
    have hyi : yarnIdx (spliceL c.row a 2 [.stack k, .yarn]) = a + 1 := by
      apply yarnIdx_of hy' hl'
      rw [getD_spliceL _ _ _ _ _ (by omega)]; simp
    apply laid_splice hL hc a 2 [.stack k, .yarn] [cc + 2, cc + 3] _ ha rfl hy' rF
    · intro j; rw [kF]; exact hb j
    · intro i
      rw [kF, loadAt_seg_two _ ha, hP, hk, ec]
      simp [loadAt, stackSize]
    · rw [hyi, getD_spliceL _ _ _ _ _ (by rw [canonical_length]; omega)]
      rw [cF]; simp
    · intro t ht
      have : t = 0 := by simp at ht; omega
      subst this; simp [scpos]; omega
    · intro h0 _; refine lt_of_le_of_lt (scpos_hi _ _) ?_; simp [scpos]; push_cast [show 1 ≤ a by omega]; omega
    · intro _ _; refine lt_of_lt_of_le ?_ (scpos_lo _ _); simp [scpos]; omega
  refine ⟨hfits, ?_⟩
  cases front with
  | false =>
    simp only [ite_false, Bool.false_eq_true, ite_false, List.nil_append, List.append_nil] at hpre hN ⊢
    set s1 := apply st (.miss .R (fN cc)) with hs1
    set s2 := apply s1 (.miss .R (fN (cc + 1))) with hs2
    set s3 := apply s2 (.miss .R (fN (cc + 2))) with hs3
    have e1c : s1.carrier = cc + 1 := by simp [hs1, apply, slot, fN, leavesTo, hr]
    have e2c : s2.carrier = cc + 2 := by simp [hs2, apply, slot, fN, leavesTo]; omega
    have e3c : s3.carrier = cc + 3 := by simp [hs3, apply, slot, fN, leavesTo]; omega
    have e1s : s1.stk = st.stk := rfl
    have e2s : s2.stk = st.stk := rfl
    have e3s : s3.stk = st.stk := rfl
    have e2r : s2.rack = 0 := hr
    have v1 : validCrate st (.miss .R (fN cc)) := by
      simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, fN, slot, arrivesFrom, hcar, hr]
    have v2 : validCrate s1 (.miss .R (fN (cc + 1))) := by
      simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, fN, slot, arrivesFrom, e1c]
    have v3 : validCrate s2 (.miss .R (fN (cc + 2))) := by
      simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, fN, slot, arrivesFrom, e2c, e2r]
    have w1 : windowOk win st (.miss .R (fN cc)) = true := by
      simp only [windowOk, slot, fN]; exact ins _ (by omega) (by omega)
    have w2 : windowOk win s1 (.miss .R (fN (cc + 1))) = true := by
      simp only [windowOk, slot, fN]; exact ins _ (by omega) (by omega)
    have w3 : windowOk win s2 (.miss .R (fN (cc + 2))) = true := by
      simp only [windowOk, slot, fN]; exact ins _ (by omega) (by omega)
    have d1 : denoteOp1 win st (.miss .R (fN cc)) = [] :=
      miss_free _ _ _ _ (by simp [frontAt, slot, fN, hfy]) (by simp [backAt, slot, fN, hb])
    have d2 : denoteOp1 win s1 (.miss .R (fN (cc + 1))) = [] :=
      miss_free _ _ _ _ (by simp [frontAt, slot, fN, e1s, hf1]) (by simp [backAt, slot, fN, e1s, hb])
    have hsb2 : strandsBefore win s2 (cc + 2) = offset c.row a := by
      rw [sb_two_free win st s2 cc (by omega) ?_ ?_ ?_, hsb]
      · intro p _ hp
        rw [segW_eq, segW_eq]; simp only [yarnAt, frontAt, backAt, e2c, e2s, e2r, hcar, hr]
        rw [ite_eq_right (by omega), ite_eq_right (by omega)]
      · rw [segW_eq]; simp only [yarnAt, frontAt, backAt, e2c, e2s, e2r, hfy, hb]; simp
      · rw [segW_eq]; simp only [yarnAt, frontAt, backAt, e2c, e2s, e2r, hf1, hb]; simp
    have d3 : denoteOp1 win s2 (.miss .R (fN (cc + 2))) = plainB (swapBlocks (offset c.row a) 1 (2 * k) false) := by
      have hK : backAt s2 (cc + 2) = 0 := by simp [backAt, e2s, e2r, hb]
      have hF : frontAt s2 (cc + 2) = 2 * k := by simp [frontAt, e2s, hkk]
      simp only [denoteOp1, slot, fN, arrivesFrom, hsb2, hK, hF, swapB_nil (Or.inr rfl),
        List.append_nil]
      rfl
    have hden : denote1 win st [.miss .R (fN cc), .miss .R (fN (cc + 1)), .miss .R (fN (cc + 2))] =
        some (s3, plainB (swapBlocks (offset c.row a) 1 (2 * k) false)) := by
      rw [denote1_cons_v _ v1 w1, denote1_cons_v _ v2 w2, denote1_single_op v3 w3, d1, d2, d3]; rfl
    refine ⟨s3, ?_, hlaid s3 _ hr (fun q => rfl) e3c⟩
    rw [List.drop_left]
    have := denote_of_denote1 win st _ _ _ (by
      intro op hop; simp at hop; rcases hop with h | h | h <;> subst h <;> trivial) hden
    rw [liftB_plainB] at this
    simpa [Obj.width] using this
  | true =>
    simp only [ite_true, List.cons_append, List.nil_append,
      ] at hpre hN ⊢
    have hq3 := hN (.xfer (fN (cc + 2)) (bN (cc + 2))) (by simp) (cc + 2) (by simp [Op.named, fN])
    set sX := apply st (.xfer (fN (cc + 2)) (bN (cc + 2))) with hsX
    have kX : ∀ q, sX.stk q = if q = ⟨.b, cc + 2⟩ then (st.stk ⟨.f, cc + 2⟩).reverse
        else if q = ⟨.f, cc + 2⟩ then [] else st.stk q := by
      intro q; simp only [hsX, apply, upd_apply, xferStack, hb, List.append_nil, fN, bN]
    set s1 := apply sX (.miss .R (fN cc)) with hs1
    set s2 := apply s1 (.miss .R (fN (cc + 1))) with hs2
    set s3 := apply s2 (.miss .R (fN (cc + 2))) with hs3
    set s4 := apply s3 (.xfer (bN (cc + 2)) (fN (cc + 2))) with hs4
    have eXr : sX.rack = 0 := hr
    have eXc : sX.carrier = cc := hcar
    have e1c : s1.carrier = cc + 1 := by simp [hs1, apply, slot, fN, leavesTo, eXr]
    have e2c : s2.carrier = cc + 2 := by simp [hs2, apply, slot, fN, leavesTo]; omega
    have e3c : s3.carrier = cc + 3 := by simp [hs3, apply, slot, fN, leavesTo]; omega
    have e1s : s1.stk = sX.stk := rfl
    have e2s : s2.stk = sX.stk := rfl
    have e3s : s3.stk = sX.stk := rfl
    have e1r : s1.rack = 0 := hr
    have e2r : s2.rack = 0 := hr
    have e3r : s3.rack = 0 := hr
    have k4 : ∀ q, s4.stk q = st.stk q := by
      intro q; simp only [hs4, apply, upd_apply, xferStack, e3s, kX, fN, bN]
      by_cases h : q = ⟨.f, cc + 2⟩
      · subst h; simp
      · by_cases h' : q = ⟨.b, cc + 2⟩
        · subst h'; simp [hb]
        · simp [h, h']
    have vX : validCrate st (.xfer (fN (cc + 2)) (bN (cc + 2))) := by
      simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, slot, aligned, hr, fN, bN]
    have wX : windowOk win st (.xfer (fN (cc + 2)) (bN (cc + 2))) = true := by
      simp only [windowOk, slot, hr, fN, bN, Int.add_zero, Bool.and_self]; exact ins _ (by omega) (by omega)
    have v1 : validCrate sX (.miss .R (fN cc)) := by
      simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, fN, slot, arrivesFrom, eXc, eXr]
    have v2 : validCrate s1 (.miss .R (fN (cc + 1))) := by
      simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, fN, slot, arrivesFrom, e1c, e1r]
    have v3 : validCrate s2 (.miss .R (fN (cc + 2))) := by
      simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, fN, slot, arrivesFrom, e2c, e2r]
    have v4 : validCrate s3 (.xfer (bN (cc + 2)) (fN (cc + 2))) := by
      simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, slot, aligned, e3r, fN, bN]
    have w1 : windowOk win sX (.miss .R (fN cc)) = true := by
      simp only [windowOk, slot, fN]; exact ins _ (by omega) (by omega)
    have w2 : windowOk win s1 (.miss .R (fN (cc + 1))) = true := by
      simp only [windowOk, slot, fN]; exact ins _ (by omega) (by omega)
    have w3 : windowOk win s2 (.miss .R (fN (cc + 2))) = true := by
      simp only [windowOk, slot, fN]; exact ins _ (by omega) (by omega)
    have w4 : windowOk win s3 (.xfer (bN (cc + 2)) (fN (cc + 2))) = true := by
      simp only [windowOk, slot, e3r, fN, bN, Int.add_zero, Bool.and_self]; exact ins _ (by omega) (by omega)
    have d1 : denoteOp1 win sX (.miss .R (fN cc)) = [] :=
      miss_free _ _ _ _ (by simp [frontAt, slot, fN, kX, hfy]) (by simp [backAt, slot, fN, kX, hb, eXr])
    have d2 : denoteOp1 win s1 (.miss .R (fN (cc + 1))) = [] :=
      miss_free _ _ _ _ (by simp [frontAt, slot, fN, e1s, kX, hf1]) (by simp [backAt, slot, fN, e1s, kX, hb, e1r])
    have hsb2 : strandsBefore win s2 (cc + 2) = offset c.row a := by
      rw [sb_two_free win st s2 cc (by omega) ?_ ?_ ?_, hsb]
      · intro p _ hp
        rw [segW_eq, segW_eq]; simp only [yarnAt, frontAt, backAt, e2c, e2s, e2r, hcar, hr, kX, Int.sub_zero]
        simp [show p ≠ cc + 2 by omega, show cc ≠ p by omega, show ¬ cc + 2 = p by omega, hb]
      · rw [segW_eq]; simp only [yarnAt, frontAt, backAt, e2c, e2s, e2r, kX, Int.sub_zero]
        simp [hfy, hb]
      · rw [segW_eq]; simp only [yarnAt, frontAt, backAt, e2c, e2s, e2r, kX, Int.sub_zero]
        simp [hf1, hb]
    have d3 : denoteOp1 win s2 (.miss .R (fN (cc + 2))) = plainB (swapBlocks (offset c.row a) 1 (2 * k) true) := by
      have hK : backAt s2 (cc + 2) = 2 * k := by simp [backAt, e2s, e2r, kX, hkk]
      have hF : frontAt s2 (cc + 2) = 0 := by simp [frontAt, e2s, kX]
      simp only [denoteOp1, slot, fN, arrivesFrom, hsb2, hK, hF, swapB_nil (Or.inr rfl),
        List.nil_append, Nat.add_zero]
      rfl
    have hden : denote1 win st [.xfer (fN (cc + 2)) (bN (cc + 2)), .miss .R (fN cc), .miss .R (fN (cc + 1)),
        .miss .R (fN (cc + 2)), .xfer (bN (cc + 2)) (fN (cc + 2))] =
        some (s4, plainB (swapBlocks (offset c.row a) 1 (2 * k) true)) := by
      rw [denote1_cons_v _ vX wX, denote1_cons_v _ v1 w1, denote1_cons_v _ v2 w2, denote1_cons_v _ v3 w3,
        denote1_single_op v4 w4, d1, d2, d3]
      simp only [denoteOp1, List.nil_append, List.append_nil, Option.map_some]
      rfl
    refine ⟨s4, ?_, hlaid s4 _ (by simp [hs4, apply, e3r]) k4 e3c⟩
    rw [List.drop_left]
    have := denote_of_denote1 win st _ _ _ (by
      intro op hop; simp at hop; rcases hop with h | h | h | h | h <;> subst h <;> trivial) hden
    rw [liftB_plainB] at this
    simpa [Obj.width] using this

Fragment: stack–yarn exchange

xSY : XFrag IsSY. A stack of k is at cc. The yarn is at cc + 2. The carrier moves two slots left. The second miss crosses the stack.

front Instructions Drawing
true two misses swapBlocks off (2k) 1 true
false the stack goes to the back needle across, two misses, the stack comes back swapBlocks off (2k) 1 false
namespace FormalizeKnitting.Bridge.RM.Frag
open FormalizeKnitting.Knitout
theorem xSY : XFrag IsSY
Proof
:= by
  intro win c c1 st a front r' M hP hL hc hF hrs hcs hpre hN
  have hy := hL.1
  simp only [IsSY] at hP
  by_cases ha : a + 1 < c.row.length
  swap
  · simp [runStepB, ha] at hrs
  have hya : a + 1 = yarnIdx c.row := (getD_eq_yarn_iff hy ha).mp hP
  obtain ⟨k, hk⟩ : ∃ k, c.row.getD a .yarn = .stack k := by
    cases h : c.row.getD a .yarn with
    | yarn => exact absurd ((getD_eq_yarn_iff hy (by omega)).mp h) (by omega)
    | stack k => exact ⟨k, rfl⟩
  have hym := yarn_mem hy
  simp only [runStepB, hym, ha, and_self, ite_true, Option.some.injEq, Prod.mk.injEq, hP, hk] at hrs
  obtain ⟨rfl, rfl⟩ := hrs
  set cc : Int := 3 + 2 * (a : Int) with hccdef
  have hp : c.at_.getD a 0 = cc := by rw [hc]; exact canonical_getD_two (by omega)
  have hq : c.at_.getD (a + 1) 0 = cc + 2 := by rw [hc, canonical_getD_two ha]; push_cast; omega
  have hlen : a + 1 < c.at_.length := by rw [hc, canonical_length]; exact ha
  simp only [compileStep, hym, ha, and_self, ite_true, hP, hk, hp, hq, Option.map_some,
    Option.some.injEq, emit, Exch.yarnTo_L2] at hcs
  subst hcs
  have hat : swapAt (c.at_.set (a + 1) cc) a 0 = spliceL c.at_ a 2 [cc, cc] := by
    unfold swapAt
    rw [Exch.spliceL_set _ _ _ _ _ _ (by omega) (by omega), Exch.getD_set_eq _ _ _ _ (by omega),
      Exch.getD_set_ne _ _ _ _ _ (by omega), hp]
  simp only [hat] at hpre hN ⊢
  have hn3 := hN (.miss .L (fN cc)) (by cases front <;> simp) cc (by simp [Op.named, fN])
  have hlo := fits_lo hF hc (by omega)
  have hcar : st.carrier = cc + 2 := by
    rw [laid_carrier hL hc, ← hya]; push_cast; omega
  have hf1 : st.stk ⟨.f, cc + 1⟩ = [] := laid_front_off hL hc _ (fun j => by omega)
  have hkk : (st.stk ⟨.f, cc⟩).length = k := by rw [laid_front_at hL hc, hk]; rfl
  have hsb : strandsBefore win st cc = offset c.row a := strandsBefore_canon hL hc win (by omega) a (by omega)
  have hr := hL.2.2.1
  have hb := hL.2.2.2.1
  have ins : ∀ z, win.lo + 1 ≤ z → z + 2 ≤ win.lo + win.w → win.inside z = true := fun z h1 h2 => inside_of h1 h2
  have hfit := fits_canon hF hc ha
  have hfits : Fits win ⟨splice c.row a 2 [.yarn, .stack k], spliceL c.at_ a 2 [cc, cc], []⟩ := by
    rw [hc]; apply fits_splice hF _ _ _ _ _ hc
    intro x hx; simp at hx; omega
  have hlaid : ∀ (sF : State) (ops : List Op), sF.rack = 0 → (∀ q, sF.stk q = st.stk q) → sF.carrier = cc →
      Laid ⟨splice c.row a 2 [.yarn, .stack k], spliceL c.at_ a 2 [cc, cc], ops⟩ sF := by
    intro sF ops rF kF cF
    rw [splice_eq, hc]
    have hseg2 : ((c.row.drop a).take 2).count .yarn = 1 := by rw [seg1_two _ ha .yarn, hP, hk]; simp
    have hy' : (spliceL c.row a 2 [.yarn, .stack k]).count .yarn = 1 := by
      rw [count_splice, hseg2]; simp [hy]
    have hl' : a < (spliceL c.row a 2 [.yarn, .stack k]).length := by
      rw [length_spliceL _ _ _ _ (by omega)]; simp; omega
    have hyi : yarnIdx (spliceL c.row a 2 [.yarn, .stack k]) = a := by
      apply yarnIdx_of hy' hl'
      rw [getD_spliceL _ _ _ _ _ (by omega)]; simp
    apply laid_splice hL hc a 2 [.yarn, .stack k] [cc, cc] _ ha rfl hy' rF
    · intro j; rw [kF]; exact hb j
    · intro i
      rw [kF, loadAt_seg_two _ ha, hP, hk]
      simp [loadAt, stackSize]
      split_ifs <;> omega
    · rw [hyi, getD_spliceL _ _ _ _ _ (by rw [canonical_length]; omega)]
      rw [cF]; simp
    · intro t ht
      have : t = 0 := by simp at ht; omega
      subst this; simp [scpos]
    · intro h0 _; refine lt_of_le_of_lt (scpos_hi _ _) ?_; simp [scpos]; push_cast [show 1 ≤ a by omega]; omega
    · intro _ _; refine lt_of_lt_of_le ?_ (scpos_lo _ _); simp [scpos]; omega
  refine ⟨hfits, ?_⟩
  cases front with
  | true =>
    simp only [Bool.not_true, ite_false, Bool.false_eq_true, List.nil_append,
      List.append_nil] at hpre hN ⊢
    set s1 := apply st (.miss .L (fN (cc + 1))) with hs1
    set s2 := apply s1 (.miss .L (fN cc)) with hs2
    have e1c : s1.carrier = cc + 1 := by simp [hs1, apply, slot, fN, leavesTo, hr]
    have e2c : s2.carrier = cc := by simp [hs2, apply, slot, fN, leavesTo]
    have e1s : s1.stk = st.stk := rfl
    have e1r : s1.rack = 0 := hr
    have v1 : validCrate st (.miss .L (fN (cc + 1))) := by
      have ha1 : st.carrier = arrivesFrom .L (cc + 1) := by rw [hcar]; simp only [arrivesFrom]; omega
      simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, fN, slot, ha1, hr]
    have v2 : validCrate s1 (.miss .L (fN cc)) := by
      simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, fN, slot, arrivesFrom, e1c, e1r]
    have w1 : windowOk win st (.miss .L (fN (cc + 1))) = true := by
      simp only [windowOk, slot, fN]; exact ins _ (by omega) (by omega)
    have w2 : windowOk win s1 (.miss .L (fN cc)) = true := by
      simp only [windowOk, slot, fN]; exact ins _ (by omega) (by omega)
    have d1 : denoteOp1 win st (.miss .L (fN (cc + 1))) = [] :=
      miss_free _ _ _ _ (by simp [frontAt, slot, fN, hf1]) (by simp [backAt, slot, fN, hb])
    have hsb1 : strandsBefore win s1 (cc + 1) = offset c.row a + 2 * k := by
      rw [sb_succ win s1 (by omega), segW_eq]
      have hB : strandsBefore win s1 cc = strandsBefore win st cc := by
        apply sb_congr' win (by omega)
        intro p _ hp
        rw [segW_eq, segW_eq]; simp only [yarnAt, frontAt, backAt, e1c, e1s, e1r, hcar, hr]
        rw [ite_eq_right (by omega), ite_eq_right (by omega)]
      rw [hB, hsb]
      simp [yarnAt, frontAt, backAt, e1c, e1s, e1r, hkk, hb]
    have d2 : denoteOp1 win s1 (.miss .L (fN cc)) = plainB (swapBlocks (offset c.row a) (2 * k) 1 true) := by
      have hK : backAt s1 cc = 0 := by simp [backAt, e1s, e1r, hb]
      have hF : frontAt s1 cc = 2 * k := by simp [frontAt, e1s, hkk]
      simp only [denoteOp1, slot, fN, arrivesFrom, hsb1, hK, hF, swapB_nil (Or.inl rfl),
        List.nil_append, Nat.sub_zero, Nat.add_sub_cancel]
      rfl
    have hden : denote1 win st [.miss .L (fN (cc + 1)), .miss .L (fN cc)] =
        some (s2, plainB (swapBlocks (offset c.row a) (2 * k) 1 true)) := by
      rw [denote1_cons_v _ v1 w1, denote1_single_op v2 w2, d1, d2]; rfl
    refine ⟨s2, ?_, hlaid s2 _ hr (fun q => rfl) e2c⟩
    rw [List.drop_left]
    have := denote_of_denote1 win st _ _ _ (by
      intro op hop; simp at hop; rcases hop with h | h <;> subst h <;> trivial) hden
    rw [liftB_plainB] at this
    simpa [Obj.width] using this
  | false =>
    simp only [Bool.not_false, ite_true, List.cons_append, List.nil_append,
      ] at hpre hN ⊢
    set sX := apply st (.xfer (fN cc) (bN cc)) with hsX
    have kX : ∀ q, sX.stk q = if q = ⟨.b, cc⟩ then (st.stk ⟨.f, cc⟩).reverse
        else if q = ⟨.f, cc⟩ then [] else st.stk q := by
      intro q; simp only [hsX, apply, upd_apply, xferStack, hb, List.append_nil, fN, bN]
    set s1 := apply sX (.miss .L (fN (cc + 1))) with hs1
    set s2 := apply s1 (.miss .L (fN cc)) with hs2
    set s3 := apply s2 (.xfer (bN cc) (fN cc)) with hs3
    have eXr : sX.rack = 0 := hr
    have eXc : sX.carrier = cc + 2 := hcar
    have e1c : s1.carrier = cc + 1 := by simp [hs1, apply, slot, fN, leavesTo, eXr]
    have e2c : s2.carrier = cc := by simp [hs2, apply, slot, fN, leavesTo]
    have e1s : s1.stk = sX.stk := rfl
    have e2s : s2.stk = sX.stk := rfl
    have e1r : s1.rack = 0 := hr
    have e2r : s2.rack = 0 := hr
    have k3 : ∀ q, s3.stk q = st.stk q := by
      intro q; simp only [hs3, apply, upd_apply, xferStack, e2s, kX, fN, bN]
      by_cases h : q = ⟨.f, cc⟩
      · subst h; simp
      · by_cases h' : q = ⟨.b, cc⟩
        · subst h'; simp [hb]
        · simp [h, h']
    have vX : validCrate st (.xfer (fN cc) (bN cc)) := by
      simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, slot, aligned, hr, fN, bN]
    have wX : windowOk win st (.xfer (fN cc) (bN cc)) = true := by
      simp only [windowOk, slot, hr, fN, bN, Int.add_zero, Bool.and_self]; exact ins _ (by omega) (by omega)
    have v1 : validCrate sX (.miss .L (fN (cc + 1))) := by
      have ha1 : sX.carrier = arrivesFrom .L (cc + 1) := by rw [eXc]; simp only [arrivesFrom]; omega
      simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, fN, slot, ha1, eXr]
    have v2 : validCrate s1 (.miss .L (fN cc)) := by
      simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, fN, slot, arrivesFrom, e1c, e1r]
    have v3 : validCrate s2 (.xfer (bN cc) (fN cc)) := by
      simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, slot, aligned, e2r, fN, bN]
    have w1 : windowOk win sX (.miss .L (fN (cc + 1))) = true := by
      simp only [windowOk, slot, fN]; exact ins _ (by omega) (by omega)
    have w2 : windowOk win s1 (.miss .L (fN cc)) = true := by
      simp only [windowOk, slot, fN]; exact ins _ (by omega) (by omega)
    have w3 : windowOk win s2 (.xfer (bN cc) (fN cc)) = true := by
      simp only [windowOk, slot, e2r, fN, bN, Int.add_zero, Bool.and_self]; exact ins _ (by omega) (by omega)
    have d1 : denoteOp1 win sX (.miss .L (fN (cc + 1))) = [] :=
      miss_free _ _ _ _ (by simp [frontAt, slot, fN, kX, hf1]) (by simp [backAt, slot, fN, kX, hb, eXr])
    have hsb1 : strandsBefore win s1 (cc + 1) = offset c.row a + 2 * k := by
      rw [sb_succ win s1 (by omega), segW_eq]
      have hB : strandsBefore win s1 cc = strandsBefore win st cc := by
        apply sb_congr' win (by omega)
        intro p _ hp
        rw [segW_eq, segW_eq]; simp only [yarnAt, frontAt, backAt, e1c, e1s, e1r, hcar, hr, kX, Int.sub_zero]
        simp [show p ≠ cc by omega, show ¬ cc + 1 = p by omega, show ¬ cc + 2 = p by omega, hb]
      rw [hB, hsb]
      simp [yarnAt, frontAt, backAt, e1c, e1s, e1r, kX, hkk]
    have d2 : denoteOp1 win s1 (.miss .L (fN cc)) = plainB (swapBlocks (offset c.row a) (2 * k) 1 false) := by
      have hK : backAt s1 cc = 2 * k := by simp [backAt, e1s, e1r, kX, hkk]
      have hF : frontAt s1 cc = 0 := by simp [frontAt, e1s, kX]
      simp only [denoteOp1, slot, fN, arrivesFrom, hsb1, hK, hF, swapB_nil (Or.inl rfl),
        List.append_nil, Nat.sub_zero, Nat.add_sub_cancel]
      rfl
    have hden : denote1 win st [.xfer (fN cc) (bN cc), .miss .L (fN (cc + 1)), .miss .L (fN cc),
        .xfer (bN cc) (fN cc)] = some (s3, plainB (swapBlocks (offset c.row a) (2 * k) 1 false)) := by
      rw [denote1_cons_v _ vX wX, denote1_cons_v _ v1 w1, denote1_cons_v _ v2 w2, denote1_single_op v3 w3, d1, d2]
      simp only [denoteOp1, List.nil_append, List.append_nil, Option.map_some]
      rfl
    refine ⟨s3, ?_, hlaid s3 _ (by simp [hs3, apply, e2r]) k3 (by simp [hs3, apply, e2c])⟩
    rw [List.drop_left]
    have := denote_of_denote1 win st _ _ _ (by
      intro op hop; simp at hop; rcases hop with h | h | h | h <;> subst h <;> trivial) hden
    rw [liftB_plainB] at this
    simpa [Obj.width] using this

Fragment: stack–stack exchange, front = false

xSS_false: the left stack goes under. Stack k is object a, at p = 3 + 2a. Stack l is object a + 1, at p + 2.

Instructions Effect Drawing
loopStep p true stack k moves to front needle p + 1 (a free move) nothing
rack -1, xfer f (p + 1) → b (p + 2) stack k goes to the back bed nothing
rack 0 the back stack of k passes the 2l strands of stack l swapBlocks (offset a) (2k) (2l) false
rack 1 the back stack passes the empty position p + 3 nothing
xfer b (p + 2) → f (p + 3), rack 0 stack k goes to front needle p + 3 nothing
  • rackBraid_single gives the drawing of the one rack that draws.
namespace FormalizeKnitting.Bridge.RM
open FormalizeKnitting.Knitout FormalizeKnitting.Knitout.Exch FormalizeKnitting.Bridge.RM.Frag
theorem moveObject_right1 (c : Comp) (j : Nat) {k : Nat} (h : c.row.getD j .yarn = .stack k) {fr : Int}
    (hfr : c.at_.getD j 0 = fr) :
    moveObject c j (fr + 1) = { c with at_
Proof
:= c.at_.set j (fr + 1), ops := c.ops ++ loopStep fr true } := by
  simp only [moveObject, hfr, h, reduceCtorEq, ite_false, show fr < fr + 1 by omega, ite_true,
    show (fr + 1 - fr).toNat = 1 by omega]
  simp
theorem moveObject_left1 (c : Comp) (j : Nat) {k : Nat} (h : c.row.getD j .yarn = .stack k) {fr : Int}
    (hfr : c.at_.getD j 0 = fr) :
    moveObject c j (fr - 1) = { c with at_
Proof
:= c.at_.set j (fr - 1), ops := c.ops ++ loopStep fr false } := by
  simp only [moveObject, hfr, h, reduceCtorEq, ite_false, show ¬ fr < fr - 1 by omega,
    show (fr - (fr - 1)).toNat = 1 by omega]
  simp
theorem denoteOp_xfer (win : Window) (s : State) (n m : Needle) : denoteOp1 win s (.xfer n m) = []
Proof
:= rfl
theorem stack_of_ne {o : Obj} (h : o ≠ .yarn) : ∃ k, o = .stack k
Proof
:= by
  cases o with
  | yarn => exact absurd rfl h
  | stack k => exact ⟨k, rfl⟩
theorem xSS_false (win : Window) (c c1 : Comp) (st : State) (a : Nat) (r' : Row) (M : BWord Label)
    (hP : IsSS (c.row.getD a .yarn) (c.row.getD (a + 1) .yarn))
    (hL : Laid c st) (hc : c.at_ = canonical 2 c.row.length) (hF : Fits win c)
    (hrs : runStepB c.row (.x a false) = some (r', M))
    (hcs : compileStep c (.x a false) = some c1) (hpre : c.ops <+: c1.ops) (hN : ∀ op ∈ c1.ops, NamedIn3 win op) :
    Fits win c1 ∧ ∃ st', denote win st (c1.ops.drop c.ops.length) = some (st', M) ∧ Laid c1 st'
Proof
:= by
  have hy := hL.1
  by_cases ha : a + 1 < c.row.length
  swap
  · simp [runStepB, ha] at hrs
  obtain ⟨k, hk⟩ := stack_of_ne hP.1
  obtain ⟨l, hl⟩ := stack_of_ne hP.2
  have hym := yarn_mem hy
  simp only [runStepB, hym, ha, and_self, ite_true, Option.some.injEq, Prod.mk.injEq, hk, hl] at hrs
  obtain ⟨rfl, rfl⟩ := hrs
  have hyl := yarnIdx_lt hy
  set y := yarnIdx c.row with hydef
  have hgy : c.row.getD y .yarn = .yarn := Frag.getD_yarnIdx _ hy
  have hya : y ≠ a := fun h => by rw [h, hk] at hgy; exact absurd hgy (by simp)
  have hya1 : y ≠ a + 1 := fun h => by rw [h, hl] at hgy; exact absurd hgy (by simp)
  set p : Int := 3 + 2 * (a : Int) with hpdef
  have hp : c.at_.getD a 0 = p := by rw [hc]; exact canonical_getD_two (by omega)
  have hq : c.at_.getD (a + 1) 0 = p + 2 := by rw [hc, canonical_getD_two ha]; push_cast; omega
  have hlen : a + 1 < c.at_.length := by rw [hc, canonical_length]; exact ha
  have hm := moveObject_right1 c a hk hp
  simp only [compileStep, hym, ha, and_self, ite_true, hk, hl, hq, Option.map_some, Option.some.injEq, emit,
    Bool.not_false, show p + 2 - 1 = p + 1 by omega, show p + 2 + 1 = p + 3 by omega, hm] at hcs
  subst hcs
  have hat : swapAt ((c.at_.set a (p + 1)).set a (p + 3)) a 0 = spliceL c.at_ a 2 [p + 2, p + 3] := by
    unfold swapAt
    rw [spliceL_set _ _ _ _ _ _ (le_refl a) (by omega), spliceL_set _ _ _ _ _ _ (le_refl a) (by omega),
      getD_set_ne _ _ _ _ _ (by omega), getD_set_ne _ _ _ _ _ (by omega),
      getD_set_eq _ _ _ _ (by rw [List.length_set]; omega), hq]
  simp only [hat, List.append_assoc] at hpre hN ⊢
  have hn3 := hN (.xfer (bN (p + 2)) (fN (p + 3))) (by simp) (p + 3) (by simp [Op.named, fN])
  have hlo := fits_lo hF hc (by omega)
  have hfit := fits_canon hF hc (show a < c.row.length by omega)
  have hfit1 := fits_canon hF hc ha
  set cc : Int := 3 + 2 * (y : Int) with hccdef
  have hcar : st.carrier = cc := laid_carrier hL hc
  have hfp1 : st.stk ⟨.f, p + 1⟩ = [] := laid_front_off hL hc _ (fun j => by omega)
  have hfp3 : st.stk ⟨.f, p + 3⟩ = [] := laid_front_off hL hc _ (fun j => by omega)
  have honeA : (st.stk ⟨.f, p⟩).length = k := by rw [laid_front_at hL hc, hk]; rfl
  have honeB : (st.stk ⟨.f, p + 2⟩).length = l := by
    have := laid_front_at hL hc (a + 1)
    rw [show 3 + 2 * ((a + 1 : Nat) : Int) = p + 2 by push_cast; omega, hl] at this
    exact this
  have hb := hL.2.2.2.1
  have hr := hL.2.2.1
  refine ⟨?_, ?_⟩
  · rw [hc]
    apply fits_splice hF _ _ _ _ _ hc
    intro x hx; simp at hx; push_cast at hfit1; omega
  have ins : ∀ z, win.lo + 1 ≤ z → z + 2 ≤ win.lo + win.w → win.inside z = true := fun z h1 h2 => inside_of h1 h2
  obtain ⟨st1, hd1, h1r, h1c, k1⟩ := loopStep_right_free win st p hr hb (by omega) hfp1
    (ins _ (by omega) (by omega)) (ins _ (by omega) (by omega))
  have b1 : ∀ j, st1.stk ⟨.b, j⟩ = [] := by intro j; rw [k1]; simp [hb]
  set t1 := apply st1 (.rack (-1)) with ht1
  set t2 := apply t1 (.xfer (fN (p + 1)) (bN (p + 2))) with ht2
  set t3 := apply t2 (.rack 0) with ht3
  set t4 := apply t3 (.rack 1) with ht4
  set t5 := apply t4 (.xfer (bN (p + 2)) (fN (p + 3))) with ht5
  set t6 := apply t5 (.rack 0) with ht6
  have e1r : t1.rack = -1 := rfl
  have k2 : ∀ q, t2.stk q = if q = ⟨.b, p + 2⟩ then (st.stk ⟨.f, p⟩).reverse else
      if q = ⟨.f, p + 1⟩ ∨ q = ⟨.f, p⟩ then [] else st.stk q := by
    intro q
    show Function.update (Function.update st1.stk (fN (p + 1)) []) (bN (p + 2))
      (xferStack (st1.stk (fN (p + 1))) (st1.stk (bN (p + 2)))) q = _
    simp only [upd_apply, xferStack, k1, fN, bN]
    by_cases h1 : q = ⟨.b, p + 2⟩
    · subst h1; simp [hb]
    · by_cases h2 : q = ⟨.f, p + 1⟩
      · subst h2; simp
      · by_cases h3 : q = ⟨.f, p⟩
        · subst h3; simp
        · simp [h1, h2, h3]
  have e2r : t2.rack = -1 := rfl
  have e2c : t2.carrier = cc := by rw [← hcar, ← h1c]; rfl
  have b2 : ∀ j, j ≠ p + 2 → t2.stk ⟨.b, j⟩ = [] := by intro j h; simp [k2, h, hb]
  have e3r : t3.rack = 0 := rfl
  have e4r : t4.rack = 1 := rfl
  have k5 : ∀ q, t5.stk q = if q = ⟨.f, p + 3⟩ then st.stk ⟨.f, p⟩ else if q = ⟨.b, p + 2⟩ then []
      else t2.stk q := by
    intro q
    show Function.update (Function.update t2.stk (bN (p + 2)) []) (fN (p + 3))
      (xferStack (t2.stk (bN (p + 2))) (t2.stk (fN (p + 3)))) q = _
    simp only [upd_apply, xferStack, fN, bN]
    by_cases h1 : q = ⟨.f, p + 3⟩
    · subst h1; rw [k2, k2]; simp [hfp3]
    · simp [h1]
  have b5 : ∀ j, t5.stk ⟨.b, j⟩ = [] := by
    intro j; rw [k5]; by_cases h : j = p + 2
    · subst h; simp
    · simp [h, k2, hb]
  have e5r : t5.rack = 1 := rfl
  have e6c : t6.carrier = cc := e2c
  have v1 : validCrate st1 (.rack (-1)) := by simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, h1r]
  have v2 : validCrate t1 (.xfer (fN (p + 1)) (bN (p + 2))) := by
    simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, fN, bN, slot, aligned, e1r,
      show p + 2 + -1 = p + 1 by omega]
  have v3 : validCrate t2 (.rack 0) := by simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, e2r]
  have v4 : validCrate t3 (.rack 1) := by simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, e3r]
  have v5 : validCrate t4 (.xfer (bN (p + 2)) (fN (p + 3))) := by
    simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, fN, bN, slot, aligned, e4r,
      show p + 2 + 1 = p + 3 by omega]
  have v6 : validCrate t5 (.rack 0) := by simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, e5r]
  have w1 : windowOk win st1 (.rack (-1)) = true := by
    simp only [windowOk, List.all_eq_true, List.mem_range, Bool.or_eq_true, List.isEmpty_iff]
    intro k _; left; exact b1 _
  have w2 : windowOk win t1 (.xfer (fN (p + 1)) (bN (p + 2))) = true := by
    simp only [windowOk, slot, fN, bN, e1r, Bool.and_eq_true]
    exact ⟨ins _ (by omega) (by omega), ins _ (by omega) (by omega)⟩
  have w3 : windowOk win t2 (.rack 0) = true := by
    simp only [windowOk, List.all_eq_true, List.mem_range, Bool.or_eq_true, List.isEmpty_iff]
    intro k _
    by_cases h : win.lo + (k : Int) = p + 2
    · right; rw [h]; exact ins _ (by omega) (by omega)
    · left; exact b2 _ h
  have w4 : windowOk win t3 (.rack 1) = true := by
    simp only [windowOk, List.all_eq_true, List.mem_range, Bool.or_eq_true, List.isEmpty_iff]
    intro k _
    by_cases h : win.lo + (k : Int) = p + 2
    · right; rw [h]; exact ins _ (by omega) (by omega)
    · left; exact b2 _ h
  have w5 : windowOk win t4 (.xfer (bN (p + 2)) (fN (p + 3))) = true := by
    simp only [windowOk, slot, fN, bN, e4r, Bool.and_eq_true]
    exact ⟨ins _ (by omega) (by omega), ins _ (by omega) (by omega)⟩
  have w6 : windowOk win t5 (.rack 0) = true := by
    simp only [windowOk, List.all_eq_true, List.mem_range, Bool.or_eq_true, List.isEmpty_iff]
    intro k _; left; exact b5 _
  have d1 : denoteOp1 win st1 (.rack (-1)) = [] := by
    apply rackBraid_nil
    intro k _
    rw [ite_eq_left (by rw [h1r]; omega)]
    right; simp [backAt, b1]
  have d4 : denoteOp1 win t3 (.rack 1) = [] := by
    apply rackBraid_nil
    intro k _
    rw [ite_eq_right (by rw [e3r]; omega)]
    by_cases h : win.lo + (k : Int) - 1 - t3.rack = p + 2
    · right
      have e : win.lo + (k : Int) = p + 3 := by rw [e3r] at h; omega
      rw [e]; simp only [yarnAt, frontAt, show t3.stk = t2.stk from rfl, show t3.carrier = cc from e2c, k2]
      simp [hfp3]; omega
    · left; rw [show t3.stk = t2.stk from rfl, b2 _ h]; rfl
  have d6 : denoteOp1 win t5 (.rack 0) = [] := by
    apply rackBraid_nil
    intro k _
    rw [ite_eq_left (by rw [e5r]; omega)]
    right; simp [backAt, b5]
  have hsb : strandsBefore win t2 (p + 2) = offset c.row a + 2 * k := by
    have hA := sb_add win t2 (i := p) (by omega) 2
    rw [show p + ((2 : Nat) : Int) = p + 2 by push_cast; omega] at hA
    have hB : strandsBefore win t2 p = strandsBefore win st p := by
      apply sb_congr' win (by omega)
      intro x _ hx
      rw [segW_eq, segW_eq]
      simp only [yarnAt, frontAt, backAt, e2c, e2r, hcar, hr, k2, Int.sub_zero]
      simp [show x ≠ p by omega, show x ≠ p + 1 by omega, show x + 1 ≠ p + 2 by omega, hb]
    have h0 : segW t2 p = 0 := by
      rw [segW_eq]; simp only [yarnAt, frontAt, backAt, e2c, e2r, k2]
      simp [show cc ≠ p by omega, hb]
    have h1' : segW t2 (p + 1) = 2 * k := by
      rw [segW_eq]; simp only [yarnAt, frontAt, backAt, e2c, e2r, k2]
      simp [show cc ≠ p + 1 by omega, show p + 1 - -1 = p + 2 by omega, honeA]
    have hc0 : strandsBefore win st p = offset c.row a := strandsBefore_canon hL hc win (by omega) a (by omega)
    rw [hA, hB, hc0]
    simp [Finset.sum_range_succ, h0, h1']
  have d3 : denoteOp1 win t2 (.rack 0) = swapB (offset c.row a) (2 * k) (2 * l) false := by
    have hk0 : (p + 2 - win.lo).toNat < win.w := by omega
    have hk0e : win.lo + (((p + 2 - win.lo).toNat : Nat) : Int) = p + 2 := by omega
    show rackBraid win t2 0 = _
    rw [rackBraid_single win t2 0 _ hk0]
    · rw [ite_eq_right (by rw [e2r]; omega), hk0e, hsb]
      have hbe : (t2.stk ⟨.b, p + 2 - 1 - t2.rack⟩).length = k := by
        rw [e2r, show p + 2 - 1 - -1 = p + 2 by omega, k2]; simp [honeA]
      have hy0 : yarnAt t2 (p + 2) = 0 := by simp only [yarnAt, e2c]; rw [ite_eq_right (by omega)]
      have hf2 : frontAt t2 (p + 2) = 2 * l := by simp [frontAt, k2, honeB]
      rw [hbe, hy0, hf2]; simp
    · intro k _ hne
      rw [ite_eq_right (by rw [e2r]; omega)]
      left
      rw [b2 _ (by rw [e2r]; omega)]; rfl
  have hrest : denote1 win st1 [.rack (-1), .xfer (fN (p + 1)) (bN (p + 2)), .rack 0, .rack 1,
      .xfer (bN (p + 2)) (fN (p + 3)), .rack 0] = some (t6, swapB (offset c.row a) (2 * k) (2 * l) false) := by
    rw [denote1_cons_v _ v1 w1, denote1_cons_v _ v2 w2, denote1_cons_v _ v3 w3, denote1_cons_v _ v4 w4,
      denote1_cons_v _ v5 w5, denote1_cons_v _ v6 w6, d1, d3, d4, d6]
    simp [denote1, denoteOp_xfer]; rfl
  refine ⟨t6, ?_, ?_⟩
  · rw [List.drop_left]
    have hall := denote1_append win st _ _ st1 t6 [] _ hd1 hrest
    have := denote_of_denote1 win st _ _ _ (by
      intro op hop
      rcases List.mem_append.mp hop with h | h
      · exact loopStep_notSplit p true op h
      · simp at h; rcases h with h | h | h | h | h | h <;> subst h <;> trivial) hall
    rw [List.nil_append, swapB, liftB_plainB] at this
    simpa [Obj.width] using this
  · rw [splice_eq, hc]
    have hy' : (spliceL c.row a 2 [.stack l, .stack k]).count .yarn = 1 := by
      rw [count_splice, seg1_two _ ha .yarn, hk, hl]; simp [hy]
    have hyi : yarnIdx (spliceL c.row a 2 [.stack l, .stack k]) = y := by
      apply yarnIdx_of hy' (by rw [length_spliceL _ _ _ _ (by omega)]; simp; omega)
      rw [getD_spliceL _ _ _ _ _ (by omega)]
      by_cases h : y < a
      · rw [ite_eq_left h]; exact hgy
      · rw [ite_eq_right h, ite_eq_right (by simp; omega), show y - [Obj.stack l, Obj.stack k].length + 2 = y by simp; omega]
        exact hgy
    have k6 : ∀ i, (t6.stk ⟨.f, i⟩).length =
        if i = p + 3 then k else if i = p then 0 else (st.stk ⟨.f, i⟩).length := by
      intro i
      rw [show t6.stk = t5.stk from rfl, k5]
      by_cases h3 : i = p + 3
      · subst h3; simp [honeA]
      · rw [ite_eq_right (by simp [h3]), ite_eq_right (by simp), k2, ite_eq_right (by simp), ite_eq_right h3]
        by_cases h0 : i = p
        · subst h0; simp
        · by_cases h1 : i = p + 1
          · subst h1; simp [hfp1]
          · rw [ite_eq_right (by simp; omega), ite_eq_right h0]
    apply laid_splice hL hc a 2 [.stack l, .stack k] [p + 2, p + 3] _ ha rfl hy'
    · rfl
    · intro j; exact b5 j
    · intro i
      rw [k6 i, loadAt_seg_two _ ha, hk, hl]
      simp only [loadAt, List.zip_cons_cons, List.zip_nil_right, List.map_cons, List.map_nil, List.sum_cons,
        List.sum_nil, stackSize, show 3 + 2 * ((a + 1 : Nat) : Int) = p + 2 by push_cast; omega]
      rw [← hpdef]
      by_cases h3 : i = p + 3
      · subst h3; simp [hfp3]
      · by_cases h0 : i = p
        · subst h0; simp [honeA]
        · by_cases h2 : i = p + 2
          · subst h2; simp [honeB]
          · simp [h3, h0, Ne.symm h0, Ne.symm h2, Ne.symm h3]
    · rw [hyi, getD_spliceL _ _ _ _ _ (by rw [canonical_length]; omega)]
      show t6.carrier = _
      rw [e6c]
      by_cases h : y < a
      · rw [ite_eq_left h, canonical_getD_two hyl]
      · rw [ite_eq_right h, ite_eq_right (by simp; omega), show y - [p + 2, p + 3].length + 2 = y by simp; omega,
          canonical_getD_two hyl]
    · intro t ht
      obtain rfl : t = 0 := by simp at ht; omega
      simp [scpos]
    · intro h0 _; refine lt_of_le_of_lt (scpos_hi _ _) ?_; simp [scpos]; push_cast [show 1 ≤ a by omega]; omega
    · intro _ _; refine lt_of_lt_of_le ?_ (scpos_lo _ _); simp [scpos]; omega

Fragment: stack–stack exchange, front = true

xSS_true: the left stack goes over. It is the mirror of xSS_false. Then xSS : XFrag IsSS for both senses.

Instructions Effect Drawing
loopStep (p + 2) false stack l moves to front needle p + 1 (a free move) nothing
rack 1, xfer f (p + 1) → b p stack l goes to the back bed nothing
rack 0 the back stack of l passes no strands nothing
rack -1 the back stack of l passes the 2k strands of stack k swapBlocks (offset a) (2k) (2l) true
xfer b p → f (p - 1), rack 0 stack l goes to front needle p - 1 nothing
  • rackBraid_single gives the drawing of the one rack that draws.
namespace FormalizeKnitting.Bridge.RM
open FormalizeKnitting.Knitout FormalizeKnitting.Knitout.Exch FormalizeKnitting.Bridge.RM.Frag
theorem xSS_true (win : Window) (c c1 : Comp) (st : State) (a : Nat) (r' : Row) (M : BWord Label)
    (hP : IsSS (c.row.getD a .yarn) (c.row.getD (a + 1) .yarn))
    (hL : Laid c st) (hc : c.at_ = canonical 2 c.row.length) (hF : Fits win c)
    (hrs : runStepB c.row (.x a true) = some (r', M))
    (hcs : compileStep c (.x a true) = some c1) (hpre : c.ops <+: c1.ops) (hN : ∀ op ∈ c1.ops, NamedIn3 win op) :
    Fits win c1 ∧ ∃ st', denote win st (c1.ops.drop c.ops.length) = some (st', M) ∧ Laid c1 st'
Proof
:= by
  have hy := hL.1
  by_cases ha : a + 1 < c.row.length
  swap
  · simp [runStepB, ha] at hrs
  obtain ⟨k, hk⟩ := stack_of_ne hP.1
  obtain ⟨l, hl⟩ := stack_of_ne hP.2
  have hym := yarn_mem hy
  simp only [runStepB, hym, ha, and_self, ite_true, Option.some.injEq, Prod.mk.injEq, hk, hl] at hrs
  obtain ⟨rfl, rfl⟩ := hrs
  have hyl := yarnIdx_lt hy
  set y := yarnIdx c.row with hydef
  have hgy : c.row.getD y .yarn = .yarn := Frag.getD_yarnIdx _ hy
  have hya : y ≠ a := fun h => by rw [h, hk] at hgy; exact absurd hgy (by simp)
  have hya1 : y ≠ a + 1 := fun h => by rw [h, hl] at hgy; exact absurd hgy (by simp)
  set p : Int := 3 + 2 * (a : Int) with hpdef
  have hp : c.at_.getD a 0 = p := by rw [hc]; exact canonical_getD_two (by omega)
  have hq : c.at_.getD (a + 1) 0 = p + 2 := by rw [hc, canonical_getD_two ha]; push_cast; omega
  have hlen : a + 1 < c.at_.length := by rw [hc, canonical_length]; exact ha
  have hm := moveObject_left1 c (a + 1) hl hq
  rw [show p + 2 - 1 = p + 1 by omega] at hm
  simp only [compileStep, hym, ha, and_self, ite_true, hk, hl, hp, hq, Option.map_some, Option.some.injEq, emit,
    Bool.not_true, ite_false, Bool.false_eq_true, hm] at hcs
  subst hcs
  have hat : swapAt ((c.at_.set (a + 1) (p + 1)).set (a + 1) (p - 1)) a 0 = spliceL c.at_ a 2 [p - 1, p] := by
    unfold swapAt
    rw [spliceL_set _ _ _ _ _ _ (by omega) (by omega), spliceL_set _ _ _ _ _ _ (by omega) (by omega),
      getD_set_eq _ _ _ _ (by rw [List.length_set]; omega), getD_set_ne _ _ _ _ _ (by omega),
      getD_set_ne _ _ _ _ _ (by omega), hp]
  simp only [hat, List.append_assoc] at hpre hN ⊢
  have hn3 := hN (.xfer (bN p) (fN (p - 1))) (by simp) (p - 1) (by simp [Op.named, fN])
  have hlo := fits_lo hF hc (by omega)
  have hfit := fits_canon hF hc (show a < c.row.length by omega)
  have hfit1 := fits_canon hF hc ha
  set cc : Int := 3 + 2 * (y : Int) with hccdef
  have hcar : st.carrier = cc := laid_carrier hL hc
  have hfp1 : st.stk ⟨.f, p + 1⟩ = [] := laid_front_off hL hc _ (fun j => by omega)
  have hfm1 : st.stk ⟨.f, p - 1⟩ = [] := laid_front_off hL hc _ (fun j => by omega)
  have honeA : (st.stk ⟨.f, p⟩).length = k := by rw [laid_front_at hL hc, hk]; rfl
  have honeB : (st.stk ⟨.f, p + 2⟩).length = l := by
    have := laid_front_at hL hc (a + 1)
    rw [show 3 + 2 * ((a + 1 : Nat) : Int) = p + 2 by push_cast; omega, hl] at this
    exact this
  have hb := hL.2.2.2.1
  have hr := hL.2.2.1
  refine ⟨?_, ?_⟩
  · rw [hc]
    apply fits_splice hF _ _ _ _ _ hc
    intro x hx; simp at hx; omega
  have ins : ∀ z, win.lo + 1 ≤ z → z + 2 ≤ win.lo + win.w → win.inside z = true := fun z h1 h2 => inside_of h1 h2
  obtain ⟨st1, hd1, h1r, h1c, k1⟩ := loopStep_left_free win st (p + 2) hr hb (by omega)
    (by rw [show p + 2 - 1 = p + 1 by omega]; exact hfp1) (ins _ (by omega) (by omega)) (ins _ (by omega) (by omega))
  simp only [show p + 2 - 1 = p + 1 by omega] at k1
  have b1 : ∀ j, st1.stk ⟨.b, j⟩ = [] := by intro j; rw [k1]; simp [hb]
  set t1 := apply st1 (.rack 1) with ht1
  set t2 := apply t1 (.xfer (fN (p + 1)) (bN p)) with ht2
  set t3 := apply t2 (.rack 0) with ht3
  set t4 := apply t3 (.rack (-1)) with ht4
  set t5 := apply t4 (.xfer (bN p) (fN (p - 1))) with ht5
  set t6 := apply t5 (.rack 0) with ht6
  have e1r : t1.rack = 1 := rfl
  have k2 : ∀ q, t2.stk q = if q = ⟨.b, p⟩ then (st.stk ⟨.f, p + 2⟩).reverse else
      if q = ⟨.f, p + 1⟩ ∨ q = ⟨.f, p + 2⟩ then [] else st.stk q := by
    intro q
    show Function.update (Function.update st1.stk (fN (p + 1)) []) (bN p)
      (xferStack (st1.stk (fN (p + 1))) (st1.stk (bN p))) q = _
    simp only [upd_apply, xferStack, k1, fN, bN]
    by_cases h1 : q = ⟨.b, p⟩
    · subst h1; simp [hb]
    · by_cases h2 : q = ⟨.f, p + 1⟩
      · subst h2; simp
      · by_cases h3 : q = ⟨.f, p + 2⟩
        · subst h3; simp
        · simp [h1, h2, h3]
  have e2r : t2.rack = 1 := rfl
  have e2c : t2.carrier = cc := by rw [← hcar, ← h1c]; rfl
  have b2 : ∀ j, j ≠ p → t2.stk ⟨.b, j⟩ = [] := by intro j h; simp [k2, h, hb]
  have e3r : t3.rack = 0 := rfl
  have e4r : t4.rack = -1 := rfl
  have k5 : ∀ q, t5.stk q = if q = ⟨.f, p - 1⟩ then st.stk ⟨.f, p + 2⟩ else if q = ⟨.b, p⟩ then []
      else t2.stk q := by
    intro q
    show Function.update (Function.update t2.stk (bN p) []) (fN (p - 1))
      (xferStack (t2.stk (bN p)) (t2.stk (fN (p - 1)))) q = _
    simp only [upd_apply, xferStack, fN, bN]
    by_cases h1 : q = ⟨.f, p - 1⟩
    · subst h1; rw [k2, k2]; simp [hfm1]
    · simp [h1]
  have b5 : ∀ j, t5.stk ⟨.b, j⟩ = [] := by
    intro j; rw [k5]; by_cases h : j = p
    · subst h; simp
    · simp [h, k2, hb]
  have e5r : t5.rack = -1 := rfl
  have e6c : t6.carrier = cc := e2c
  have v1 : validCrate st1 (.rack 1) := by simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, h1r]
  have v2 : validCrate t1 (.xfer (fN (p + 1)) (bN p)) := by
    simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, fN, bN, slot, aligned, e1r]
  have v3 : validCrate t2 (.rack 0) := by simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, e2r]
  have v4 : validCrate t3 (.rack (-1)) := by simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, e3r]
  have v5 : validCrate t4 (.xfer (bN p) (fN (p - 1))) := by
    simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, fN, bN, slot, aligned, e4r,
      show p + -1 = p - 1 by omega]
  have v6 : validCrate t5 (.rack 0) := by simp [validCrate, crateRefusal1, linRefusal, erase, crateExtra1, e5r]
  have w1 : windowOk win st1 (.rack 1) = true := by
    simp only [windowOk, List.all_eq_true, List.mem_range, Bool.or_eq_true, List.isEmpty_iff]
    intro k _; left; exact b1 _
  have w2 : windowOk win t1 (.xfer (fN (p + 1)) (bN p)) = true := by
    simp only [windowOk, slot, fN, bN, e1r, Bool.and_eq_true]
    exact ⟨ins _ (by omega) (by omega), ins _ (by omega) (by omega)⟩
  have w3 : windowOk win t2 (.rack 0) = true := by
    simp only [windowOk, List.all_eq_true, List.mem_range, Bool.or_eq_true, List.isEmpty_iff]
    intro k _
    by_cases h : win.lo + (k : Int) = p
    · right; rw [h]; exact ins _ (by omega) (by omega)
    · left; exact b2 _ h
  have w4 : windowOk win t3 (.rack (-1)) = true := by
    simp only [windowOk, List.all_eq_true, List.mem_range, Bool.or_eq_true, List.isEmpty_iff]
    intro k _
    by_cases h : win.lo + (k : Int) = p
    · right; rw [h]; exact ins _ (by omega) (by omega)
    · left; exact b2 _ h
  have w5 : windowOk win t4 (.xfer (bN p) (fN (p - 1))) = true := by
    simp only [windowOk, slot, fN, bN, e4r, Bool.and_eq_true]
    exact ⟨ins _ (by omega) (by omega), ins _ (by omega) (by omega)⟩
  have w6 : windowOk win t5 (.rack 0) = true := by
    simp only [windowOk, List.all_eq_true, List.mem_range, Bool.or_eq_true, List.isEmpty_iff]
    intro k _; left; exact b5 _
  have d1 : denoteOp1 win st1 (.rack 1) = [] := by
    apply rackBraid_nil
    intro k _
    rw [ite_eq_right (by rw [h1r]; omega)]
    left; rw [b1]; rfl
  have d3 : denoteOp1 win t2 (.rack 0) = [] := by
    apply rackBraid_nil
    intro k _
    rw [ite_eq_left (by rw [e2r]; omega)]
    by_cases h : win.lo + (k : Int) - t2.rack = p
    · left
      have e : win.lo + (k : Int) = p + 1 := by rw [e2r] at h; omega
      rw [e]; simp only [yarnAt, frontAt, e2c, k2]
      simp; omega
    · right; simp only [backAt]; rw [b2 _ h]; rfl
  have d6 : denoteOp1 win t5 (.rack 0) = [] := by
    apply rackBraid_nil
    intro k _
    rw [ite_eq_right (by rw [e5r]; omega)]
    left; rw [b5]; rfl
  have hsb : strandsBefore win t3 p = offset c.row a := by
    have hB : strandsBefore win t3 p = strandsBefore win st p := by
      apply sb_congr' win (by omega)
      intro x _ hx
      rw [segW_eq, segW_eq]
      simp only [yarnAt, frontAt, backAt, show t3.carrier = cc from e2c, e3r, hcar, hr,
        show t3.stk = t2.stk from rfl, k2, Int.sub_zero]
      simp [show x ≠ p by omega, show x ≠ p + 1 by omega, show x ≠ p + 2 by omega, hb]
    have hc0 : strandsBefore win st p = offset c.row a := strandsBefore_canon hL hc win (by omega) a (by omega)
    rw [hB, hc0]
  have d4 : denoteOp1 win t3 (.rack (-1)) = swapB (offset c.row a) (2 * k) (2 * l) true := by
    have hk0 : (p - win.lo).toNat < win.w := by omega
    have hk0e : win.lo + (((p - win.lo).toNat : Nat) : Int) = p := by omega
    show rackBraid win t3 (-1) = _
    rw [rackBraid_single win t3 (-1) _ hk0]
    · rw [ite_eq_left (by rw [e3r]; omega), hk0e, hsb]
      have hy0 : yarnAt t3 p = 0 := by simp only [yarnAt, show t3.carrier = cc from e2c]; rw [ite_eq_right (by omega)]
      have hf2 : frontAt t3 p = 2 * k := by simp [frontAt, show t3.stk = t2.stk from rfl, k2, honeA]
      have hb2 : backAt t3 p = 2 * l := by simp [backAt, e3r, show t3.stk = t2.stk from rfl, k2, honeB]
      rw [hy0, hf2, hb2, Nat.zero_add]
    · intro k _ hne
      rw [ite_eq_left (by rw [e3r]; omega)]
      right
      simp only [backAt, e3r, Int.sub_zero, show t3.stk = t2.stk from rfl]
      rw [b2 _ (by omega)]; rfl
  have hrest : denote1 win st1 [.rack 1, .xfer (fN (p + 1)) (bN p), .rack 0, .rack (-1),
      .xfer (bN p) (fN (p - 1)), .rack 0] = some (t6, swapB (offset c.row a) (2 * k) (2 * l) true) := by
    rw [denote1_cons_v _ v1 w1, denote1_cons_v _ v2 w2, denote1_cons_v _ v3 w3, denote1_cons_v _ v4 w4,
      denote1_cons_v _ v5 w5, denote1_cons_v _ v6 w6, d1, d3, d4, d6]
    simp [denote1, denoteOp_xfer]; rfl
  refine ⟨t6, ?_, ?_⟩
  · rw [List.drop_left]
    have hall := denote1_append win st _ _ st1 t6 [] _ hd1 hrest
    have := denote_of_denote1 win st _ _ _ (by
      intro op hop
      rcases List.mem_append.mp hop with h | h
      · exact loopStep_notSplit (p + 2) false op h
      · simp at h; rcases h with h | h | h | h | h | h <;> subst h <;> trivial) hall
    rw [List.nil_append, swapB, liftB_plainB] at this
    simpa [Obj.width] using this
  · rw [splice_eq, hc]
    have hy' : (spliceL c.row a 2 [.stack l, .stack k]).count .yarn = 1 := by
      rw [count_splice, seg1_two _ ha .yarn, hk, hl]; simp [hy]
    have hyi : yarnIdx (spliceL c.row a 2 [.stack l, .stack k]) = y := by
      apply yarnIdx_of hy' (by rw [length_spliceL _ _ _ _ (by omega)]; simp; omega)
      rw [getD_spliceL _ _ _ _ _ (by omega)]
      by_cases h : y < a
      · rw [ite_eq_left h]; exact hgy
      · rw [ite_eq_right h, ite_eq_right (by simp; omega), show y - [Obj.stack l, Obj.stack k].length + 2 = y by simp; omega]
        exact hgy
    have k6 : ∀ i, (t6.stk ⟨.f, i⟩).length =
        if i = p - 1 then l else if i = p + 2 then 0 else (st.stk ⟨.f, i⟩).length := by
      intro i
      rw [show t6.stk = t5.stk from rfl, k5]
      by_cases h3 : i = p - 1
      · subst h3; simp [honeB]
      · rw [ite_eq_right (by simp [h3]), ite_eq_right (by simp), k2, ite_eq_right (by simp), ite_eq_right h3]
        by_cases h0 : i = p + 2
        · subst h0; simp
        · by_cases h1 : i = p + 1
          · subst h1; simp [hfp1]
          · rw [ite_eq_right (by simp; omega), ite_eq_right h0]
    apply laid_splice hL hc a 2 [.stack l, .stack k] [p - 1, p] _ ha rfl hy'
    · rfl
    · intro j; exact b5 j
    · intro i
      rw [k6 i, loadAt_seg_two _ ha, hk, hl]
      simp only [loadAt, List.zip_cons_cons, List.zip_nil_right, List.map_cons, List.map_nil, List.sum_cons,
        List.sum_nil, stackSize, show 3 + 2 * ((a + 1 : Nat) : Int) = p + 2 by push_cast; omega]
      rw [← hpdef]
      by_cases h3 : i = p - 1
      · subst h3; simp [hfm1]; omega
      · by_cases h0 : i = p + 2
        · subst h0; simp [honeB, show p + 2 ≠ p - 1 by omega, show p - 1 ≠ p + 2 by omega]
        · by_cases h2 : i = p
          · subst h2; simp [honeA]; omega
          · simp [h3, h0, Ne.symm h0, Ne.symm h2, Ne.symm h3]
    · rw [hyi, getD_spliceL _ _ _ _ _ (by rw [canonical_length]; omega)]
      show t6.carrier = _
      rw [e6c]
      by_cases h : y < a
      · rw [ite_eq_left h, canonical_getD_two hyl]
      · rw [ite_eq_right h, ite_eq_right (by simp; omega), show y - [p - 1, p].length + 2 = y by simp; omega,
          canonical_getD_two hyl]
    · intro t ht
      obtain rfl : t = 0 := by simp at ht; omega
      simp [scpos]
    · intro h0 _; refine lt_of_le_of_lt (scpos_hi _ _) ?_; simp [scpos]; push_cast [show 1 ≤ a by omega]; omega
    · intro _ _; refine lt_of_lt_of_le ?_ (scpos_lo _ _); simp [scpos]; omega
theorem xSS : XFrag IsSS
Proof
:= by
  intro win c c1 st a front r' M hP hL hc hF hrs hcs hpre hN
  cases front with
  | false => exact xSS_false win c c1 st a r' M hP hL hc hF hrs hcs hpre hN
  | true => exact xSS_true win c c1 st a r' M hP hL hc hF hrs hcs hpre hN

The compile functor C : 𝒮 ⥤ 𝒦

C sends a row to its canonical count state. It sends a shorthand program to the knitout program that the compiler writes for it.

Part Definition
On objects canonK r: the count state canonL r, with finitely many loops (canon_fin)
On arrows compileOps a w: the program that compileSteps 2 writes for w from the canonical layout of a
Identity compileOps_nil: the empty shorthand program gives the empty program
Composition compileOps_comp: the program of p ++ q is the program of p, then the program of q
  • canonL r: rack 0, back bed empty, object j at front needle 3 + 2j, the carrier at the yarn's position.
  • compileOps gives [] when compileSteps fails. For an arrow it does not fail (compile_shom).
  • compileOps_run: from canonL a, the count machine runs compileOps a w and ends on canonL b.
  • compileOps_spec: the compiled program is Good in a window that holds the canonical layout. The retract proof uses this.
  • compileSteps_shift: the compiler only appends. This gives compileOps_comp.

The canonical state

def canonL (r : ShorthandObj) : LinState :=
  ⟨0, fun n => match n.bed with
    | .f => loadAt r.row (canonical 2 r.row.length) n.idx
    | .b => 0,
   (canonical 2 r.row.length).getD (yarnIdx r.row) 0⟩
theorem laid_canon (r : ShorthandObj) :
    Bridge.RM.Laid ⟨r.row, canonical 2 r.row.length, []⟩ (lift (canonL r))
Proof
:= by
  refine ⟨r.yarn, canonical_length _, rfl, fun j => rfl, fun i => ?_, rfl, fun j hj => ?_⟩
  · simp [lift, canonL]
  · dsimp only at hj ⊢
    rw [canonical_getD_two (by omega), canonical_getD_two hj]
    cases r.row.getD j .yarn <;> cases r.row.getD (j + 1) .yarn <;> simp only [scpos] <;> push_cast <;> omega
namespace CompileC
theorem mem_canonical {n : Nat} {x : Int} (h : x ∈ canonical 2 n) : ∃ j : Nat, j < n ∧ x = 3 + 2 * (j : Int)
Proof
:= by
  rw [Frag.canonical_two_eq] at h
  simp only [Frag.canonFrom, List.mem_map, List.mem_range] at h
  obtain ⟨j, hj, rfl⟩ := h
  exact ⟨j, hj, by simp⟩
theorem loadAt_canon_pos {r : Row} {i : Int} (h : loadAt r (canonical 2 r.length) i ≠ 0) :
    ∃ j : Nat, j < r.length ∧ i = 3 + 2 * (j : Int)
Proof
:= by
  by_cases hi : ∃ j : Nat, i = 3 + 2 * (j : Int)
  · obtain ⟨j, rfl⟩ := hi
    refine ⟨j, ?_, rfl⟩
    by_contra hj
    rw [Frag.loadAt_canon_at, Frag.stackSize_of_ge (by omega)] at h
    exact h rfl
  · simp only [not_exists] at hi
    exact absurd (Frag.loadAt_canon_off r i hi) h
theorem inv_canon (r : ShorthandObj) (win : Window) (hlo : win.lo ≤ 3) (hhi : 3 + 2 * (r.row.length : Int) ≤ win.lo + win.w) :
    MR.Inv win (lift (canonL r))
Proof
:= by
  refine ⟨fun j hj => absurd rfl hj, fun n hn => ?_, ?_⟩
  · obtain ⟨bd, i⟩ := n
    cases bd with
    | b => exact absurd rfl hn
    | f =>
      have h0 : loadAt r.row (canonical 2 r.row.length) i ≠ 0 := by
        intro h0; apply hn; simp [lift, canonL, h0]
      obtain ⟨j, hj, rfl⟩ := loadAt_canon_pos h0
      simp only [slot]
      omega
  · have hy := Frag.yarnIdx_lt r.yarn
    simp only [lift, canonL]
    rw [canonical_getD_two hy]
    omega
theorem erase_laid {c : Comp} {st : State} (b : ShorthandObj) (hL : Laid c st) (hr : c.row = b.row)
    (ha : c.at_ = canonical 2 b.row.length) : erase st = canonL b
Proof
:= by
  obtain ⟨-, -, hrack, hback, hfront, hcar, -⟩ := hL
  rw [hr, ha] at hfront hcar
  simp only [erase, canonL]
  congr 1
  funext n
  obtain ⟨bd, i⟩ := n
  cases bd with
  | f => exact hfront i
  | b => simp [hback i]

Compiling a program: the end coordinates

theorem compileSteps_at : ∀ (w : List Step) (c : Comp) (r' : Row) (M : BWord Label), c.row.count .yarn = 1 →
    c.at_ = canonical 2 c.row.length → DB c.row w = some (r', M) → ∀ c2, compileSteps 2 c w = some c2 →
      c2.at_ = canonical 2 c2.row.length
Proof
  | [], c, r', M, hy, hcan, hDB, c2, h => by
    simp only [compileSteps, Option.some.injEq] at h; subst h; exact hcan
  | s :: ss, c, r', M, hy, hcan, hDB, c2, h => by
    simp only [DB] at hDB
    cases hrs : runStepB c.row s with
    | none => simp [hrs] at hDB
    | some p =>
      obtain ⟨r1, M1⟩ := p
      simp only [hrs] at hDB
      cases hrest : DB r1 ss with
      | none => simp [hrest] at hDB
      | some q =>
        obtain ⟨r2, M2⟩ := q
        obtain ⟨c1, hc1, hr1, hy1, -, hl1⟩ := compileTotal c s r1 M1 hy hcan hrs
        obtain ⟨⟨c1', ha1, hr1', hat1, -⟩, -⟩ := arrangeTotal_two c1 (by rw [hr1]; exact hy1) hl1
        simp only [compileSteps, hc1, ha1] at h
        exact compileSteps_at ss c1' r2 M2 (by rw [hr1', hr1]; exact hy1) (by rw [hat1, hr1'])
          (by rw [hr1', hr1]; exact hrest) c2 h
theorem compileSteps_append (S : Nat) : ∀ (c : Comp) (w1 w2 : List Step),
    compileSteps S c (w1 ++ w2) = (compileSteps S c w1).bind (compileSteps S · w2)
Proof
  | c, [], w2 => rfl
  | c, s :: ss, w2 => by
    simp only [List.cons_append, compileSteps]
    cases compileStep c s with
    | none => rfl
    | some c1 =>
      simp only
      cases arrange c1 (canonical S c1.row.length) with
      | none => rfl
      | some c2 => exact compileSteps_append S c2 ss w2

The compiler only appends

def shift (o : List Op) (c : Comp) : Comp := { c with ops := o ++ c.ops }
@[simp] theorem shift_row (o : List Op) (c : Comp) : (shift o c).row = c.row
Proof
:= rfl
@[simp] theorem shift_at (o : List Op) (c : Comp) : (shift o c).at_ = c.at_ := rfl
@[simp] theorem shift_ops (o : List Op) (c : Comp) : (shift o c).ops = o ++ c.ops := rfl
theorem moveObject_shift (o : List Op) (c : Comp) (j : Nat) (d : Int) :
    moveObject (shift o c) j d = shift o (moveObject c j d)
Proof
:= by
  simp [moveObject, shift]
theorem emit_shift (o : List Op) (c : Comp) (l : List Op) : emit (shift o c) l = shift o (emit c l)
Proof
:= by
  simp [emit, shift]
theorem foldl_shift (o : List Op) (P : Nat → Bool) (t : Nat → Int) :
    ∀ (L : List Nat) (x : Comp),
      L.foldl (fun c' j => if P j then moveObject c' j (t j) else c') (shift o x) =
        shift o (L.foldl (fun c' j => if P j then moveObject c' j (t j) else c') x)
Proof
  | [], _ => rfl
  | j :: L, x => by
    simp only [List.foldl_cons]
    by_cases h : P j
    · simp only [h, ite_true, moveObject_shift, foldl_shift o P t L]
    · simp only [h, Bool.false_eq_true, ite_false, foldl_shift o P t L]
theorem arrange_shift (o : List Op) (c : Comp) (t : List Int) :
    arrange (shift o c) t = (arrange c t).map (shift o)
Proof
:= by
  unfold arrange
  dsimp only [shift_row, shift_at]
  split_ifs with h
  · simp only [Option.map_some, Option.some.injEq]
    have h1 := foldl_shift o (fun j => decide (scpos (c.row.getD j .yarn) (t.getD j 0) >
      scpos (c.row.getD j .yarn) (c.at_.getD j 0))) (fun j => t.getD j 0) (List.range c.row.length).reverse c
    have h2 := foldl_shift o (fun j => decide (scpos (c.row.getD j .yarn) (t.getD j 0) <
      scpos (c.row.getD j .yarn) (c.at_.getD j 0))) (fun j => t.getD j 0) (List.range c.row.length)
    simp only [decide_eq_true_eq] at h1 h2
    rw [h1, h2]
  · simp
theorem compileStep_shift (o : List Op) (c : Comp) (s : Step) :
    compileStep (shift o c) s = (compileStep c s).map (shift o)
Proof
:= by
  cases s with
  | x a front =>
    simp only [compileStep, shift_row, shift_at]
    by_cases h : Obj.yarn ∈ c.row ∧ a + 1 < c.row.length
    · simp only [ite_eq_left h]
      cases h1 : c.row.getD a .yarn <;> cases h2 : c.row.getD (a + 1) .yarn <;> cases front <;>
        simp [h, shift, moveObject, emit]
    · simp [h]
  | tuck d =>
    simp only [compileStep, shift_row, shift_at]
    by_cases h : Obj.yarn ∈ c.row
    · simp only [ite_eq_left h]
      cases d <;> simp [h, shift]
    · simp [h]
  | merge a =>
    simp only [compileStep, shift_row, shift_at]
    by_cases h : Obj.yarn ∈ c.row
    · simp only [ite_eq_left h]
      cases stackAt c.row a <;> cases stackAt c.row (a + 1) <;> simp [h, shift, moveObject, emit]
    · simp [h]
  | knit d bd =>
    simp only [compileStep, shift_row, shift_at]
    by_cases h : Obj.yarn ∈ c.row ∧ hasBeside c.row d
    · simp only [ite_eq_left h]
      cases stackAt c.row (besideIdx c.row d) <;> simp [h, shift, emit]
    · simp [h]
  | split d bd =>
    simp only [compileStep, shift_row, shift_at]
    by_cases h : Obj.yarn ∈ c.row ∧ hasBeside c.row d
    · simp only [ite_eq_left h]
      cases stackAt c.row (besideIdx c.row d) <;> simp [h, shift, emit]
    · simp [h]
  | drop a =>
    simp only [compileStep, shift_row, shift_at]
    by_cases h : Obj.yarn ∈ c.row
    · simp only [ite_eq_left h]
      cases stackAt c.row a <;> simp [h, shift]
    · simp [h]
theorem compileSteps_shift (S : Nat) (o : List Op) : ∀ (c : Comp) (w : List Step),
    compileSteps S (shift o c) w = (compileSteps S c w).map (shift o)
Proof
  | c, [] => rfl
  | c, s :: ss => by
    simp only [compileSteps, compileStep_shift]
    cases compileStep c s with
    | none => rfl
    | some c1 =>
      simp only [Option.map_some, shift_row, arrange_shift]
      cases arrange c1 (canonical S c1.row.length) with
      | none => rfl
      | some c2 => exact compileSteps_shift S o c2 ss

The compiled program of an arrow

theorem db_of_shom {a b : ShorthandObj} (w : ShorthandProgram a b) : ∃ M, DB a.row w.1 = some (b.row, M)
Proof
:= by
  obtain ⟨M, hM⟩ := w.2
  rw [D_eq_DB] at hM
  cases h : DB a.row w.1 with
  | none => rw [h] at hM; simp at hM
  | some p =>
    rw [h] at hM
    simp only [Option.map_some, Option.some.injEq, Prod.mk.injEq] at hM
    exact ⟨p.2, by rw [← hM.1]⟩
theorem compile_shom {a b : ShorthandObj} (w : ShorthandProgram a b) :
    ∃ c2 M, compileSteps 2 ⟨a.row, canonical 2 a.row.length, []⟩ w.1 = some c2 ∧ c2.row = b.row ∧
      c2.at_ = canonical 2 b.row.length ∧
      ∀ win st, Laid ⟨a.row, canonical 2 a.row.length, []⟩ st → Fits win ⟨a.row, canonical 2 a.row.length, []⟩ →
        (∀ op ∈ c2.ops, NamedIn3 win op) → ∃ st', denote win st c2.ops = some (st', M) ∧ Laid c2 st'
Proof
:= by
  obtain ⟨M, hDB⟩ := db_of_shom w
  obtain ⟨c2, hc2, hr2, -, -, -, hcond⟩ := compileSteps_spec arrangeFree arrangeTotal_two stepFragment_two
    compileTotal w.1 ⟨a.row, canonical 2 a.row.length, []⟩ b.row M a.yarn rfl hDB
  have hat := compileSteps_at w.1 _ b.row M a.yarn rfl hDB c2 hc2
  refine ⟨c2, M, hc2, hr2, by rw [hat, hr2], fun win st hL hF hN => ?_⟩
  obtain ⟨-, st', hd, hL'⟩ := hcond win st hL hF hN
  exact ⟨st', by simpa using hd, hL'⟩
open CompileC
theorem canon_fin (r : ShorthandObj) : ∃ win, MR.Inv win (lift (canonL r))
Proof
:=
  ⟨⟨0, 2 * r.row.length + 3⟩, inv_canon r _ (by simp) (by push_cast; omega)⟩
def canonK (r : ShorthandObj) : KnitoutObj := ⟨canonL r, canon_fin r⟩

def compileOps (r : ShorthandObj) (w : List Step) : List Op :=
  match compileSteps 2 ⟨r.row, canonical 2 r.row.length, []⟩ w with
  | some c2 => c2.ops
  | none => []
theorem compileOps_of {r : ShorthandObj} {w : List Step} {c2 : Comp}
    (h : compileSteps 2 ⟨r.row, canonical 2 r.row.length, []⟩ w = some c2) : compileOps r w = c2.ops
Proof
:= by
  simp [compileOps, h]
theorem compileOps_spec {a b : ShorthandObj} (w : ShorthandProgram a b) :
    ∃ c2, Bridge.RM.compileSteps 2 ⟨a.row, canonical 2 a.row.length, []⟩ w.1 = some c2 ∧
      c2.ops = compileOps a w.1 ∧
      ∃ win, Bridge.RM.Fits win ⟨a.row, canonical 2 a.row.length, []⟩ ∧
        (∀ op ∈ c2.ops, NamedIn3 win op) ∧ Good win (lift (canonL a)) c2.ops
Proof
:= by
  obtain ⟨c2, M, hc2, hr2, hat2, hcond⟩ := compile_shom w
  obtain ⟨B, hB, hb⟩ := Widen.exists_bound (c2.ops.flatMap Op.named)
  set win : Window := ⟨-(B + 5), (2 * B + 2 * (a.row.length : Int) + 20).toNat⟩ with hwin
  have hF : Fits win ⟨a.row, canonical 2 a.row.length, []⟩ := by
    intro x hx
    obtain ⟨j, hj, rfl⟩ := mem_canonical hx
    simp only [hwin]; omega
  have hN : ∀ op ∈ c2.ops, NamedIn3 win op := by
    intro op hop j hj
    have := hb j (List.mem_flatMap.mpr ⟨op, hop, hj⟩)
    simp only [hwin]; omega
  obtain ⟨st', hd, -⟩ := hcond win _ (laid_canon a) hF hN
  refine ⟨c2, hc2, (compileOps_of hc2).symm, win, hF, hN, ?_, fun op hop j hj => ?_, st', M, hd⟩
  · exact inv_canon a win (by simp only [hwin]; omega) (by simp only [hwin]; omega)
  · have := hN op hop j hj; omega
theorem compileOps_run {a b : ShorthandObj} (w : ShorthandProgram a b) : runStepsL (canonL a) (compileOps a w.1) = some (canonL b)
Proof
:= by
  obtain ⟨c2, M, hc2, hr2, hat2, hcond⟩ := compile_shom w
  obtain ⟨B, hB, hb⟩ := Widen.exists_bound (c2.ops.flatMap Op.named)
  set win : Window := ⟨-(B + 5), (2 * B + 2 * (a.row.length : Int) + 20).toNat⟩ with hwin
  have hF : Fits win ⟨a.row, canonical 2 a.row.length, []⟩ := by
    intro x hx
    obtain ⟨j, hj, rfl⟩ := mem_canonical hx
    simp only [hwin]; omega
  have hN : ∀ op ∈ c2.ops, NamedIn3 win op := by
    intro op hop j hj
    have := hb j (List.mem_flatMap.mpr ⟨op, hop, hj⟩)
    simp only [hwin]; omega
  obtain ⟨st', hd, hL'⟩ := hcond win _ (laid_canon a) hF hN
  have h := runStepsL_of_runSteps _ _ _ (runSteps_of_denote hd)
  rw [erase_lift, erase_laid b hL' hr2 hat2] at h
  rw [compileOps_of hc2]; exact h
theorem compileOps_nil (r : ShorthandObj) : compileOps r [] = []
Proof
:= rfl
theorem compileOps_comp {a b c : ShorthandObj} (p : ShorthandProgram a b) (q : ShorthandProgram b c) :
    compileOps a (p.1 ++ q.1) = compileOps a p.1 ++ compileOps b q.1
Proof
:= by
  obtain ⟨c1, -, hc1, hr1, hat1, -⟩ := compile_shom p
  obtain ⟨c2, -, hc2, -, -, -⟩ := compile_shom q
  have e : c1 = shift c1.ops ⟨b.row, canonical 2 b.row.length, []⟩ := by
    cases c1; simp only at hr1 hat1; subst hr1 hat1; simp [shift]
  have h : compileSteps 2 ⟨a.row, canonical 2 a.row.length, []⟩ (p.1 ++ q.1) = some (shift c1.ops c2) := by
    rw [compileSteps_append, hc1, Option.bind_some, e, compileSteps_shift, hc2]
    simp [shift]
  rw [compileOps_of h, compileOps_of hc1, compileOps_of hc2]
  rfl
def C : ShorthandObj ⥤ KnitoutObj where
  obj := canonK
  map {a b} w := (⟨compileOps a (show ShorthandProgram a b from w).1, compileOps_run w⟩ : KnitoutProgram (canonK a) (canonK b))
  map_id a := Subtype.ext (compileOps_nil a)
  map_comp p q := Subtype.ext (compileOps_comp p q)
theorem C_obj (r : ShorthandObj) : (C.obj r).t = canonL r
Proof
:= rfl
theorem C_map_val {a b : ShorthandObj} (w : a ⟶ b) :
    (show KnitoutProgram (C.obj a) (C.obj b) from C.map w).1 = compileOps a (show ShorthandProgram a b from w).1
Proof
:= rfl