File size: 28,127 Bytes
92416a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
import OAI.Computability.UniqueGames.Machines.MachineDrainManyLemmas
import OAI.Computability.UniqueGames.Machines.MachineRadixStepLemmas
import OAI.Computability.UniqueGames.PCP.SourceFieldArrayLemmas
import OAI.Computability.UniqueGames.Reduction.EncodingLemmas
import OAI.Computability.UniqueGames.Reduction.MachineFieldTemplate

namespace OAI

section

/-! A fixed canonical-word template followed by actual radix-address execution.
The program is determined by the fixed tokens and tape layout. Numeric field
values enter only the tape invariants and execution theorem, never the labels. -/

namespace UniqueGamesTheorem.Reduction.MachineTemplateAddress

open Turing
open UniqueGamesTheorem.Foundations.Complexity
open UniqueGamesTheorem.Foundations.Hastad

inductive Tape (q width : Nat)
  | field (i : Fin q)
  | radix | output | reversed | forward | copyScratch
  | accA | accB | counter | hornerScratch
  | digit (i : Fin width)
  deriving DecidableEq, Fintype

abbrev State (σ : Type) := (σ × Unit) × Option Bool
abbrev Alphabet {K : Type} (_ : K) := Bool

variable {q width : Nat} {K Λ σ : Type} [DecidableEq K]

def hornerLayout : MachineHorner.Layout width ↪ Tape q width where
  toFun
    | .inl 0 => .radix
    | .inl 1 => .accA
    | .inl 2 => .accB
    | .inl 3 => .output
    | .inl 4 => .counter
    | .inl 5 => .hornerScratch
    | .inr i => .digit i
  inj' := by
    rintro (a | a) (b | b) h
    · fin_cases a <;> fin_cases b <;> simp_all
    · fin_cases a <;> simp_all
    · fin_cases b <;> simp_all
    · exact congrArg Sum.inr (Tape.digit.inj h)

def hornerSlots (slots : Tape q width ↪ K) : MachineHorner.Layout width ↪ K :=
  hornerLayout.trans slots

def chosen (slots : Tape q width ↪ K) : List K := List.ofFn (fun i => slots (.digit i))

omit [DecidableEq K] in
@[simp] theorem mem_chosen (slots : Tape q width ↪ K) (tape : K) :
    tape ∈ chosen slots ↔ ∃ i, slots (.digit i) = tape := by
  simp [chosen, List.mem_ofFn]

abbrev Label (m width : Nat) (cleanup : List K) :=
  MachineFieldTemplate.Label m ⊕ Unit ⊕ (Fin (width + 1) × Bool) ⊕
    MachineHorner.Label width ⊕ MachineDrainMany.Label cleanup

def emitLabel {m : Nat} {cleanup : List K} (l : MachineFieldTemplate.Label m) :
    Label m width cleanup := .inl l
def reverseLabel {m : Nat} {cleanup : List K} : Label m width cleanup := .inr (.inl ())
def parseLabel {m : Nat} {cleanup : List K} (l : Fin (width + 1) × Bool) :
    Label m width cleanup := .inr (.inr (.inl l))
def hornerLabel {m : Nat} {cleanup : List K} (l : MachineHorner.Label width) :
    Label m width cleanup := .inr (.inr (.inr (.inl l)))
def cleanupLabel {m : Nat} {cleanup : List K} (l : MachineDrainMany.Label cleanup) :
    Label m width cleanup := .inr (.inr (.inr (.inr l)))

def parseDestination (slots : Tape q width ↪ K) (i : Nat) : K :=
  if h : i < width then slots (.digit ⟨i, h⟩) else slots .forward

omit [DecidableEq K] in
@[simp] theorem parseDestination_below (slots : Tape q width ↪ K) (i : Nat) (hi : i < width) :
    parseDestination slots i = slots (.digit ⟨i, hi⟩) := by simp [parseDestination, hi]

/-- Fixed finite instruction assembly, with arbitrary placement and continuation. -/
def instruction (tokens : List (MachineFieldTemplate.Token q)) (slots : Tape q width ↪ K)
    (place : Label tokens.length width (chosen slots) → Λ) (exit : Option Λ) :
    Label tokens.length width (chosen slots) → TM2.Stmt (Alphabet (K := K)) Λ (State σ)
  | .inl l => MachineFieldTemplate.instruction tokens (fun j => slots (.field j))
      (slots .copyScratch) (slots .reversed) (fun l => place (emitLabel l))
      (some (place reverseLabel)) l
  | .inr (.inl _) => MachineTransfer.loopAt (slots .reversed) (slots .forward) id false
      (place reverseLabel) (some (place (parseLabel (SourceFieldArray.startLabel width 0))))
  | .inr (.inr (.inl l)) =>
      if h : l.1.val < width then
        if l.2 then
          SourceMachine.fieldLoop (slots .forward) (slots (.digit ⟨l.1.val, h⟩))
            (place (parseLabel (l.1, true)))
            (some (place (parseLabel (SourceFieldArray.startLabel width (l.1.val + 1)))))
        else SourceMachine.fieldStart (slots (.digit ⟨l.1.val, h⟩))
          (place (parseLabel (l.1, true)))
      else SourceFieldArray.finish (slots .forward) (some (place (hornerLabel .start)))
  | .inr (.inr (.inr (.inl l))) => MachineHorner.statement (hornerSlots slots)
      (fun l => place (hornerLabel l))
      (MachineDrainMany.entry (chosen slots) (fun l => place (cleanupLabel l)) exit) l
  | .inr (.inr (.inr (.inr l))) => MachineDrainMany.instruction (chosen slots)
      (fun l => place (cleanupLabel l)) exit l

def program (tokens : List (MachineFieldTemplate.Token q)) (slots : Tape q width ↪ K)
    (exit : Option (Label tokens.length width (chosen slots))) :
    Label tokens.length width (chosen slots) →
      TM2.Stmt (Alphabet (K := K)) (Label tokens.length width (chosen slots)) (State σ) :=
  instruction tokens slots id exit

structure Clean (slots : Tape q width ↪ K) (base : K → List Bool) : Prop where
  reversed : base (slots .reversed) = []
  forward : base (slots .forward) = []
  copyScratch : base (slots .copyScratch) = []
  accA : base (slots .accA) = []
  accB : base (slots .accB) = []
  counter : base (slots .counter) = []
  hornerScratch : base (slots .hornerScratch) = []
  digit : ∀ j, base (slots (.digit j)) = []

def digits (values : List Nat) (i : Nat) : Nat := values[i]?.getD 0

def forwardTapes (slots : Tape q width ↪ K) (base : K → List Bool) (values : List Nat) :
    K → List Bool := Function.update base (slots .forward) (encodeWords values)

def parsedTapes (slots : Tape q width ↪ K) (base : K → List Bool) (values : List Nat) :
    K → List Bool :=
  SourceFieldArray.sequenceTapes (slots .forward) (parseDestination slots)
    (forwardTapes slots base values) 0 values []

def resultTapes (slots : Tape q width ↪ K) (base : K → List Bool) (value : Nat) :
    K → List Bool := Function.update base (slots .output) (encodeWord value ++ base (slots .output))

def afterHorner (slots : Tape q width ↪ K) (base : K → List Bool) (B : Nat) (values : List Nat) :
    K → List Bool :=
  MachineHorner.resultTapes (hornerSlots slots) (parsedTapes slots base values)
    (MachineHorner.value B (digits values) width)

def phaseSteps (tokens : List (MachineFieldTemplate.Token q)) (slots : Tape q width ↪ K)
    (base : K → List Bool) (B : Nat) (values : List Nat) : Nat :=
  MachineFieldTemplate.templateSteps tokens (fun j => base (slots (.field j))) +
    ((encodeWords values).length + 1) + (values.sum + 2 * values.length + 1) +
    MachineHorner.steps B (digits values) width +
    MachineDrainMany.steps (chosen slots) (afterHorner slots base B values)

@[simp] theorem resultTapes_output (slots : Tape q width ↪ K) (base : K → List Bool) (value : Nat) :
    resultTapes slots base value (slots .output) = encodeWord value ++ base (slots .output) := by
  simp [resultTapes]

theorem resultTapes_other (slots : Tape q width ↪ K) (base : K → List Bool) (value : Nat)
    (tape : K) (hne : tape ≠ slots .output) : resultTapes slots base value tape = base tape := by
  simp [resultTapes, hne]

/-- The numeric recurrence used by the checked Horner machine is the direct
canonical-address radix, in the original template-word order. -/
theorem hornerValue_eq_radix (B : Nat) (values : List Nat) :
    MachineHorner.value B (digits values) values.length = CanonicalAddress.radix B values := by
  rw [MachineHorner.value_eq_foldl, CanonicalAddress.radix_eq_foldl]
  congr 1
  apply List.ext_getElem
  · simp
  · intro i hi hj
    simp only [List.getElem_map, List.getElem_range, digits,
      List.getElem?_eq_getElem hj, Option.getD_some]

theorem parsedTapes_other (slots : Tape q width ↪ K) (base : K → List Bool)
    (values : List Nat) (hlen : values.length = width) (tape : K)
    (notForward : tape ≠ slots .forward) (notDigit : ∀ i, tape ≠ slots (.digit i)) :
    parsedTapes slots base values tape = base tape := by
  rw [parsedTapes, SourceFieldArray.sequenceTapes_other]
  · exact Function.update_of_ne notForward _ _
  · exact notForward
  · intro r hr
    simp only [Nat.zero_add, parseDestination_below slots r (by omega)]
    exact notDigit _

theorem parsedTapes_source (slots : Tape q width ↪ K) (base : K → List Bool)
    (values : List Nat) (hlen : values.length = width) :
    parsedTapes slots base values (slots .forward) = [] := by
  apply SourceFieldArray.sequenceTapes_source
  · intro r hr
    simp only [Nat.zero_add, parseDestination_below slots r (by omega)]
    exact slots.injective.ne (by simp)
  · simp [forwardTapes]

theorem parsedTapes_digit (slots : Tape q width ↪ K) (base : K → List Bool)
    (values : List Nat) (hlen : values.length = width) (clean : Clean slots base) (i : Fin width) :
    parsedTapes slots base values (slots (.digit i)) = encodeWord (digits values i.val) := by
  have hi : i.val < values.length := by omega
  have h := SourceFieldArray.sequenceTapes_selected (slots .forward) (parseDestination slots)
    (forwardTapes slots base values) 0 values [] i.val hi
    (by
      intro r hr
      simp only [Nat.zero_add, parseDestination_below slots r (by omega)]
      exact slots.injective.ne (by simp))
    (by
      intro r s hr hs h
      simp only [Nat.zero_add, parseDestination_below slots r (by omega),
        parseDestination_below slots s (by omega)] at h
      exact congrArg Fin.val (Tape.digit.inj (slots.injective h)))
  simpa [parsedTapes, parseDestination, i.isLt, forwardTapes, clean.digit,
    slots.injective.ne (show Tape.digit i ≠ Tape.forward by simp), digits,
    List.getElem?_eq_getElem hi] using h

theorem parsedTapes_clean (slots : Tape q width ↪ K) (base : K → List Bool)
    (values : List Nat) (hlen : values.length = width) (clean : Clean slots base) :
    MachineHorner.Clean (hornerSlots slots) (parsedTapes slots base values) := by
  constructor
  · rw [show hornerSlots slots (.inl 1) = slots .accA from rfl,
      parsedTapes_other slots base values hlen _ (slots.injective.ne (by simp))
        (fun _ => slots.injective.ne (by simp))]
    exact clean.accA
  · rw [show hornerSlots slots (.inl 2) = slots .accB from rfl,
      parsedTapes_other slots base values hlen _ (slots.injective.ne (by simp))
        (fun _ => slots.injective.ne (by simp))]
    exact clean.accB
  · rw [show hornerSlots slots (.inl 4) = slots .counter from rfl,
      parsedTapes_other slots base values hlen _ (slots.injective.ne (by simp))
        (fun _ => slots.injective.ne (by simp))]
    exact clean.counter
  · rw [show hornerSlots slots (.inl 5) = slots .hornerScratch from rfl,
      parsedTapes_other slots base values hlen _ (slots.injective.ne (by simp))
        (fun _ => slots.injective.ne (by simp))]
    exact clean.hornerScratch

theorem cleanup_result (slots : Tape q width ↪ K) (base : K → List Bool)
    (B : Nat) (values : List Nat) (hlen : values.length = width) (clean : Clean slots base) :
    MachineDrainMany.finalTapes (chosen slots) (afterHorner slots base B values) =
      resultTapes slots base (CanonicalAddress.radix B values) := by
  have hv : MachineHorner.value B (digits values) width = CanonicalAddress.radix B values := by
    rw [← hlen, hornerValue_eq_radix]
  funext tape
  rw [MachineDrainMany.finalTapes_apply]
  by_cases hd : tape ∈ chosen slots
  · rw [ite_eq_left hd]
    obtain ⟨i, rfl⟩ := (mem_chosen slots tape).mp hd
    simp [resultTapes, slots.injective.ne (show Tape.digit i ≠ Tape.output by simp), clean.digit]
  · rw [ite_eq_right hd]
    have notDigit : ∀ i, tape ≠ slots (.digit i) := by
      intro i hi
      exact hd ((mem_chosen slots tape).mpr ⟨i, hi.symm⟩)
    by_cases ho : tape = slots .output
    · subst tape
      simp only [afterHorner, MachineHorner.resultTapes,
        show hornerSlots slots (.inl 3) = slots .output from rfl,
        Function.update_self, resultTapes_output, hv]
      rw [parsedTapes_other slots base values hlen _ (slots.injective.ne (by simp)) notDigit]
    · simp only [afterHorner, MachineHorner.resultTapes,
        show hornerSlots slots (.inl 3) = slots .output from rfl,
        resultTapes, Function.update_of_ne ho]
      by_cases hf : tape = slots .forward
      · subst tape
        rw [parsedTapes_source slots base values hlen, clean.forward]
      · exact parsedTapes_other slots base values hlen tape hf notDigit

section Execution

variable (tokens : List (MachineFieldTemplate.Token q)) (slots : Tape q width ↪ K)
variable (place : Label tokens.length width (chosen slots) → Λ) (exit : Option Λ)
variable (P : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ))
variable (atInstruction : ∀ l, P (place l) = instruction tokens slots place exit l)

include atInstruction

omit [DecidableEq K] in
theorem parse_atStart (r : Nat) (hr : r < width) :
    P (place (parseLabel (SourceFieldArray.startLabel width r))) =
      SourceMachine.fieldStart (parseDestination slots r)
        (place (parseLabel (SourceFieldArray.loopLabel width r))) := by
  rw [atInstruction]
  simp [instruction, parseLabel, SourceFieldArray.startLabel, SourceFieldArray.loopLabel,
    SourceFieldArray.boundedIndex_val hr.le, hr]

omit [DecidableEq K] in
theorem parse_atLoop (r : Nat) (hr : r < width) :
    P (place (parseLabel (SourceFieldArray.loopLabel width r))) =
      SourceMachine.fieldLoop (slots .forward) (parseDestination slots r)
        (place (parseLabel (SourceFieldArray.loopLabel width r)))
        (some (place (parseLabel (SourceFieldArray.startLabel width (r + 1))))) := by
  rw [atInstruction]
  simp [instruction, parseLabel, SourceFieldArray.startLabel, SourceFieldArray.loopLabel,
    SourceFieldArray.boundedIndex_val hr.le, hr]

omit [DecidableEq K] in
theorem parse_atDone :
    P (place (parseLabel (SourceFieldArray.startLabel width width))) =
      SourceFieldArray.finish (slots .forward) (some (place (hornerLabel .start))) := by
  rw [atInstruction]
  simp [instruction, parseLabel, SourceFieldArray.startLabel]

theorem phaseTrace (base : K → List Bool) (B : Nat) (values : List Nat)
    (hlen : values.length = width) (clean : Clean slots base)
    (baseField : base (slots .radix) = encodeWord B)
    (wordCorrect : MachineFieldTemplate.templateOutput tokens (fun j => base (slots (.field j))) =
      encodeWords values) (ambient : σ) (register : Option Bool) :
    (MachineComposition.advance (TM2.step P))^[phaseSteps tokens slots base B values]
      (some ⟨some (place (emitLabel (MachineFieldTemplate.startAt tokens.length 0))),
        ((ambient, ()), register), base⟩) =
      some ⟨exit, ((ambient, ()), none), resultTapes slots base (CanonicalAddress.radix B values)⟩ := by
  let emitted := MachineFieldTemplate.outputTapes base (slots .reversed) (encodeWords values)
  have emitRun := MachineFieldTemplate.phaseTrace tokens (fun j => slots (.field j))
    (slots .copyScratch) (slots .reversed)
    (fun _ => slots.injective.ne (by simp)) (fun _ => slots.injective.ne (by simp))
    (slots.injective.ne (by simp)) (fun l => place (emitLabel l))
    (some (place reverseLabel)) P (fun l => atInstruction (emitLabel l))
    base clean.copyScratch ((ambient, ()), register)
  rw [wordCorrect] at emitRun
  change (MachineComposition.advance (TM2.step P))^[_] _ =
    some ⟨some (place reverseLabel), ((ambient, ()), none), emitted⟩ at emitRun
  have reverseRun := MachineTransfer.transferAt_fromTapes
    (Γ := fun _ : K => Bool) (σ := σ × Unit)
    (slots .reversed) (slots .forward) (slots.injective.ne (by simp)) id false
    (place reverseLabel) (some (place (parseLabel (SourceFieldArray.startLabel width 0))))
    P (atInstruction reverseLabel) emitted (ambient, ()) none
  have reverseResult : MachineTransfer.tapesAt (slots .reversed) (slots .forward) emitted []
      ((emitted (slots .reversed)).reverse.map id ++ emitted (slots .forward)) =
      forwardTapes slots base values := by
    funext tape
    by_cases hr : tape = slots .reversed
    · subst tape
      simp [emitted, MachineFieldTemplate.outputTapes, MachineTransfer.tapesAt, forwardTapes,
        slots.injective.ne (show Tape.reversed ≠ Tape.forward by simp), clean.reversed]
    · by_cases hf : tape = slots .forward
      · subst tape
        simp [emitted, MachineFieldTemplate.outputTapes, MachineTransfer.tapesAt, forwardTapes,
          slots.injective.ne (show Tape.forward ≠ Tape.reversed by simp),
          clean.reversed, clean.forward]
      · simp [emitted, MachineFieldTemplate.outputTapes, MachineTransfer.tapesAt,
          forwardTapes, hr, hf]
  rw [reverseResult] at reverseRun
  have reverseLength : (emitted (slots .reversed)).length + 1 = (encodeWords values).length + 1 := by
    simp [emitted, MachineFieldTemplate.outputTapes, clean.reversed]
  rw [reverseLength] at reverseRun
  change (MachineComposition.advance (TM2.step P))^[(encodeWords values).length + 1]
    (some ⟨some (place reverseLabel), ((ambient, ()), none), emitted⟩) =
    some ⟨some (place (parseLabel (SourceFieldArray.startLabel width 0))),
      ((ambient, ()), none), forwardTapes slots base values⟩ at reverseRun
  have parseRun := SourceFieldArray.sequenceTrace (slots .forward) (parseDestination slots)
    (fun r => place (parseLabel (SourceFieldArray.startLabel width r)))
    (fun r => place (parseLabel (SourceFieldArray.loopLabel width r)))
    (some (place (hornerLabel .start))) P (forwardTapes slots base values) 0 values []
    (by
      intro r hr
      simp only [Nat.zero_add, parseDestination_below slots r (by omega)]
      exact slots.injective.ne (by simp))
    (by intro r hr; simpa using parse_atStart tokens slots place exit P atInstruction r (by omega))
    (by intro r hr; simpa using parse_atLoop tokens slots place exit P atInstruction r (by omega))
    (by simpa only [Nat.zero_add, hlen] using parse_atDone tokens slots place exit P atInstruction)
    (by simp [forwardTapes]) (ambient, ()) none
  change (MachineComposition.advance (TM2.step P))^[values.sum + 2 * values.length + 1]
    (some ⟨some (place (parseLabel (SourceFieldArray.startLabel width 0))),
      ((ambient, ()), none), forwardTapes slots base values⟩) =
    some ⟨some (place (hornerLabel .start)), ((ambient, ()), none),
      parsedTapes slots base values⟩ at parseRun
  have hbase : parsedTapes slots base values (hornerSlots slots (.inl 0)) = encodeWord B := by
    change parsedTapes slots base values (slots .radix) = _
    rw [parsedTapes_other slots base values hlen _ (slots.injective.ne (by simp))
      (fun _ => slots.injective.ne (by simp))]
    exact baseField
  have hornerRun := MachineHorner.hornerTrace (hornerSlots slots) (fun l => place (hornerLabel l))
    (MachineDrainMany.entry (chosen slots) (fun l => place (cleanupLabel l)) exit)
    P (fun l => atInstruction (hornerLabel l)) (parsedTapes slots base values) B (digits values)
    hbase (parsedTapes_digit slots base values hlen clean)
    (parsedTapes_clean slots base values hlen clean) ambient none
  have cleanupRun := MachineDrainMany.trace (chosen slots) (fun l => place (cleanupLabel l)) exit
    P (fun l => atInstruction (cleanupLabel l)) (afterHorner slots base B values) (ambient, ()) none
  rw [MachineDrainMany.finalRegister_none, cleanup_result slots base B values hlen clean] at cleanupRun
  rw [show phaseSteps tokens slots base B values =
    MachineDrainMany.steps (chosen slots) (afterHorner slots base B values) +
      (MachineHorner.steps B (digits values) width +
      ((values.sum + 2 * values.length + 1) +
      (((encodeWords values).length + 1) +
      MachineFieldTemplate.templateSteps tokens (fun j => base (slots (.field j)))))) by
        unfold phaseSteps; omega]
  rw [Function.iterate_add_apply]
  rw [Function.iterate_add_apply (m := MachineHorner.steps B (digits values) width)]
  rw [Function.iterate_add_apply (m := values.sum + 2 * values.length + 1)]
  rw [Function.iterate_add_apply (m := (encodeWords values).length + 1)]
  rw [emitRun, reverseRun, parseRun, hornerRun]
  exact cleanupRun

end Execution

/-- The emitted finite program discharges every instruction-placement premise. -/
theorem programTrace (tokens : List (MachineFieldTemplate.Token q)) (slots : Tape q width ↪ K)
    (exit : Option (Label tokens.length width (chosen slots)))
    (base : K → List Bool) (B : Nat) (values : List Nat) (hlen : values.length = width)
    (clean : Clean slots base) (baseField : base (slots .radix) = encodeWord B)
    (wordCorrect : MachineFieldTemplate.templateOutput tokens (fun j => base (slots (.field j))) =
      encodeWords values) (ambient : σ) (register : Option Bool) :
    (MachineComposition.advance (TM2.step (program tokens slots exit)))^[phaseSteps tokens slots base B values]
      (some ⟨some (emitLabel (MachineFieldTemplate.startAt tokens.length 0)),
        ((ambient, ()), register), base⟩) =
      some ⟨exit, ((ambient, ()), none), resultTapes slots base (CanonicalAddress.radix B values)⟩ :=
  phaseTrace tokens slots id exit (program tokens slots exit) (fun _ => rfl)
    base B values hlen clean baseField wordCorrect ambient register

/-- Timed witness with the exact sum of the five concrete phase counts. -/
def phaseInTime (tokens : List (MachineFieldTemplate.Token q)) (slots : Tape q width ↪ K)
    (place : Label tokens.length width (chosen slots) → Λ) (exit : Option Λ)
    (P : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ))
    (atInstruction : ∀ l, P (place l) = instruction tokens slots place exit l)
    (base : K → List Bool) (B : Nat) (values : List Nat) (hlen : values.length = width)
    (clean : Clean slots base) (baseField : base (slots .radix) = encodeWord B)
    (wordCorrect : MachineFieldTemplate.templateOutput tokens (fun j => base (slots (.field j))) =
      encodeWords values) (ambient : σ) (register : Option Bool) :
    StateTransition.EvalsToInTime (TM2.step P)
      ⟨some (place (emitLabel (MachineFieldTemplate.startAt tokens.length 0))),
        ((ambient, ()), register), base⟩
      (some ⟨exit, ((ambient, ()), none), resultTapes slots base (CanonicalAddress.radix B values)⟩)
      (phaseSteps tokens slots base B values) where
  steps := phaseSteps tokens slots base B values
  evals_in_steps := phaseTrace tokens slots place exit P atInstruction
    base B values hlen clean baseField wordCorrect ambient register
  steps_le_m := Nat.le_refl _

omit [DecidableEq K] in
private theorem copiedLength_le (tokens : List (MachineFieldTemplate.Token q))
    (fields : Fin q → List Bool) (M : Nat) (bounded : ∀ j, (fields j).length ≤ M) :
    MachineFieldTemplate.copiedLength tokens fields ≤ tokens.length * M := by
  induction tokens with
  | nil => simp [MachineFieldTemplate.copiedLength]
  | cons token tokens ih =>
    cases token with
    | literal bits =>
      simp only [MachineFieldTemplate.copiedLength, List.map_cons, List.sum_cons,
        List.length_cons, Nat.zero_add] at *
      nlinarith
    | copy j =>
      simp only [MachineFieldTemplate.copiedLength, List.map_cons, List.sum_cons,
        List.length_cons] at *
      have h := bounded j
      nlinarith

omit [DecidableEq K] in
private theorem lengthSum_le (selected : List K) (base : K → List Bool) (bound : Nat)
    (bounded : ∀ tape ∈ selected, (base tape).length ≤ bound) :
    MachineDrainMany.lengthSum selected base ≤ selected.length * bound := by
  induction selected with
  | nil => simp [MachineDrainMany.lengthSum]
  | cons tape selected ih =>
    have ht := bounded tape (by simp)
    have hs := ih (fun t ht => bounded t (by simp [ht]))
    simp only [MachineDrainMany.lengthSum, List.map_cons, List.sum_cons,
      List.length_cons] at *
    nlinarith

/-- A fixed polynomial in a magnitude bounding input fields, the serialized
word list, the radix, and the digits. Width and token count are static. -/
noncomputable def timePolynomial (tokenCount width : Nat) : Polynomial Nat :=
  MachineHorner.timePolynomial width +
    Polynomial.C (3 * tokenCount + width + 2) * Polynomial.X +
    Polynomial.C (3 * tokenCount + 3 * width + 3)

omit [DecidableEq K] in
theorem timePolynomial_eval (tokenCount width M : Nat) :
    (timePolynomial tokenCount width).eval M =
      (MachineHorner.timePolynomial width).eval M +
      (3 * tokenCount + width + 2) * M + (3 * tokenCount + 3 * width + 3) := by
  simp [timePolynomial]

theorem phaseSteps_le_timePolynomial (tokens : List (MachineFieldTemplate.Token q))
    (slots : Tape q width ↪ K) (base : K → List Bool) (B : Nat) (values : List Nat)
    (hlen : values.length = width) (clean : Clean slots base) (M : Nat)
    (fieldsBound : ∀ j, (base (slots (.field j))).length ≤ M)
    (wordsBound : (encodeWords values).length ≤ M) (radixBound : B ≤ M)
    (digitBound : ∀ i, i < width → digits values i ≤ M) :
    phaseSteps tokens slots base B values ≤ (timePolynomial tokens.length width).eval M := by
  have hcopied := copiedLength_le tokens (fun j => base (slots (.field j))) M fieldsBound
  have htemplate := MachineFieldTemplate.templateSteps_le tokens (fun j => base (slots (.field j)))
  have hhorner := MachineHorner.steps_le_timePolynomial B (digits values) width M radixBound digitBound
  have hselected : ∀ tape ∈ chosen slots, (afterHorner slots base B values tape).length ≤ M + 1 := by
    intro tape ht
    obtain ⟨i, rfl⟩ := (mem_chosen slots tape).mp ht
    have heq : afterHorner slots base B values (slots (.digit i)) =
        encodeWord (digits values i.val) := by
      simp only [afterHorner, MachineHorner.resultTapes,
        show hornerSlots slots (.inl 3) = slots .output from rfl,
        Function.update_of_ne (slots.injective.ne (show Tape.digit i ≠ Tape.output by simp))]
      exact parsedTapes_digit slots base values hlen clean i
    rw [heq]
    simpa only [encodeWord, List.length_append, List.length_replicate, List.length_singleton] using
      Nat.add_le_add_right (digitBound i.val i.isLt) 1
  have hsum := lengthSum_le (chosen slots) (afterHorner slots base B values) (M + 1) hselected
  have hcleanup := MachineDrainMany.steps_le (chosen slots) (afterHorner slots base B values)
  have hchosen : (chosen slots).length = width := by simp [chosen]
  rw [hchosen] at hsum hcleanup
  have hparse := SourceFieldArray.sequence_time_eq_length values
  rw [hlen] at hparse
  rw [timePolynomial_eval]
  unfold phaseSteps
  rw [hlen]
  nlinarith

def phaseInPolynomialTime (tokens : List (MachineFieldTemplate.Token q))
    (slots : Tape q width ↪ K) (place : Label tokens.length width (chosen slots) → Λ)
    (exit : Option Λ) (P : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ))
    (atInstruction : ∀ l, P (place l) = instruction tokens slots place exit l)
    (base : K → List Bool) (B : Nat) (values : List Nat) (hlen : values.length = width)
    (clean : Clean slots base) (baseField : base (slots .radix) = encodeWord B)
    (wordCorrect : MachineFieldTemplate.templateOutput tokens (fun j => base (slots (.field j))) =
      encodeWords values) (ambient : σ) (register : Option Bool) (M : Nat)
    (fieldsBound : ∀ j, (base (slots (.field j))).length ≤ M)
    (wordsBound : (encodeWords values).length ≤ M) (radixBound : B ≤ M)
    (digitBound : ∀ i, i < width → digits values i ≤ M) :
    StateTransition.EvalsToInTime (TM2.step P)
      ⟨some (place (emitLabel (MachineFieldTemplate.startAt tokens.length 0))),
        ((ambient, ()), register), base⟩
      (some ⟨exit, ((ambient, ()), none), resultTapes slots base (CanonicalAddress.radix B values)⟩)
      ((timePolynomial tokens.length width).eval M) where
  steps := phaseSteps tokens slots base B values
  evals_in_steps := phaseTrace tokens slots place exit P atInstruction
    base B values hlen clean baseField wordCorrect ambient register
  steps_le_m := phaseSteps_le_timePolynomial tokens slots base B values hlen clean M
    fieldsBound wordsBound radixBound digitBound

end UniqueGamesTheorem.Reduction.MachineTemplateAddress

end

end OAI