-
Notifications
You must be signed in to change notification settings - Fork 251
/
TMToPartrec.lean
2071 lines (1846 loc) · 98.8 KB
/
TMToPartrec.lean
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/-
Copyright (c) 2020 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.Computability.Halting
import Mathlib.Computability.TuringMachine
import Mathlib.Data.Num.Lemmas
import Mathlib.Tactic.DeriveFintype
#align_import computability.tm_to_partrec from "leanprover-community/mathlib"@"6155d4351090a6fad236e3d2e4e0e4e7342668e8"
/-!
# Modelling partial recursive functions using Turing machines
This file defines a simplified basis for partial recursive functions, and a `Turing.TM2` model
Turing machine for evaluating these functions. This amounts to a constructive proof that every
`Partrec` function can be evaluated by a Turing machine.
## Main definitions
* `ToPartrec.Code`: a simplified basis for partial recursive functions, valued in
`List ℕ →. List ℕ`.
* `ToPartrec.Code.eval`: semantics for a `ToPartrec.Code` program
* `PartrecToTM2.tr`: A TM2 turing machine which can evaluate `code` programs
-/
open Function (update)
open Relation
namespace Turing
/-!
## A simplified basis for partrec
This section constructs the type `Code`, which is a data type of programs with `List ℕ` input and
output, with enough expressivity to write any partial recursive function. The primitives are:
* `zero'` appends a `0` to the input. That is, `zero' v = 0 :: v`.
* `succ` returns the successor of the head of the input, defaulting to zero if there is no head:
* `succ [] = [1]`
* `succ (n :: v) = [n + 1]`
* `tail` returns the tail of the input
* `tail [] = []`
* `tail (n :: v) = v`
* `cons f fs` calls `f` and `fs` on the input and conses the results:
* `cons f fs v = (f v).head :: fs v`
* `comp f g` calls `f` on the output of `g`:
* `comp f g v = f (g v)`
* `case f g` cases on the head of the input, calling `f` or `g` depending on whether it is zero or
a successor (similar to `Nat.casesOn`).
* `case f g [] = f []`
* `case f g (0 :: v) = f v`
* `case f g (n+1 :: v) = g (n :: v)`
* `fix f` calls `f` repeatedly, using the head of the result of `f` to decide whether to call `f`
again or finish:
* `fix f v = []` if `f v = []`
* `fix f v = w` if `f v = 0 :: w`
* `fix f v = fix f w` if `f v = n+1 :: w` (the exact value of `n` is discarded)
This basis is convenient because it is closer to the Turing machine model - the key operations are
splitting and merging of lists of unknown length, while the messy `n`-ary composition operation
from the traditional basis for partial recursive functions is absent - but it retains a
compositional semantics. The first step in transitioning to Turing machines is to make a sequential
evaluator for this basis, which we take up in the next section.
-/
namespace ToPartrec
/-- The type of codes for primitive recursive functions. Unlike `Nat.Partrec.Code`, this uses a set
of operations on `List ℕ`. See `Code.eval` for a description of the behavior of the primitives. -/
inductive Code
| zero'
| succ
| tail
| cons : Code → Code → Code
| comp : Code → Code → Code
| case : Code → Code → Code
| fix : Code → Code
deriving DecidableEq, Inhabited
#align turing.to_partrec.code Turing.ToPartrec.Code
#align turing.to_partrec.code.zero' Turing.ToPartrec.Code.zero'
#align turing.to_partrec.code.succ Turing.ToPartrec.Code.succ
#align turing.to_partrec.code.tail Turing.ToPartrec.Code.tail
#align turing.to_partrec.code.cons Turing.ToPartrec.Code.cons
#align turing.to_partrec.code.comp Turing.ToPartrec.Code.comp
#align turing.to_partrec.code.case Turing.ToPartrec.Code.case
#align turing.to_partrec.code.fix Turing.ToPartrec.Code.fix
/-- The semantics of the `Code` primitives, as partial functions `List ℕ →. List ℕ`. By convention
we functions that return a single result return a singleton `[n]`, or in some cases `n :: v` where
`v` will be ignored by a subsequent function.
* `zero'` appends a `0` to the input. That is, `zero' v = 0 :: v`.
* `succ` returns the successor of the head of the input, defaulting to zero if there is no head:
* `succ [] = [1]`
* `succ (n :: v) = [n + 1]`
* `tail` returns the tail of the input
* `tail [] = []`
* `tail (n :: v) = v`
* `cons f fs` calls `f` and `fs` on the input and conses the results:
* `cons f fs v = (f v).head :: fs v`
* `comp f g` calls `f` on the output of `g`:
* `comp f g v = f (g v)`
* `case f g` cases on the head of the input, calling `f` or `g` depending on whether it is zero or
a successor (similar to `Nat.casesOn`).
* `case f g [] = f []`
* `case f g (0 :: v) = f v`
* `case f g (n+1 :: v) = g (n :: v)`
* `fix f` calls `f` repeatedly, using the head of the result of `f` to decide whether to call `f`
again or finish:
* `fix f v = []` if `f v = []`
* `fix f v = w` if `f v = 0 :: w`
* `fix f v = fix f w` if `f v = n+1 :: w` (the exact value of `n` is discarded)
-/
def Code.eval : Code → List ℕ →. List ℕ
| Code.zero' => fun v => pure (0 :: v)
| Code.succ => fun v => pure [v.headI.succ]
| Code.tail => fun v => pure v.tail
| Code.cons f fs => fun v => do
let n ← Code.eval f v
let ns ← Code.eval fs v
pure (n.headI :: ns)
| Code.comp f g => fun v => g.eval v >>= f.eval
| Code.case f g => fun v => v.headI.rec (f.eval v.tail) fun y _ => g.eval (y::v.tail)
| Code.fix f =>
PFun.fix fun v => (f.eval v).map fun v => if v.headI = 0 then Sum.inl v.tail else Sum.inr v.tail
#align turing.to_partrec.code.eval Turing.ToPartrec.Code.eval
namespace Code
/- Porting note: The equation lemma of `eval` is too strong; it simplifies terms like the LHS of
`pred_eval`. Even `eqns` can't fix this. We removed `simp` attr from `eval` and prepare new simp
lemmas for `eval`. -/
@[simp]
theorem zero'_eval : zero'.eval = fun v => pure (0 :: v) := by simp [eval]
@[simp]
theorem succ_eval : succ.eval = fun v => pure [v.headI.succ] := by simp [eval]
@[simp]
theorem tail_eval : tail.eval = fun v => pure v.tail := by simp [eval]
@[simp]
theorem cons_eval (f fs) : (cons f fs).eval = fun v => do {
let n ← Code.eval f v
let ns ← Code.eval fs v
pure (n.headI :: ns) } := by simp [eval]
@[simp]
theorem comp_eval (f g) : (comp f g).eval = fun v => g.eval v >>= f.eval := by simp [eval]
@[simp]
theorem case_eval (f g) :
(case f g).eval = fun v => v.headI.rec (f.eval v.tail) fun y _ => g.eval (y::v.tail) := by
simp [eval]
@[simp]
theorem fix_eval (f) : (fix f).eval =
PFun.fix fun v => (f.eval v).map fun v =>
if v.headI = 0 then Sum.inl v.tail else Sum.inr v.tail := by
simp [eval]
/-- `nil` is the constant nil function: `nil v = []`. -/
def nil : Code :=
tail.comp succ
#align turing.to_partrec.code.nil Turing.ToPartrec.Code.nil
@[simp]
theorem nil_eval (v) : nil.eval v = pure [] := by simp [nil]
#align turing.to_partrec.code.nil_eval Turing.ToPartrec.Code.nil_eval
/-- `id` is the identity function: `id v = v`. -/
def id : Code :=
tail.comp zero'
#align turing.to_partrec.code.id Turing.ToPartrec.Code.id
@[simp]
theorem id_eval (v) : id.eval v = pure v := by simp [id]
#align turing.to_partrec.code.id_eval Turing.ToPartrec.Code.id_eval
/-- `head` gets the head of the input list: `head [] = [0]`, `head (n :: v) = [n]`. -/
def head : Code :=
cons id nil
#align turing.to_partrec.code.head Turing.ToPartrec.Code.head
@[simp]
theorem head_eval (v) : head.eval v = pure [v.headI] := by simp [head]
#align turing.to_partrec.code.head_eval Turing.ToPartrec.Code.head_eval
/-- `zero` is the constant zero function: `zero v = [0]`. -/
def zero : Code :=
cons zero' nil
#align turing.to_partrec.code.zero Turing.ToPartrec.Code.zero
@[simp]
theorem zero_eval (v) : zero.eval v = pure [0] := by simp [zero]
#align turing.to_partrec.code.zero_eval Turing.ToPartrec.Code.zero_eval
/-- `pred` returns the predecessor of the head of the input:
`pred [] = [0]`, `pred (0 :: v) = [0]`, `pred (n+1 :: v) = [n]`. -/
def pred : Code :=
case zero head
#align turing.to_partrec.code.pred Turing.ToPartrec.Code.pred
@[simp]
theorem pred_eval (v) : pred.eval v = pure [v.headI.pred] := by
simp [pred]; cases v.headI <;> simp
#align turing.to_partrec.code.pred_eval Turing.ToPartrec.Code.pred_eval
/-- `rfind f` performs the function of the `rfind` primitive of partial recursive functions.
`rfind f v` returns the smallest `n` such that `(f (n :: v)).head = 0`.
It is implemented as:
rfind f v = pred (fix (fun (n::v) => f (n::v) :: n+1 :: v) (0 :: v))
The idea is that the initial state is `0 :: v`, and the `fix` keeps `n :: v` as its internal state;
it calls `f (n :: v)` as the exit test and `n+1 :: v` as the next state. At the end we get
`n+1 :: v` where `n` is the desired output, and `pred (n+1 :: v) = [n]` returns the result.
-/
def rfind (f : Code) : Code :=
comp pred <| comp (fix <| cons f <| cons succ tail) zero'
#align turing.to_partrec.code.rfind Turing.ToPartrec.Code.rfind
/-- `prec f g` implements the `prec` (primitive recursion) operation of partial recursive
functions. `prec f g` evaluates as:
* `prec f g [] = [f []]`
* `prec f g (0 :: v) = [f v]`
* `prec f g (n+1 :: v) = [g (n :: prec f g (n :: v) :: v)]`
It is implemented as:
G (a :: b :: IH :: v) = (b :: a+1 :: b-1 :: g (a :: IH :: v) :: v)
F (0 :: f_v :: v) = (f_v :: v)
F (n+1 :: f_v :: v) = (fix G (0 :: n :: f_v :: v)).tail.tail
prec f g (a :: v) = [(F (a :: f v :: v)).head]
Because `fix` always evaluates its body at least once, we must special case the `0` case to avoid
calling `g` more times than necessary (which could be bad if `g` diverges). If the input is
`0 :: v`, then `F (0 :: f v :: v) = (f v :: v)` so we return `[f v]`. If the input is `n+1 :: v`,
we evaluate the function from the bottom up, with initial state `0 :: n :: f v :: v`. The first
number counts up, providing arguments for the applications to `g`, while the second number counts
down, providing the exit condition (this is the initial `b` in the return value of `G`, which is
stripped by `fix`). After the `fix` is complete, the final state is `n :: 0 :: res :: v` where
`res` is the desired result, and the rest reduces this to `[res]`. -/
def prec (f g : Code) : Code :=
let G :=
cons tail <|
cons succ <|
cons (comp pred tail) <|
cons (comp g <| cons id <| comp tail tail) <| comp tail <| comp tail tail
let F := case id <| comp (comp (comp tail tail) (fix G)) zero'
cons (comp F (cons head <| cons (comp f tail) tail)) nil
#align turing.to_partrec.code.prec Turing.ToPartrec.Code.prec
attribute [-simp] Part.bind_eq_bind Part.map_eq_map Part.pure_eq_some
theorem exists_code.comp {m n} {f : Vector ℕ n →. ℕ} {g : Fin n → Vector ℕ m →. ℕ}
(hf : ∃ c : Code, ∀ v : Vector ℕ n, c.eval v.1 = pure <$> f v)
(hg : ∀ i, ∃ c : Code, ∀ v : Vector ℕ m, c.eval v.1 = pure <$> g i v) :
∃ c : Code, ∀ v : Vector ℕ m, c.eval v.1 = pure <$> ((Vector.mOfFn fun i => g i v) >>= f) := by
rsuffices ⟨cg, hg⟩ :
∃ c : Code, ∀ v : Vector ℕ m, c.eval v.1 = Subtype.val <$> Vector.mOfFn fun i => g i v
· obtain ⟨cf, hf⟩ := hf
exact
⟨cf.comp cg, fun v => by
simp [hg, hf, map_bind, seq_bind_eq, Function.comp]
rfl⟩
clear hf f; induction' n with n IH
· exact ⟨nil, fun v => by simp [Vector.mOfFn, Bind.bind]; rfl⟩
· obtain ⟨cg, hg₁⟩ := hg 0
obtain ⟨cl, hl⟩ := IH fun i => hg i.succ
exact
⟨cons cg cl, fun v => by
simp [Vector.mOfFn, hg₁, map_bind, seq_bind_eq, bind_assoc, (· ∘ ·), hl]
rfl⟩
#align turing.to_partrec.code.exists_code.comp Turing.ToPartrec.Code.exists_code.comp
theorem exists_code {n} {f : Vector ℕ n →. ℕ} (hf : Nat.Partrec' f) :
∃ c : Code, ∀ v : Vector ℕ n, c.eval v.1 = pure <$> f v := by
induction hf with
| prim hf =>
induction hf with
| zero => exact ⟨zero', fun ⟨[], _⟩ => rfl⟩
| succ => exact ⟨succ, fun ⟨[v], _⟩ => rfl⟩
| get i =>
refine Fin.succRec (fun n => ?_) (fun n i IH => ?_) i
· exact ⟨head, fun ⟨List.cons a as, _⟩ => by simp [Bind.bind]; rfl⟩
· obtain ⟨c, h⟩ := IH
exact ⟨c.comp tail, fun v => by simpa [← Vector.get_tail, Bind.bind] using h v.tail⟩
| comp g hf hg IHf IHg =>
simpa [Part.bind_eq_bind] using exists_code.comp IHf IHg
| @prec n f g _ _ IHf IHg =>
obtain ⟨cf, hf⟩ := IHf
obtain ⟨cg, hg⟩ := IHg
simp only [Part.map_eq_map, Part.map_some, PFun.coe_val] at hf hg
refine ⟨prec cf cg, fun v => ?_⟩
rw [← v.cons_head_tail]
specialize hf v.tail
replace hg := fun a b => hg (a ::ᵥ b ::ᵥ v.tail)
simp only [Vector.cons_val, Vector.tail_val] at hf hg
simp only [Part.map_eq_map, Part.map_some, Vector.cons_val, Vector.tail_cons,
Vector.head_cons, PFun.coe_val, Vector.tail_val]
simp only [← Part.pure_eq_some] at hf hg ⊢
induction' v.head with n _ <;>
simp [prec, hf, Part.bind_assoc, ← Part.bind_some_eq_map, Part.bind_some,
show ∀ x, pure x = [x] from fun _ => rfl, Bind.bind, Functor.map]
suffices ∀ a b, a + b = n →
(n.succ :: 0 ::
g (n ::ᵥ Nat.rec (f v.tail) (fun y IH => g (y ::ᵥ IH ::ᵥ v.tail)) n ::ᵥ v.tail) ::
v.val.tail : List ℕ) ∈
PFun.fix
(fun v : List ℕ => Part.bind (cg.eval (v.headI :: v.tail.tail))
(fun x => Part.some (if v.tail.headI = 0
then Sum.inl
(v.headI.succ :: v.tail.headI.pred :: x.headI :: v.tail.tail.tail : List ℕ)
else Sum.inr
(v.headI.succ :: v.tail.headI.pred :: x.headI :: v.tail.tail.tail))))
(a :: b :: Nat.rec (f v.tail) (fun y IH => g (y ::ᵥ IH ::ᵥ v.tail)) a :: v.val.tail) by
erw [Part.eq_some_iff.2 (this 0 n (zero_add n))]
simp only [List.headI, Part.bind_some, List.tail_cons]
intro a b e
induction' b with b IH generalizing a
· refine PFun.mem_fix_iff.2 (Or.inl <| Part.eq_some_iff.1 ?_)
simp only [hg, ← e, Part.bind_some, List.tail_cons, pure]
rfl
· refine PFun.mem_fix_iff.2 (Or.inr ⟨_, ?_, IH (a + 1) (by rwa [add_right_comm])⟩)
simp only [hg, eval, Part.bind_some, Nat.rec_add_one, List.tail_nil, List.tail_cons, pure]
exact Part.mem_some_iff.2 rfl
| comp g _ _ IHf IHg => exact exists_code.comp IHf IHg
| @rfind n f _ IHf =>
obtain ⟨cf, hf⟩ := IHf; refine ⟨rfind cf, fun v => ?_⟩
replace hf := fun a => hf (a ::ᵥ v)
simp only [Part.map_eq_map, Part.map_some, Vector.cons_val, PFun.coe_val,
show ∀ x, pure x = [x] from fun _ => rfl] at hf ⊢
refine Part.ext fun x => ?_
simp only [rfind, Part.bind_eq_bind, Part.pure_eq_some, Part.map_eq_map, Part.bind_some,
exists_prop, cons_eval, comp_eval, fix_eval, tail_eval, succ_eval, zero'_eval,
List.headI_nil, List.headI_cons, pred_eval, Part.map_some, false_eq_decide_iff,
Part.mem_bind_iff, List.length, Part.mem_map_iff, Nat.mem_rfind, List.tail_nil,
List.tail_cons, true_eq_decide_iff, Part.mem_some_iff, Part.map_bind]
constructor
· rintro ⟨v', h1, rfl⟩
suffices ∀ v₁ : List ℕ, v' ∈ PFun.fix
(fun v => (cf.eval v).bind fun y => Part.some <|
if y.headI = 0 then Sum.inl (v.headI.succ :: v.tail)
else Sum.inr (v.headI.succ :: v.tail)) v₁ →
∀ n, (v₁ = n :: v.val) → (∀ m < n, ¬f (m ::ᵥ v) = 0) →
∃ a : ℕ,
(f (a ::ᵥ v) = 0 ∧ ∀ {m : ℕ}, m < a → ¬f (m ::ᵥ v) = 0) ∧ [a] = [v'.headI.pred]
by exact this _ h1 0 rfl (by rintro _ ⟨⟩)
clear h1
intro v₀ h1
refine PFun.fixInduction h1 fun v₁ h2 IH => ?_
clear h1
rintro n rfl hm
have := PFun.mem_fix_iff.1 h2
simp only [hf, Part.bind_some] at this
split_ifs at this with h
· simp only [List.headI_nil, List.headI_cons, exists_false, or_false_iff, Part.mem_some_iff,
List.tail_cons, false_and_iff, Sum.inl.injEq] at this
subst this
exact ⟨_, ⟨h, @(hm)⟩, rfl⟩
· refine IH (n.succ::v.val) (by simp_all) _ rfl fun m h' => ?_
obtain h | rfl := Nat.lt_succ_iff_lt_or_eq.1 h'
exacts [hm _ h, h]
· rintro ⟨n, ⟨hn, hm⟩, rfl⟩
refine ⟨n.succ::v.1, ?_, rfl⟩
have : (n.succ::v.1 : List ℕ) ∈
PFun.fix (fun v =>
(cf.eval v).bind fun y =>
Part.some <|
if y.headI = 0 then Sum.inl (v.headI.succ :: v.tail)
else Sum.inr (v.headI.succ :: v.tail))
(n::v.val) :=
PFun.mem_fix_iff.2 (Or.inl (by simp [hf, hn]))
generalize (n.succ :: v.1 : List ℕ) = w at this ⊢
clear hn
induction' n with n IH
· exact this
refine IH (fun {m} h' => hm (Nat.lt_succ_of_lt h'))
(PFun.mem_fix_iff.2 (Or.inr ⟨_, ?_, this⟩))
simp only [hf, hm n.lt_succ_self, Part.bind_some, List.headI, eq_self_iff_true, if_false,
Part.mem_some_iff, and_self_iff, List.tail_cons]
#align turing.to_partrec.code.exists_code Turing.ToPartrec.Code.exists_code
end Code
/-!
## From compositional semantics to sequential semantics
Our initial sequential model is designed to be as similar as possible to the compositional
semantics in terms of its primitives, but it is a sequential semantics, meaning that rather than
defining an `eval c : List ℕ →. List ℕ` function for each program, defined by recursion on
programs, we have a type `Cfg` with a step function `step : Cfg → Option cfg` that provides a
deterministic evaluation order. In order to do this, we introduce the notion of a *continuation*,
which can be viewed as a `Code` with a hole in it where evaluation is currently taking place.
Continuations can be assigned a `List ℕ →. List ℕ` semantics as well, with the interpretation
being that given a `List ℕ` result returned from the code in the hole, the remainder of the
program will evaluate to a `List ℕ` final value.
The continuations are:
* `halt`: the empty continuation: the hole is the whole program, whatever is returned is the
final result. In our notation this is just `_`.
* `cons₁ fs v k`: evaluating the first part of a `cons`, that is `k (_ :: fs v)`, where `k` is the
outer continuation.
* `cons₂ ns k`: evaluating the second part of a `cons`: `k (ns.headI :: _)`. (Technically we don't
need to hold on to all of `ns` here since we are already committed to taking the head, but this
is more regular.)
* `comp f k`: evaluating the first part of a composition: `k (f _)`.
* `fix f k`: waiting for the result of `f` in a `fix f` expression:
`k (if _.headI = 0 then _.tail else fix f (_.tail))`
The type `Cfg` of evaluation states is:
* `ret k v`: we have received a result, and are now evaluating the continuation `k` with result
`v`; that is, `k v` where `k` is ready to evaluate.
* `halt v`: we are done and the result is `v`.
The main theorem of this section is that for each code `c`, the state `stepNormal c halt v` steps
to `v'` in finitely many steps if and only if `Code.eval c v = some v'`.
-/
/-- The type of continuations, built up during evaluation of a `Code` expression. -/
inductive Cont
| halt
| cons₁ : Code → List ℕ → Cont → Cont
| cons₂ : List ℕ → Cont → Cont
| comp : Code → Cont → Cont
| fix : Code → Cont → Cont
deriving Inhabited
#align turing.to_partrec.cont Turing.ToPartrec.Cont
#align turing.to_partrec.cont.halt Turing.ToPartrec.Cont.halt
#align turing.to_partrec.cont.cons₁ Turing.ToPartrec.Cont.cons₁
#align turing.to_partrec.cont.cons₂ Turing.ToPartrec.Cont.cons₂
#align turing.to_partrec.cont.comp Turing.ToPartrec.Cont.comp
#align turing.to_partrec.cont.fix Turing.ToPartrec.Cont.fix
/-- The semantics of a continuation. -/
def Cont.eval : Cont → List ℕ →. List ℕ
| Cont.halt => pure
| Cont.cons₁ fs as k => fun v => do
let ns ← Code.eval fs as
Cont.eval k (v.headI :: ns)
| Cont.cons₂ ns k => fun v => Cont.eval k (ns.headI :: v)
| Cont.comp f k => fun v => Code.eval f v >>= Cont.eval k
| Cont.fix f k => fun v => if v.headI = 0 then k.eval v.tail else f.fix.eval v.tail >>= k.eval
#align turing.to_partrec.cont.eval Turing.ToPartrec.Cont.eval
/-- The set of configurations of the machine:
* `halt v`: The machine is about to stop and `v : List ℕ` is the result.
* `ret k v`: The machine is about to pass `v : List ℕ` to continuation `k : cont`.
We don't have a state corresponding to normal evaluation because these are evaluated immediately
to a `ret` "in zero steps" using the `stepNormal` function. -/
inductive Cfg
| halt : List ℕ → Cfg
| ret : Cont → List ℕ → Cfg
deriving Inhabited
#align turing.to_partrec.cfg Turing.ToPartrec.Cfg
#align turing.to_partrec.cfg.halt Turing.ToPartrec.Cfg.halt
#align turing.to_partrec.cfg.ret Turing.ToPartrec.Cfg.ret
/-- Evaluating `c : Code` in a continuation `k : Cont` and input `v : List ℕ`. This goes by
recursion on `c`, building an augmented continuation and a value to pass to it.
* `zero' v = 0 :: v` evaluates immediately, so we return it to the parent continuation
* `succ v = [v.headI.succ]` evaluates immediately, so we return it to the parent continuation
* `tail v = v.tail` evaluates immediately, so we return it to the parent continuation
* `cons f fs v = (f v).headI :: fs v` requires two sub-evaluations, so we evaluate
`f v` in the continuation `k (_.headI :: fs v)` (called `Cont.cons₁ fs v k`)
* `comp f g v = f (g v)` requires two sub-evaluations, so we evaluate
`g v` in the continuation `k (f _)` (called `Cont.comp f k`)
* `case f g v = v.head.casesOn (f v.tail) (fun n => g (n :: v.tail))` has the information needed
to evaluate the case statement, so we do that and transition to either
`f v` or `g (n :: v.tail)`.
* `fix f v = let v' := f v; if v'.headI = 0 then k v'.tail else fix f v'.tail`
needs to first evaluate `f v`, so we do that and leave the rest for the continuation (called
`Cont.fix f k`)
-/
def stepNormal : Code → Cont → List ℕ → Cfg
| Code.zero' => fun k v => Cfg.ret k (0::v)
| Code.succ => fun k v => Cfg.ret k [v.headI.succ]
| Code.tail => fun k v => Cfg.ret k v.tail
| Code.cons f fs => fun k v => stepNormal f (Cont.cons₁ fs v k) v
| Code.comp f g => fun k v => stepNormal g (Cont.comp f k) v
| Code.case f g => fun k v =>
v.headI.rec (stepNormal f k v.tail) fun y _ => stepNormal g k (y::v.tail)
| Code.fix f => fun k v => stepNormal f (Cont.fix f k) v
#align turing.to_partrec.step_normal Turing.ToPartrec.stepNormal
/-- Evaluating a continuation `k : Cont` on input `v : List ℕ`. This is the second part of
evaluation, when we receive results from continuations built by `stepNormal`.
* `Cont.halt v = v`, so we are done and transition to the `Cfg.halt v` state
* `Cont.cons₁ fs as k v = k (v.headI :: fs as)`, so we evaluate `fs as` now with the continuation
`k (v.headI :: _)` (called `cons₂ v k`).
* `Cont.cons₂ ns k v = k (ns.headI :: v)`, where we now have everything we need to evaluate
`ns.headI :: v`, so we return it to `k`.
* `Cont.comp f k v = k (f v)`, so we call `f v` with `k` as the continuation.
* `Cont.fix f k v = k (if v.headI = 0 then k v.tail else fix f v.tail)`, where `v` is a value,
so we evaluate the if statement and either call `k` with `v.tail`, or call `fix f v` with `k` as
the continuation (which immediately calls `f` with `Cont.fix f k` as the continuation).
-/
def stepRet : Cont → List ℕ → Cfg
| Cont.halt, v => Cfg.halt v
| Cont.cons₁ fs as k, v => stepNormal fs (Cont.cons₂ v k) as
| Cont.cons₂ ns k, v => stepRet k (ns.headI :: v)
| Cont.comp f k, v => stepNormal f k v
| Cont.fix f k, v => if v.headI = 0 then stepRet k v.tail else stepNormal f (Cont.fix f k) v.tail
#align turing.to_partrec.step_ret Turing.ToPartrec.stepRet
/-- If we are not done (in `Cfg.halt` state), then we must be still stuck on a continuation, so
this main loop calls `stepRet` with the new continuation. The overall `step` function transitions
from one `Cfg` to another, only halting at the `Cfg.halt` state. -/
def step : Cfg → Option Cfg
| Cfg.halt _ => none
| Cfg.ret k v => some (stepRet k v)
#align turing.to_partrec.step Turing.ToPartrec.step
/-- In order to extract a compositional semantics from the sequential execution behavior of
configurations, we observe that continuations have a monoid structure, with `Cont.halt` as the unit
and `Cont.then` as the multiplication. `Cont.then k₁ k₂` runs `k₁` until it halts, and then takes
the result of `k₁` and passes it to `k₂`.
We will not prove it is associative (although it is), but we are instead interested in the
associativity law `k₂ (eval c k₁) = eval c (k₁.then k₂)`. This holds at both the sequential and
compositional levels, and allows us to express running a machine without the ambient continuation
and relate it to the original machine's evaluation steps. In the literature this is usually
where one uses Turing machines embedded inside other Turing machines, but this approach allows us
to avoid changing the ambient type `Cfg` in the middle of the recursion.
-/
def Cont.then : Cont → Cont → Cont
| Cont.halt => fun k' => k'
| Cont.cons₁ fs as k => fun k' => Cont.cons₁ fs as (k.then k')
| Cont.cons₂ ns k => fun k' => Cont.cons₂ ns (k.then k')
| Cont.comp f k => fun k' => Cont.comp f (k.then k')
| Cont.fix f k => fun k' => Cont.fix f (k.then k')
#align turing.to_partrec.cont.then Turing.ToPartrec.Cont.then
theorem Cont.then_eval {k k' : Cont} {v} : (k.then k').eval v = k.eval v >>= k'.eval := by
induction' k with _ _ _ _ _ _ _ _ _ k_ih _ _ k_ih generalizing v <;>
simp only [Cont.eval, Cont.then, bind_assoc, pure_bind, *]
· simp only [← k_ih]
· split_ifs <;> [rfl; simp only [← k_ih, bind_assoc]]
#align turing.to_partrec.cont.then_eval Turing.ToPartrec.Cont.then_eval
/-- The `then k` function is a "configuration homomorphism". Its operation on states is to append
`k` to the continuation of a `Cfg.ret` state, and to run `k` on `v` if we are in the `Cfg.halt v`
state. -/
def Cfg.then : Cfg → Cont → Cfg
| Cfg.halt v => fun k' => stepRet k' v
| Cfg.ret k v => fun k' => Cfg.ret (k.then k') v
#align turing.to_partrec.cfg.then Turing.ToPartrec.Cfg.then
/-- The `stepNormal` function respects the `then k'` homomorphism. Note that this is an exact
equality, not a simulation; the original and embedded machines move in lock-step until the
embedded machine reaches the halt state. -/
theorem stepNormal_then (c) (k k' : Cont) (v) :
stepNormal c (k.then k') v = (stepNormal c k v).then k' := by
induction c generalizing k v with simp only [Cont.then, stepNormal, *]
| cons c c' ih _ => rw [← ih, Cont.then]
| comp c c' _ ih' => rw [← ih', Cont.then]
| case => cases v.headI <;> simp only [Nat.rec_zero]
| fix c ih => rw [← ih, Cont.then]
| _ => simp only [Cfg.then]
#align turing.to_partrec.step_normal_then Turing.ToPartrec.stepNormal_then
/-- The `stepRet` function respects the `then k'` homomorphism. Note that this is an exact
equality, not a simulation; the original and embedded machines move in lock-step until the
embedded machine reaches the halt state. -/
theorem stepRet_then {k k' : Cont} {v} : stepRet (k.then k') v = (stepRet k v).then k' := by
induction k generalizing v with simp only [Cont.then, stepRet, *]
| cons₁ =>
rw [← stepNormal_then]
rfl
| comp =>
rw [← stepNormal_then]
| fix _ _ k_ih =>
split_ifs
· rw [← k_ih]
· rw [← stepNormal_then]
rfl
| _ => simp only [Cfg.then]
#align turing.to_partrec.step_ret_then Turing.ToPartrec.stepRet_then
/-- This is a temporary definition, because we will prove in `code_is_ok` that it always holds.
It asserts that `c` is semantically correct; that is, for any `k` and `v`,
`eval (stepNormal c k v) = eval (Cfg.ret k (Code.eval c v))`, as an equality of partial values
(so one diverges iff the other does).
In particular, we can let `k = Cont.halt`, and then this asserts that `stepNormal c Cont.halt v`
evaluates to `Cfg.halt (Code.eval c v)`. -/
def Code.Ok (c : Code) :=
∀ k v, Turing.eval step (stepNormal c k v) =
Code.eval c v >>= fun v => Turing.eval step (Cfg.ret k v)
#align turing.to_partrec.code.ok Turing.ToPartrec.Code.Ok
theorem Code.Ok.zero {c} (h : Code.Ok c) {v} :
Turing.eval step (stepNormal c Cont.halt v) = Cfg.halt <$> Code.eval c v := by
rw [h, ← bind_pure_comp]; congr; funext v
exact Part.eq_some_iff.2 (mem_eval.2 ⟨ReflTransGen.single rfl, rfl⟩)
#align turing.to_partrec.code.ok.zero Turing.ToPartrec.Code.Ok.zero
theorem stepNormal.is_ret (c k v) : ∃ k' v', stepNormal c k v = Cfg.ret k' v' := by
induction c generalizing k v with
| cons _f fs IHf _IHfs => apply IHf
| comp f _g _IHf IHg => apply IHg
| case f g IHf IHg =>
rw [stepNormal]
simp only []
cases v.headI <;> [apply IHf; apply IHg]
| fix f IHf => apply IHf
| _ => exact ⟨_, _, rfl⟩
#align turing.to_partrec.step_normal.is_ret Turing.ToPartrec.stepNormal.is_ret
theorem cont_eval_fix {f k v} (fok : Code.Ok f) :
Turing.eval step (stepNormal f (Cont.fix f k) v) =
f.fix.eval v >>= fun v => Turing.eval step (Cfg.ret k v) := by
refine Part.ext fun x => ?_
simp only [Part.bind_eq_bind, Part.mem_bind_iff]
constructor
· suffices ∀ c, x ∈ eval step c → ∀ v c', c = Cfg.then c' (Cont.fix f k) →
Reaches step (stepNormal f Cont.halt v) c' →
∃ v₁ ∈ f.eval v, ∃ v₂ ∈ if List.headI v₁ = 0 then pure v₁.tail else f.fix.eval v₁.tail,
x ∈ eval step (Cfg.ret k v₂) by
intro h
obtain ⟨v₁, hv₁, v₂, hv₂, h₃⟩ :=
this _ h _ _ (stepNormal_then _ Cont.halt _ _) ReflTransGen.refl
refine ⟨v₂, PFun.mem_fix_iff.2 ?_, h₃⟩
simp only [Part.eq_some_iff.2 hv₁, Part.map_some]
split_ifs at hv₂ ⊢
· rw [Part.mem_some_iff.1 hv₂]
exact Or.inl (Part.mem_some _)
· exact Or.inr ⟨_, Part.mem_some _, hv₂⟩
refine fun c he => evalInduction he fun y h IH => ?_
rintro v (⟨v'⟩ | ⟨k', v'⟩) rfl hr <;> rw [Cfg.then] at h IH <;> simp only [] at h IH
· have := mem_eval.2 ⟨hr, rfl⟩
rw [fok, Part.bind_eq_bind, Part.mem_bind_iff] at this
obtain ⟨v'', h₁, h₂⟩ := this
rw [reaches_eval] at h₂
swap
· exact ReflTransGen.single rfl
cases Part.mem_unique h₂ (mem_eval.2 ⟨ReflTransGen.refl, rfl⟩)
refine ⟨v', h₁, ?_⟩
rw [stepRet] at h
revert h
by_cases he : v'.headI = 0 <;> simp only [exists_prop, if_pos, if_false, he] <;> intro h
· refine ⟨_, Part.mem_some _, ?_⟩
rw [reaches_eval]
· exact h
exact ReflTransGen.single rfl
· obtain ⟨k₀, v₀, e₀⟩ := stepNormal.is_ret f Cont.halt v'.tail
have e₁ := stepNormal_then f Cont.halt (Cont.fix f k) v'.tail
rw [e₀, Cont.then, Cfg.then] at e₁
simp only [] at e₁
obtain ⟨v₁, hv₁, v₂, hv₂, h₃⟩ :=
IH (stepRet (k₀.then (Cont.fix f k)) v₀) (by rw [stepRet, if_neg he, e₁]; rfl)
v'.tail _ stepRet_then (by apply ReflTransGen.single; rw [e₀]; rfl)
refine ⟨_, PFun.mem_fix_iff.2 ?_, h₃⟩
simp only [Part.eq_some_iff.2 hv₁, Part.map_some, Part.mem_some_iff]
split_ifs at hv₂ ⊢ <;> [exact Or.inl (congr_arg Sum.inl (Part.mem_some_iff.1 hv₂));
exact Or.inr ⟨_, rfl, hv₂⟩]
· exact IH _ rfl _ _ stepRet_then (ReflTransGen.tail hr rfl)
· rintro ⟨v', he, hr⟩
rw [reaches_eval] at hr
swap
· exact ReflTransGen.single rfl
refine PFun.fixInduction he fun v (he : v' ∈ f.fix.eval v) IH => ?_
rw [fok, Part.bind_eq_bind, Part.mem_bind_iff]
obtain he | ⟨v'', he₁', _⟩ := PFun.mem_fix_iff.1 he
· obtain ⟨v', he₁, he₂⟩ := (Part.mem_map_iff _).1 he
split_ifs at he₂ with h; cases he₂
refine ⟨_, he₁, ?_⟩
rw [reaches_eval]
swap
· exact ReflTransGen.single rfl
rwa [stepRet, if_pos h]
· obtain ⟨v₁, he₁, he₂⟩ := (Part.mem_map_iff _).1 he₁'
split_ifs at he₂ with h; cases he₂
clear he₁'
refine ⟨_, he₁, ?_⟩
rw [reaches_eval]
swap
· exact ReflTransGen.single rfl
rw [stepRet, if_neg h]
exact IH v₁.tail ((Part.mem_map_iff _).2 ⟨_, he₁, if_neg h⟩)
#align turing.to_partrec.cont_eval_fix Turing.ToPartrec.cont_eval_fix
theorem code_is_ok (c) : Code.Ok c := by
induction c with (intro k v; rw [stepNormal])
| cons f fs IHf IHfs =>
rw [Code.eval, IHf]
simp only [bind_assoc, Cont.eval, pure_bind]; congr; funext v
rw [reaches_eval]; swap
· exact ReflTransGen.single rfl
rw [stepRet, IHfs]; congr; funext v'
refine Eq.trans (b := eval step (stepRet (Cont.cons₂ v k) v')) ?_ (Eq.symm ?_) <;>
exact reaches_eval (ReflTransGen.single rfl)
| comp f g IHf IHg =>
rw [Code.eval, IHg]
simp only [bind_assoc, Cont.eval, pure_bind]; congr; funext v
rw [reaches_eval]; swap
· exact ReflTransGen.single rfl
rw [stepRet, IHf]
| case f g IHf IHg =>
simp only [Code.eval]
cases v.headI <;> simp only [Nat.rec_zero, Part.bind_eq_bind] <;> [apply IHf; apply IHg]
| fix f IHf => rw [cont_eval_fix IHf]
| _ => simp only [Code.eval, pure_bind]
#align turing.to_partrec.code_is_ok Turing.ToPartrec.code_is_ok
theorem stepNormal_eval (c v) : eval step (stepNormal c Cont.halt v) = Cfg.halt <$> c.eval v :=
(code_is_ok c).zero
#align turing.to_partrec.step_normal_eval Turing.ToPartrec.stepNormal_eval
theorem stepRet_eval {k v} : eval step (stepRet k v) = Cfg.halt <$> k.eval v := by
induction k generalizing v with
| halt =>
simp only [mem_eval, Cont.eval, map_pure]
exact Part.eq_some_iff.2 (mem_eval.2 ⟨ReflTransGen.refl, rfl⟩)
| cons₁ fs as k IH =>
rw [Cont.eval, stepRet, code_is_ok]
simp only [← bind_pure_comp, bind_assoc]; congr; funext v'
rw [reaches_eval]; swap
· exact ReflTransGen.single rfl
rw [stepRet, IH, bind_pure_comp]
| cons₂ ns k IH => rw [Cont.eval, stepRet]; exact IH
| comp f k IH =>
rw [Cont.eval, stepRet, code_is_ok]
simp only [← bind_pure_comp, bind_assoc]; congr; funext v'
rw [reaches_eval]; swap
· exact ReflTransGen.single rfl
rw [IH, bind_pure_comp]
| fix f k IH =>
rw [Cont.eval, stepRet]; simp only [bind_pure_comp]
split_ifs; · exact IH
simp only [← bind_pure_comp, bind_assoc, cont_eval_fix (code_is_ok _)]
congr; funext; rw [bind_pure_comp, ← IH]
exact reaches_eval (ReflTransGen.single rfl)
#align turing.to_partrec.step_ret_eval Turing.ToPartrec.stepRet_eval
end ToPartrec
/-!
## Simulating sequentialized partial recursive functions in TM2
At this point we have a sequential model of partial recursive functions: the `Cfg` type and
`step : Cfg → Option Cfg` function from the previous section. The key feature of this model is that
it does a finite amount of computation (in fact, an amount which is statically bounded by the size
of the program) between each step, and no individual step can diverge (unlike the compositional
semantics, where every sub-part of the computation is potentially divergent). So we can utilize the
same techniques as in the other TM simulations in `Computability.TuringMachine` to prove that
each step corresponds to a finite number of steps in a lower level model. (We don't prove it here,
but in anticipation of the complexity class P, the simulation is actually polynomial-time as well.)
The target model is `Turing.TM2`, which has a fixed finite set of stacks, a bit of local storage,
with programs selected from a potentially infinite (but finitely accessible) set of program
positions, or labels `Λ`, each of which executes a finite sequence of basic stack commands.
For this program we will need four stacks, each on an alphabet `Γ'` like so:
inductive Γ' | consₗ | cons | bit0 | bit1
We represent a number as a bit sequence, lists of numbers by putting `cons` after each element, and
lists of lists of natural numbers by putting `consₗ` after each list. For example:
0 ~> []
1 ~> [bit1]
6 ~> [bit0, bit1, bit1]
[1, 2] ~> [bit1, cons, bit0, bit1, cons]
[[], [1, 2]] ~> [consₗ, bit1, cons, bit0, bit1, cons, consₗ]
The four stacks are `main`, `rev`, `aux`, `stack`. In normal mode, `main` contains the input to the
current program (a `List ℕ`) and `stack` contains data (a `List (List ℕ)`) associated to the
current continuation, and in `ret` mode `main` contains the value that is being passed to the
continuation and `stack` contains the data for the continuation. The `rev` and `aux` stacks are
usually empty; `rev` is used to store reversed data when e.g. moving a value from one stack to
another, while `aux` is used as a temporary for a `main`/`stack` swap that happens during `cons₁`
evaluation.
The only local store we need is `Option Γ'`, which stores the result of the last pop
operation. (Most of our working data are natural numbers, which are too large to fit in the local
store.)
The continuations from the previous section are data-carrying, containing all the values that have
been computed and are awaiting other arguments. In order to have only a finite number of
continuations appear in the program so that they can be used in machine states, we separate the
data part (anything with type `List ℕ`) from the `Cont` type, producing a `Cont'` type that lacks
this information. The data is kept on the `stack` stack.
Because we want to have subroutines for e.g. moving an entire stack to another place, we use an
infinite inductive type `Λ'` so that we can execute a program and then return to do something else
without having to define too many different kinds of intermediate states. (We must nevertheless
prove that only finitely many labels are accessible.) The labels are:
* `move p k₁ k₂ q`: move elements from stack `k₁` to `k₂` while `p` holds of the value being moved.
The last element, that fails `p`, is placed in neither stack but left in the local store.
At the end of the operation, `k₂` will have the elements of `k₁` in reverse order. Then do `q`.
* `clear p k q`: delete elements from stack `k` until `p` is true. Like `move`, the last element is
left in the local storage. Then do `q`.
* `copy q`: Move all elements from `rev` to both `main` and `stack` (in reverse order),
then do `q`. That is, it takes `(a, b, c, d)` to `(b.reverse ++ a, [], c, b.reverse ++ d)`.
* `push k f q`: push `f s`, where `s` is the local store, to stack `k`, then do `q`. This is a
duplicate of the `push` instruction that is part of the TM2 model, but by having a subroutine
just for this purpose we can build up programs to execute inside a `goto` statement, where we
have the flexibility to be general recursive.
* `read (f : Option Γ' → Λ')`: go to state `f s` where `s` is the local store. Again this is only
here for convenience.
* `succ q`: perform a successor operation. Assuming `[n]` is encoded on `main` before,
`[n+1]` will be on main after. This implements successor for binary natural numbers.
* `pred q₁ q₂`: perform a predecessor operation or `case` statement. If `[]` is encoded on
`main` before, then we transition to `q₁` with `[]` on main; if `(0 :: v)` is on `main` before
then `v` will be on `main` after and we transition to `q₁`; and if `(n+1 :: v)` is on `main`
before then `n :: v` will be on `main` after and we transition to `q₂`.
* `ret k`: call continuation `k`. Each continuation has its own interpretation of the data in
`stack` and sets up the data for the next continuation.
* `ret (cons₁ fs k)`: `v :: KData` on `stack` and `ns` on `main`, and the next step expects
`v` on `main` and `ns :: KData` on `stack`. So we have to do a little dance here with six
reverse-moves using the `aux` stack to perform a three-point swap, each of which involves two
reversals.
* `ret (cons₂ k)`: `ns :: KData` is on `stack` and `v` is on `main`, and we have to put
`ns.headI :: v` on `main` and `KData` on `stack`. This is done using the `head` subroutine.
* `ret (fix f k)`: This stores no data, so we just check if `main` starts with `0` and
if so, remove it and call `k`, otherwise `clear` the first value and call `f`.
* `ret halt`: the stack is empty, and `main` has the output. Do nothing and halt.
In addition to these basic states, we define some additional subroutines that are used in the
above:
* `push'`, `peek'`, `pop'` are special versions of the builtins that use the local store to supply
inputs and outputs.
* `unrev`: special case `move false rev main` to move everything from `rev` back to `main`. Used as
a cleanup operation in several functions.
* `moveExcl p k₁ k₂ q`: same as `move` but pushes the last value read back onto the source stack.
* `move₂ p k₁ k₂ q`: double `move`, so that the result comes out in the right order at the target
stack. Implemented as `moveExcl p k rev; move false rev k₂`. Assumes that neither `k₁` nor `k₂`
is `rev` and `rev` is initially empty.
* `head k q`: get the first natural number from stack `k` and reverse-move it to `rev`, then clear
the rest of the list at `k` and then `unrev` to reverse-move the head value to `main`. This is
used with `k = main` to implement regular `head`, i.e. if `v` is on `main` before then `[v.headI]`
will be on `main` after; and also with `k = stack` for the `cons` operation, which has `v` on
`main` and `ns :: KData` on `stack`, and results in `KData` on `stack` and `ns.headI :: v` on
`main`.
* `trNormal` is the main entry point, defining states that perform a given `code` computation.
It mostly just dispatches to functions written above.
The main theorem of this section is `tr_eval`, which asserts that for each that for each code `c`,
the state `init c v` steps to `halt v'` in finitely many steps if and only if
`Code.eval c v = some v'`.
-/
set_option linter.uppercaseLean3 false
namespace PartrecToTM2
section
open ToPartrec
/-- The alphabet for the stacks in the program. `bit0` and `bit1` are used to represent `ℕ` values
as lists of binary digits, `cons` is used to separate `List ℕ` values, and `consₗ` is used to
separate `List (List ℕ)` values. See the section documentation. -/
inductive Γ'
| consₗ
| cons
| bit0
| bit1
deriving DecidableEq, Inhabited, Fintype
#align turing.partrec_to_TM2.Γ' Turing.PartrecToTM2.Γ'
#align turing.partrec_to_TM2.Γ'.Cons Turing.PartrecToTM2.Γ'.consₗ
#align turing.partrec_to_TM2.Γ'.cons Turing.PartrecToTM2.Γ'.cons
#align turing.partrec_to_TM2.Γ'.bit0 Turing.PartrecToTM2.Γ'.bit0
#align turing.partrec_to_TM2.Γ'.bit1 Turing.PartrecToTM2.Γ'.bit1
/-- The four stacks used by the program. `main` is used to store the input value in `trNormal`
mode and the output value in `Λ'.ret` mode, while `stack` is used to keep all the data for the
continuations. `rev` is used to store reversed lists when transferring values between stacks, and
`aux` is only used once in `cons₁`. See the section documentation. -/
inductive K'
| main
| rev
| aux
| stack
deriving DecidableEq, Inhabited
#align turing.partrec_to_TM2.K' Turing.PartrecToTM2.K'
#align turing.partrec_to_TM2.K'.main Turing.PartrecToTM2.K'.main
#align turing.partrec_to_TM2.K'.rev Turing.PartrecToTM2.K'.rev
#align turing.partrec_to_TM2.K'.aux Turing.PartrecToTM2.K'.aux
#align turing.partrec_to_TM2.K'.stack Turing.PartrecToTM2.K'.stack
open K'
/-- Continuations as in `ToPartrec.Cont` but with the data removed. This is done because we want
the set of all continuations in the program to be finite (so that it can ultimately be encoded into
the finite state machine of a Turing machine), but a continuation can handle a potentially infinite
number of data values during execution. -/
inductive Cont'
| halt
| cons₁ : Code → Cont' → Cont'
| cons₂ : Cont' → Cont'
| comp : Code → Cont' → Cont'
| fix : Code → Cont' → Cont'
deriving DecidableEq, Inhabited
#align turing.partrec_to_TM2.cont' Turing.PartrecToTM2.Cont'
#align turing.partrec_to_TM2.cont'.halt Turing.PartrecToTM2.Cont'.halt
#align turing.partrec_to_TM2.cont'.cons₁ Turing.PartrecToTM2.Cont'.cons₁
#align turing.partrec_to_TM2.cont'.cons₂ Turing.PartrecToTM2.Cont'.cons₂
#align turing.partrec_to_TM2.cont'.comp Turing.PartrecToTM2.Cont'.comp
#align turing.partrec_to_TM2.cont'.fix Turing.PartrecToTM2.Cont'.fix
/-- The set of program positions. We make extensive use of inductive types here to let us describe
"subroutines"; for example `clear p k q` is a program that clears stack `k`, then does `q` where
`q` is another label. In order to prevent this from resulting in an infinite number of distinct
accessible states, we are careful to be non-recursive (although loops are okay). See the section
documentation for a description of all the programs. -/
inductive Λ'
| move (p : Γ' → Bool) (k₁ k₂ : K') (q : Λ')
| clear (p : Γ' → Bool) (k : K') (q : Λ')
| copy (q : Λ')
| push (k : K') (s : Option Γ' → Option Γ') (q : Λ')
| read (f : Option Γ' → Λ')
| succ (q : Λ')
| pred (q₁ q₂ : Λ')
| ret (k : Cont')
#align turing.partrec_to_TM2.Λ' Turing.PartrecToTM2.Λ'
#align turing.partrec_to_TM2.Λ'.move Turing.PartrecToTM2.Λ'.move
#align turing.partrec_to_TM2.Λ'.clear Turing.PartrecToTM2.Λ'.clear
#align turing.partrec_to_TM2.Λ'.copy Turing.PartrecToTM2.Λ'.copy
#align turing.partrec_to_TM2.Λ'.push Turing.PartrecToTM2.Λ'.push
#align turing.partrec_to_TM2.Λ'.read Turing.PartrecToTM2.Λ'.read
#align turing.partrec_to_TM2.Λ'.succ Turing.PartrecToTM2.Λ'.succ
#align turing.partrec_to_TM2.Λ'.pred Turing.PartrecToTM2.Λ'.pred
#align turing.partrec_to_TM2.Λ'.ret Turing.PartrecToTM2.Λ'.ret
-- Porting note: `Turing.PartrecToTM2.Λ'.rec` is noncomputable in Lean4, so we make it computable.
compile_inductive% Code
compile_inductive% Cont'
compile_inductive% K'
compile_inductive% Λ'
instance Λ'.instInhabited : Inhabited Λ' :=
⟨Λ'.ret Cont'.halt⟩
#align turing.partrec_to_TM2.Λ'.inhabited Turing.PartrecToTM2.Λ'.instInhabited
instance Λ'.instDecidableEq : DecidableEq Λ' := fun a b => by
induction a generalizing b <;> cases b <;> first
| apply Decidable.isFalse; rintro ⟨⟨⟩⟩; done
| exact decidable_of_iff' _ (by simp [Function.funext_iff]; rfl)
#align turing.partrec_to_TM2.Λ'.decidable_eq Turing.PartrecToTM2.Λ'.instDecidableEq
/-- The type of TM2 statements used by this machine. -/
def Stmt' :=
TM2.Stmt (fun _ : K' => Γ') Λ' (Option Γ') deriving Inhabited
#align turing.partrec_to_TM2.stmt' Turing.PartrecToTM2.Stmt'
/-- The type of TM2 configurations used by this machine. -/
def Cfg' :=
TM2.Cfg (fun _ : K' => Γ') Λ' (Option Γ') deriving Inhabited
#align turing.partrec_to_TM2.cfg' Turing.PartrecToTM2.Cfg'
open TM2.Stmt
/-- A predicate that detects the end of a natural number, either `Γ'.cons` or `Γ'.consₗ` (or
implicitly the end of the list), for use in predicate-taking functions like `move` and `clear`. -/
@[simp]
def natEnd : Γ' → Bool
| Γ'.consₗ => true
| Γ'.cons => true
| _ => false
#align turing.partrec_to_TM2.nat_end Turing.PartrecToTM2.natEnd
/-- Pop a value from the stack and place the result in local store. -/
@[simp]
def pop' (k : K') : Stmt' → Stmt' :=
pop k fun _ v => v
#align turing.partrec_to_TM2.pop' Turing.PartrecToTM2.pop'
/-- Peek a value from the stack and place the result in local store. -/
@[simp]
def peek' (k : K') : Stmt' → Stmt' :=
peek k fun _ v => v
#align turing.partrec_to_TM2.peek' Turing.PartrecToTM2.peek'
/-- Push the value in the local store to the given stack. -/
@[simp]
def push' (k : K') : Stmt' → Stmt' :=
push k fun x => x.iget
#align turing.partrec_to_TM2.push' Turing.PartrecToTM2.push'
/-- Move everything from the `rev` stack to the `main` stack (reversed). -/