import Mathlib import OAI.Computability.DeterministicSum.Expressions namespace OAI /-! Indexed kernels and memory-preserving iteration. -/ namespace DeterministicThreeSum.Structured open Command def written (initial : Data) (base : ℕ) (f : ℕ → ℕ) (k a : ℕ) : Option ℕ := if base≤a ∧ a (∀ r, keep r → t.registers r=s.registers r) ∧ t.registers index=k ∧ t.memory=written initial base f k have hyes : ∀ k t, k rfl,hstart,by rwa [written_zero]⟩ obtain ⟨cost,t,he,hc,ht⟩ := bounded_loop Inv hyes hno hb (i:=0) (by omega) hs exact ⟨cost,t,he,by simpa [Nat.add_assoc] using hc,ht⟩ end DeterministicThreeSum.Structured namespace DeterministicThreeSum.Structured.Indexed open Command def Scalar.reads {m : ℕ} (env : Fin m → ℕ) : Scalar m → Finset ℕ | .literal _ => ∅ | .input a => {a.value env} | .binary _ a b => a.reads env ∪ b.reads env | .branch x y a b => if x.value env exact ⟨Iff.rfl,rfl⟩ | input a => have hh:=h (a.value env) (by simp [Scalar.reads]) simp [Scalar.Valid,Scalar.value,hh] | binary op a b iha ihb => obtain ⟨ha,ha'⟩:=iha (fun k hk => h k (by simp only [Scalar.reads,Finset.mem_union];exact Or.inl hk)) obtain ⟨hb,hb'⟩:=ihb (fun k hk => h k (by simp only [Scalar.reads,Finset.mem_union];exact Or.inr hk)) exact ⟨and_congr ha hb,by simp only [Scalar.value,ha',hb']⟩ | branch x y a b iha ihb => by_cases hh : x.value env s.registers a.val) index i) s.memory) (hdis : ∀ i, i s.registers a.val) index i), a

e.value T (Function.update (fun a : Fin m => s.registers a.val) index i) s.memory) N := by let env : ℕ → Fin m → ℕ := fun i => Function.update (fun a : Fin m => s.registers a.val) index i let f : ℕ → ℕ := fun i => e.value T (env i) s.memory let keep : ℕ → Prop := fun r => r< m ∧ r≠index.val have hkeep : keep bound.val := ⟨bound.isLt,fun h => hib (Fin.ext h.symm)⟩ have hnot : ¬keep index.val := by simp [keep] have stepProof : ∀ i u, i h (Fin.ext hh)⟩ have hmod' : u.registers 2=T := (hu 2 ⟨by omega,Ne.symm hi2⟩).trans hmod have heq : ∀ a∈e.reads (env i), u.memory a=s.memory a := by intro a ha rw [hmem] exact written_outside (by have hh:=hdis i hi a ha;omega) obtain ⟨heqValid,heqVal⟩:=e.memory_congr (w:=w) (T:=T) (env i) u.memory s.memory heq obtain ⟨c,v,he,hc,hvm,hvr,hvf⟩:=e.compile_correct (env i) u.memory u le_rfl hm3 hT hadd hmul hparams hmod' rfl (heqValid.mpr (hv i hi)) have hval : v.registers m=f i := hvr.trans heqVal have hidx : v.registers index.val=i := (hvf _ index.isLt).trans hindex have hbas : v.registers base.val=P := (hvf _ base.isLt).trans ((hu _ ⟨base.isLt,fun h => hip (Fin.ext h.symm)⟩).trans hbase) have hfv : f i hib (Fin.ext h)) (kernelBody index base e) s s f keep hkeep hnot hbound hstart rfl stepProof exact ⟨c,t,he,by simpa only [Nat.add_assoc] using hc,fun r hr' hi => hr r ⟨hr',hi⟩,ht,hm⟩ end DeterministicThreeSum.Structured.Indexed end OAI