-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTangle.lean
More file actions
2011 lines (1931 loc) · 106 KB
/
Copy pathTangle.lean
File metadata and controls
2011 lines (1931 loc) · 106 KB
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
-- SPDX-License-Identifier: MPL-2.0
-- Tangle.lean — Mechanized type safety proofs for the TANGLE language core.
--
-- Models the core type system from docs/spec/FORMAL-SEMANTICS.md:
-- - Syntax: Expr inductive (26 constructors) with the de Bruijn Var and the
-- let binder Lett, plus Num, Str, Bool, Identity, BraidLit, Compose (.),
-- Tensor (|), Pipeline (>>), Close, Add, Eq, the echo constructors
-- EchoClose, Lower, Residue, EchoVal (structured loss), and the product
-- constructors Pair, Fst, Snd, EchoAdd, EchoEq
-- - Typing: HasType inductive relation (26 rules) covering T-Var, T-Let,
-- T-Num, T-Str, T-Bool, T-Identity, T-Braid, T-Compose-Word, T-Tensor-Word,
-- T-Pipeline, T-Close-Word, T-Add-Num, T-Eq-Word, T-Eq-Num, T-Eq-Str, the
-- echo rules T-Echo-Close, T-Lower, T-Residue, T-Echo-Val, the product
-- rules T-Pair, T-Fst, T-Snd, T-Echo-Add, and the echo-equality rules
-- T-Echo-Eq-Word, T-Echo-Eq-Num, T-Echo-Eq-Str. Contexts are
-- `Ctx = List Ty` (de Bruijn); `Γ[i]?` (`List.getElem?`) looks up Var.
-- - Substitution: capture-avoiding de Bruijn `shift`/`subst` over all 22
-- value/operation constructors (TG-1).
-- - Semantics: Small-step Step relation (55 rules incl. echo + product +
-- the two let rules letStep / letRed)
--
-- Theorems proven:
-- 1. Progress: well-typed closed terms are values or can step
-- 2. Preservation: stepping preserves types
-- 3. Determinism: if e ⟶ e₁ and e ⟶ e₂ then e₁ = e₂
-- 4. Type Safety: corollary combining progress and preservation
-- Plus the two metatheory lemmas WEAKENING (context insertion) and
-- SUBST_PRESERVES (the substitution lemma) underpinning let-reduction.
-- All cover the echo-types fragment, the product fragment, and let-binding.
--
-- Echo types (structured loss): `close : Word[n] → Word[0]` is TANGLE's
-- canonical lossy map. The echo type former `Ty.echo ρ τ` and the
-- constructors `echoClose`/`lower`/`residue` integrate echo-types
-- (hyperpolymath/echo-types: `Echo f y := Σ (x : A), f x ≡ y`) directly into
-- the type system: closing a braid through an echo retains the residue, so the
-- otherwise-irreversible `close` becomes reversible at the type level. The
-- product type `Ty.prod ρ σ` carries two further lossy operations, `echoAdd`
-- and `echoEq`: ordinary `add` discards which two numbers were summed, but
-- `echoAdd` keeps the summand pair as its residue (residue type `Num × Num`,
-- result `Num`); ordinary `eq` discards which two operands were compared, but
-- `echoEq` keeps the operand pair as its residue (residue type `ρ × ρ`, result
-- `Bool`), so distinct inputs that collapse to the same sum or boolean stay
-- distinguishable. See the §ECHO-TYPES section at the foot of the file for the
-- residue-recovery and non-injectivity theorems (the `close`, `echoAdd`, and
-- `echoEq` forms).
--
-- TG-1 LANDED: variables + the `lett` binder, capture-avoiding de Bruijn
-- `shift`/`subst`, and the full substitution metatheory. `weakening`
-- (context insertion) and `subst_preserves` (the substitution lemma) are
-- proved, and Progress / Preservation / Determinism / Type Safety + the
-- decidability layer (`infer`, `infer_sound`, `infer_complete`) all extend to
-- cover variables and let. One honest deviation: `subst_preserves` carries
-- its substitutee `s` typed in the COMBINED context `Γ₁ ++ Γ₂` (the true
-- inductive invariant — the closed-context `HasType Γ₂ s σ` form is false for a
-- non-empty prefix); the `letRed` consumer uses `Γ₁ := []` where the two forms
-- coincide. See the §METATHEORY comment block for the full rationale.
--
-- Developed for Lean 4. Tested against leanprover/lean4:v4.14.0.
--
-- Author: Jonathan D.A. Jewell, Claude
namespace Tangle
-- ═══════════════════════════════════════════════════════════════════════
-- SYNTAX
-- ═══════════════════════════════════════════════════════════════════════
/-- A braid generator σᵢ^{±1}: strand index i with exponent +1 or -1.
Mirrors `generator` in compiler/lib/ast.ml. -/
structure Generator where
idx : Nat
exp : Int
deriving DecidableEq, Repr
/-- Types in the core TANGLE language.
Word[n] represents braid words on n strands (§2.1 of the spec). -/
inductive Ty where
| num : Ty -- Num: integers and floats
| str : Ty -- Str: strings
| bool : Ty -- Bool: booleans
| word : Nat → Ty -- Word[n]: braid word on n strands
| echo : Ty → Ty → Ty -- Echo[ρ, τ]: structured-loss type — a τ-result
-- carrying a ρ-typed residue. The simply-typed
-- shadow of echo-types' `Echo f y := Σ (x : A), f x ≡ y`
-- (hyperpolymath/echo-types, Echo.agda): ρ is the
-- residue (domain witness x : A), τ is the result
-- (codomain point y). See §ECHO-TYPES below.
| prod : Ty → Ty → Ty -- product (pair) type ρ × σ; residue carrier for lossy binary ops
| epi : Nat → Ty → Ty → Ty
-- Epi[κ, ρ, τ]: at STANDPOINT κ, evidence of type ρ
-- purporting to support a claim of type τ. The
-- simply-typed shadow of epistemic-types'
-- `Epi K κ A` (EpistemicTypes/Warrant.agda), whose
-- record carries `warrant` + `evidence` and — the
-- whole point — NO field of type A.
--
-- κ is a standpoint index: an agent, evidence
-- state, accessibility context or warrant regime.
-- Indexed by Nat, mirroring `word : Nat → Ty`.
--
-- NON-FACTIVE BY CONSTRUCTION: τ appears in the
-- type but there is NO elimination rule producing
-- τ. Holding `Epi[κ,ρ,τ]` does not give you τ —
-- that is the difference between knowing and
-- having a warrant. Upstream models the factive
-- case as a SEPARATE record (`FactiveModality`
-- with `reflect`), never as a modality with a
-- missing proof; this mirrors that choice.
deriving DecidableEq, Repr
/-- Core expression AST. Mirrors the OCaml AST in compiler/lib/ast.ml.
Uses de Bruijn indices (not needed for closed terms but included
for completeness of the typing judgment). -/
inductive Expr where
| var : Nat → Expr -- de Bruijn variable
| lett : Expr → Expr → Expr -- let _ = e₁ in e₂ (e₂ binds var 0)
| num : Int → Expr -- integer literal
| str : String → Expr -- string literal
| boolLit : Bool → Expr -- boolean literal
| identity : Expr -- identity element (Word[0])
| braidLit : List Generator → Expr -- braid literal [σ₁, σ₂⁻¹, ...]
| compose : Expr → Expr → Expr -- vertical composition (.)
| tensor : Expr → Expr → Expr -- horizontal tensor (|)
| pipeline : Expr → Expr → Expr -- pipeline (>>), sugar for (.)
| close : Expr → Expr -- closure
| add : Expr → Expr → Expr -- numeric addition
| eq : Expr → Expr → Expr -- structural equality
-- Echo types (structured loss). `close` is TANGLE's canonical lossy map
-- (Word[n] ↠ Word[0]); these constructors give it a residue-retaining
-- variant and the two projections, mirroring echo-types' fibre/residue API.
-- A formed echo is the value `echoVal residue result`; `echoClose` is the
-- redex that reduces into one, and `lower`/`residue` are its two projections.
| echoClose : Expr → Expr -- echo-preserving closure (redex → echoVal)
| lower : Expr → Expr -- project an echo to its result (forget residue)
| residue : Expr → Expr -- project an echo to its residue (recover witness)
| echoVal : Expr → Expr → Expr -- formed echo value: (residue, result)
| pair : Expr → Expr → Expr -- product introduction
| fst : Expr → Expr -- first projection
| snd : Expr → Expr -- second projection
-- Epistemic (warranted claim). `warrant κ c ev` is the redex; it reduces to
-- the formed value `epiVal κ c ev`. The claim `c` is RETAINED in the value
-- (so typing stays unique) but is unreachable: `evidence` is the only
-- elimination, and it yields the token, never the claim.
| warrant : Nat → Expr → Expr → Expr -- warrant κ claim evidence (redex)
| epiVal : Nat → Expr → Expr → Expr -- formed warrant: standpoint, claim, token
| evidence : Expr → Expr -- project the evidence token (ONLY elimination)
| echoAdd : Expr → Expr → Expr -- echo-preserving addition (residue = pair of summands)
| echoEq : Expr → Expr → Expr -- echo-preserving equality (residue = operand pair)
deriving DecidableEq, Repr
/-- Value predicate: fully reduced expressions. -/
inductive IsValue : Expr → Prop where
| num : ∀ n, IsValue (.num n)
| str : ∀ s, IsValue (.str s)
| boolLit : ∀ b, IsValue (.boolLit b)
| identity : IsValue .identity
| braidLit : ∀ gs, IsValue (.braidLit gs)
| echoVal : ∀ {r v}, IsValue r → IsValue v → IsValue (.echoVal r v) -- a formed echo value (residue r, result v)
| pair : ∀ {a b}, IsValue a → IsValue b → IsValue (.pair a b)
| epiVal : ∀ {κ c ev}, IsValue c → IsValue ev → IsValue (.epiVal κ c ev)
-- ═══════════════════════════════════════════════════════════════════════
-- WIDTH
-- ═══════════════════════════════════════════════════════════════════════
/-- Width of a generator list: max(index + 1) across all generators.
Corresponds to the width function in §2.5 of the spec. -/
def generatorWidth (gs : List Generator) : Nat :=
gs.foldl (fun acc g => max acc (g.idx + 1)) 0
/-- Shift all generator indices by n (for tensor product).
shift(σᵢ, k) = σ_{i+k} per §4.6. -/
def shiftGenerators (gs : List Generator) (n : Nat) : List Generator :=
gs.map fun g => { g with idx := g.idx + n }
-- ═══════════════════════════════════════════════════════════════════════
-- BRAID-GROUP EQUIVALENCE (TG-7)
-- ═══════════════════════════════════════════════════════════════════════
--
-- Owner ruling 2026-07-29 (tangle#50): `==` on braids decides braid-GROUP
-- equivalence, NOT list equality. Syntactic equality contradicts the
-- language's own thesis — programs are topological objects and equivalence is
-- isotopy — so `==` must not be the one place that quietly reverts to
-- comparing representations.
--
-- This is a faithful port of `compiler/lib/braid_equiv.ml` (Dehornoy 1997,
-- "A fast method for comparing braids"). A σᵢ-handle is a factor
-- σᵢ^e · w₀ · σ_{i+1}^d · w₁ · ⋯ · σ_{i+1}^d · w_m · σᵢ^{-e}
-- whose interior uses only σⱼ with j ≥ i+2 apart from same-sign σ_{i+1}. It
-- reduces to
-- w₀ · (σ_{i+1}^{-e} σᵢ^d σ_{i+1}^e) · w₁ · ⋯ · w_m
-- and a handle-free, freely-reduced word is empty iff the braid is trivial, so
-- equiv u v ⇔ reduce (u · v⁻¹) = ε.
--
-- ── TRUSTED, NOT PROVEN ────────────────────────────────────────────────
-- These are DEFINITIONS, not axioms — nothing here is postulated, and the
-- metatheory below (Progress / Preservation / Determinism) goes through for
-- `braidEquiv` exactly as it did for list equality, because all three need
-- only that it is a TOTAL FUNCTION into `Bool`. Determinism in particular is
-- unaffected: a function applied to fixed arguments yields a fixed result.
--
-- What is NOT established here is that `braidEquiv` DECIDES braid-group
-- equality. That is the mechanised Garside/Dehornoy correctness proof, which
-- is research-grade and explicitly out of scope (tangle#51). Until it exists,
-- `braidEquiv` is trusted code that the `Step` relation is proven *relative
-- to*. The sorry/axiom gate passing does NOT mean this claim is proven; see
-- PROOF-NARRATIVE.md §TG-7.
--
-- Termination is by an explicit FUEL parameter rather than a well-founded
-- measure, mirroring the OCaml `max_steps` safety bound. Dehornoy reduction
-- does terminate, but proving that is precisely the research-grade obligation
-- above; fuel keeps these definitions total and computable without smuggling
-- in an unproven termination claim.
/-- A braid word as unit letters: index ≥ 1 and sign ±1.
Mirrors `type letter` in braid_equiv.ml. -/
structure Letter where
idx : Nat
sgn : Int
deriving DecidableEq, Repr
/-- Expand generators with arbitrary nonzero exponents into unit letters. -/
def unitsOf (gs : List Generator) : List Letter :=
gs.flatMap fun g =>
List.replicate g.exp.natAbs { idx := g.idx, sgn := if g.exp ≥ 0 then 1 else -1 }
/-- Inverse braid word: reverse order, negate every sign. (ab)⁻¹ = b⁻¹a⁻¹. -/
def inverseWord (w : List Letter) : List Letter :=
(w.map fun l => { l with sgn := -l.sgn }).reverse
/-- Free reduction: cancel adjacent σ·σ⁻¹. -/
def freeReduce (w : List Letter) : List Letter :=
w.foldr (fun x acc =>
match acc with
| y :: rest => if x.idx = y.idx && x.sgn = -y.sgn then rest else x :: acc
| [] => [x]) []
/-- Does the letter at the head open a handle over `rest`? Returns the
interior and the tail after the closing letter, or `none`.
Mirrors `handle_at` / the `scan` loop in braid_equiv.ml. -/
def scanHandle (i : Nat) (e : Int) :
List Letter → Option Int → List Letter → Option (List Letter × List Letter)
| [], _, _ => none -- no close → not a handle
| l :: ls, dOpt, acc =>
if l.idx = i then
if l.sgn = -e then some (acc.reverse, ls) -- closes the handle
else none -- same-sign σᵢ → blocked
else if l.idx < i then none -- σ_{<i} inside → blocked
else if l.idx = i + 1 then
match dOpt with
| none => scanHandle i e ls (some l.sgn) (l :: acc)
| some d => if d = l.sgn then scanHandle i e ls dOpt (l :: acc)
else none -- mixed σ_{i+1} signs
else scanHandle i e ls dOpt (l :: acc) -- j ≥ i+2 → interior, ok
/-- Rewrite a handle's interior: σ_{i+1}^d ↦ σ_{i+1}^{-e} σᵢ^d σ_{i+1}^e. -/
def rewriteInterior (i : Nat) (e : Int) (interior : List Letter) : List Letter :=
interior.flatMap fun l =>
if l.idx = i + 1 then
[ { idx := i + 1, sgn := -e }, { idx := i, sgn := l.sgn }, { idx := i + 1, sgn := e } ]
else [l]
/-- Reduce the leftmost handle; `none` if the word is handle-free. -/
def reduceOne : List Letter → Option (List Letter)
| [] => none
| l :: ls =>
match scanHandle l.idx l.sgn ls none [] with
| some (interior, tail) => some (rewriteInterior l.idx l.sgn interior ++ tail)
| none =>
match reduceOne ls with
| some ls' => some (l :: ls')
| none => none
/-- Default fuel; mirrors `default_max_steps` in braid_equiv.ml. -/
def defaultFuel : Nat := 1000000
/-- Reduce to a handle-free, freely-reduced word (fuel-bounded). -/
def reduceFuel : Nat → List Letter → List Letter
| 0, w => w -- safety net
| fuel + 1, w =>
match reduceOne w with
| none => w
| some w' => reduceFuel fuel (freeReduce w')
/-- Reduce with the default fuel. -/
def reduceWord (w : List Letter) : List Letter :=
reduceFuel defaultFuel (freeReduce w)
/-- A unit word is trivial iff it reduces to the empty word. -/
def isTrivialWord (w : List Letter) : Bool := reduceWord w == []
/-- A generator list denotes the trivial (identity) braid. -/
def isTrivialBraid (gs : List Generator) : Bool := isTrivialWord (unitsOf gs)
/-- **Braid-group equivalence**: `u ≡ v` iff `u · v⁻¹` is trivial.
This is what `==` on braids means (tangle#50). -/
def braidEquiv (u v : List Generator) : Bool :=
isTrivialWord (unitsOf u ++ inverseWord (unitsOf v))
/-- Writhe (exponent sum): invariant under the braid relations. A necessary
condition for equivalence, exposed for testing. -/
def writhe (gs : List Generator) : Int :=
gs.foldl (fun a g => a + g.exp) 0
-- ═══════════════════════════════════════════════════════════════════════
-- DE BRUIJN SUBSTITUTION MACHINERY
-- ═══════════════════════════════════════════════════════════════════════
--
-- Standard POPLmark substitution operators on de Bruijn terms. `shift d c e`
-- lifts every free variable of `e` whose index is ≥ the cutoff `c` by `d`
-- (used to move a term under `d` extra binders). `subst j s e` replaces the
-- variable at index `j` by `s`, decrements every free variable > `j` (the
-- binder being eliminated disappears), and shifts `s` by one under each binder
-- it crosses. Both recurse uniformly through every `Expr` constructor.
/-- de Bruijn shift: lift free variables ≥ cutoff `c` by `d`. -/
def shift (d : Nat) (c : Nat) : Expr → Expr
| .var k => if k < c then .var k else .var (k + d)
| .lett e₁ e₂ => .lett (shift d c e₁) (shift d (c+1) e₂)
| .num n => .num n
| .str s => .str s
| .boolLit b => .boolLit b
| .identity => .identity
| .braidLit gs => .braidLit gs
| .compose a b => .compose (shift d c a) (shift d c b)
| .tensor a b => .tensor (shift d c a) (shift d c b)
| .pipeline a b => .pipeline (shift d c a) (shift d c b)
| .close a => .close (shift d c a)
| .add a b => .add (shift d c a) (shift d c b)
| .eq a b => .eq (shift d c a) (shift d c b)
| .echoClose a => .echoClose (shift d c a)
| .lower a => .lower (shift d c a)
| .residue a => .residue (shift d c a)
| .echoVal a b => .echoVal (shift d c a) (shift d c b)
| .pair a b => .pair (shift d c a) (shift d c b)
| .warrant κ cl ev => .warrant κ (shift d c cl) (shift d c ev)
| .epiVal κ cl ev => .epiVal κ (shift d c cl) (shift d c ev)
| .evidence e => .evidence (shift d c e)
| .fst a => .fst (shift d c a)
| .snd a => .snd (shift d c a)
| .echoAdd a b => .echoAdd (shift d c a) (shift d c b)
| .echoEq a b => .echoEq (shift d c a) (shift d c b)
/-- de Bruijn substitution: replace variable `j` by `s`, decrement vars > `j`,
shift `s` under binders. -/
def subst (j : Nat) (s : Expr) : Expr → Expr
| .var k => if k < j then .var k else if k = j then s else .var (k - 1)
| .lett e₁ e₂ => .lett (subst j s e₁) (subst (j+1) (shift 1 0 s) e₂)
| .num n => .num n
| .str t => .str t
| .boolLit b => .boolLit b
| .identity => .identity
| .braidLit gs => .braidLit gs
| .compose a b => .compose (subst j s a) (subst j s b)
| .tensor a b => .tensor (subst j s a) (subst j s b)
| .pipeline a b => .pipeline (subst j s a) (subst j s b)
| .close a => .close (subst j s a)
| .add a b => .add (subst j s a) (subst j s b)
| .eq a b => .eq (subst j s a) (subst j s b)
| .echoClose a => .echoClose (subst j s a)
| .lower a => .lower (subst j s a)
| .residue a => .residue (subst j s a)
| .echoVal a b => .echoVal (subst j s a) (subst j s b)
| .pair a b => .pair (subst j s a) (subst j s b)
| .warrant κ cl ev => .warrant κ (subst j s cl) (subst j s ev)
| .epiVal κ cl ev => .epiVal κ (subst j s cl) (subst j s ev)
| .evidence e => .evidence (subst j s e)
| .fst a => .fst (subst j s a)
| .snd a => .snd (subst j s a)
| .echoAdd a b => .echoAdd (subst j s a) (subst j s b)
| .echoEq a b => .echoEq (subst j s a) (subst j s b)
-- ═══════════════════════════════════════════════════════════════════════
-- TYPING JUDGMENT
-- ═══════════════════════════════════════════════════════════════════════
/-- Typing context (de Bruijn indexed). -/
abbrev Ctx := List Ty
/-- Typing judgment: Γ ⊢ e : τ.
Encodes the rules from §3 of FORMAL-SEMANTICS.md. -/
inductive HasType : Ctx → Expr → Ty → Prop where
| tNum (Γ : Ctx) (n : Int) : -- [T-Num]
HasType Γ (.num n) .num
| tStr (Γ : Ctx) (s : String) : -- [T-Str]
HasType Γ (.str s) .str
| tBool (Γ : Ctx) (b : Bool) : -- [T-Bool]
HasType Γ (.boolLit b) .bool
| tIdentity (Γ : Ctx) : -- [T-Identity]
HasType Γ .identity (.word 0)
| tBraid (Γ : Ctx) (gs : List Generator) : -- [T-Braid]
HasType Γ (.braidLit gs) (.word (generatorWidth gs))
| tComposeWord (Γ : Ctx) (e₁ e₂ : Expr) (n m : Nat) : -- [T-Compose-Word]
HasType Γ e₁ (.word n) →
HasType Γ e₂ (.word m) →
HasType Γ (.compose e₁ e₂) (.word (max n m))
| tTensorWord (Γ : Ctx) (e₁ e₂ : Expr) (n m : Nat) : -- [T-Tensor-Word]
HasType Γ e₁ (.word n) →
HasType Γ e₂ (.word m) →
HasType Γ (.tensor e₁ e₂) (.word (n + m))
| tPipeline (Γ : Ctx) (e₁ e₂ : Expr) (τ : Ty) : -- [T-Pipeline]
HasType Γ (.compose e₁ e₂) τ →
HasType Γ (.pipeline e₁ e₂) τ
| tCloseWord (Γ : Ctx) (e : Expr) (n : Nat) : -- [T-Close-Word]
HasType Γ e (.word n) →
HasType Γ (.close e) (.word 0)
| tAddNum (Γ : Ctx) (e₁ e₂ : Expr) : -- [T-Add-Num]
HasType Γ e₁ .num →
HasType Γ e₂ .num →
HasType Γ (.add e₁ e₂) .num
-- [T-Eq-Word]. The two operands need NOT have the same width (#92).
--
-- Braid groups embed: Bₙ ↪ Bₙ₊₁ by adding a strand nothing touches. A word
-- on n strands IS a word on max(n,m) strands, so the comparison is asked in
-- the larger group — which is exactly what `braidEquiv` already computes: it
-- takes two generator lists and has no width parameter at all.
--
-- Requiring n = n was inconsistent with the rest of the language:
-- * `tComposeWord` (below) already WIDENS to max n m, so a program could
-- compose two braids it was then forbidden to compare;
-- * `~` (isotopy) accepted differing widths in OCaml and, since TG-7,
-- evaluates through the SAME `braidEquiv` — identical operands and
-- identical answer, one rejected by the typechecker and one not;
-- * `eqIdBraid`/`eqBraidId` below decide "is this braid trivial?" against
-- `identity : word 0`, which under the old rule could only ever type
-- when the braid was empty. The step relation had rules for a question
-- the typing rule forbade asking.
| tEqWord (Γ : Ctx) (e₁ e₂ : Expr) (n m : Nat) : -- [T-Eq-Word]
HasType Γ e₁ (.word n) →
HasType Γ e₂ (.word m) →
HasType Γ (.eq e₁ e₂) .bool
| tEqNum (Γ : Ctx) (e₁ e₂ : Expr) : -- [T-Eq-Num]
HasType Γ e₁ .num →
HasType Γ e₂ .num →
HasType Γ (.eq e₁ e₂) .bool
| tEqStr (Γ : Ctx) (e₁ e₂ : Expr) : -- [T-Eq-Str]
HasType Γ e₁ .str →
HasType Γ e₂ .str →
HasType Γ (.eq e₁ e₂) .bool
-- ── Epistemic (warranted claim) ─────────────────────────────────────
-- Note what is ABSENT: there is no rule with conclusion `HasType Γ _ τ`
-- from a premise `HasType Γ e (.epi κ ρ τ)`. A warrant does not discharge
-- its claim. Upstream states the same thing by giving `Warrant` only an
-- `Evidence` field and putting extraction in a separate `SoundWarrant`.
| tWarrant (Γ : Ctx) (κ : Nat) (c ev : Expr) (ρ τ : Ty) : -- [T-Warrant]
HasType Γ c τ → -- what is claimed
HasType Γ ev ρ → -- the evidence token
HasType Γ (.warrant κ c ev) (.epi κ ρ τ)
| tEpiVal (Γ : Ctx) (κ : Nat) (c ev : Expr) (ρ τ : Ty) : -- [T-Epi-Val]
HasType Γ c τ →
HasType Γ ev ρ →
HasType Γ (.epiVal κ c ev) (.epi κ ρ τ)
| tEvidence (Γ : Ctx) (e : Expr) (κ : Nat) (ρ τ : Ty) : -- [T-Evidence]
HasType Γ e (.epi κ ρ τ) →
HasType Γ (.evidence e) ρ -- ρ, NEVER τ
| tEchoClose (Γ : Ctx) (e : Expr) (n : Nat) : -- [T-Echo-Close]
HasType Γ e (.word n) → -- echo-intro for `close`:
HasType Γ (.echoClose e) (.echo (.word n) (.word 0)) -- residue Word[n], result Word[0]
| tLower (Γ : Ctx) (e : Expr) (ρ τ : Ty) : -- [T-Lower] (project to result)
HasType Γ e (.echo ρ τ) →
HasType Γ (.lower e) τ
| tResidue (Γ : Ctx) (e : Expr) (ρ τ : Ty) : -- [T-Residue] (recover witness)
HasType Γ e (.echo ρ τ) →
HasType Γ (.residue e) ρ
| tEchoVal (Γ : Ctx) (r v : Expr) (ρ τ : Ty) : -- [T-Echo-Val]
HasType Γ r ρ →
HasType Γ v τ →
HasType Γ (.echoVal r v) (.echo ρ τ)
| tPair (Γ : Ctx) (a b : Expr) (α β : Ty) : -- [T-Pair]
HasType Γ a α → HasType Γ b β → HasType Γ (.pair a b) (.prod α β)
| tFst (Γ : Ctx) (e : Expr) (α β : Ty) : -- [T-Fst]
HasType Γ e (.prod α β) → HasType Γ (.fst e) α
| tSnd (Γ : Ctx) (e : Expr) (α β : Ty) : -- [T-Snd]
HasType Γ e (.prod α β) → HasType Γ (.snd e) β
| tEchoAdd (Γ : Ctx) (e₁ e₂ : Expr) : -- [T-Echo-Add]
HasType Γ e₁ .num → HasType Γ e₂ .num →
HasType Γ (.echoAdd e₁ e₂) (.echo (.prod .num .num) .num)
| tEchoEqWord (Γ : Ctx) (e₁ e₂ : Expr) (n : Nat) : -- [T-Echo-Eq-Word]
HasType Γ e₁ (.word n) → HasType Γ e₂ (.word n) →
HasType Γ (.echoEq e₁ e₂) (.echo (.prod (.word n) (.word n)) .bool)
| tEchoEqNum (Γ : Ctx) (e₁ e₂ : Expr) : -- [T-Echo-Eq-Num]
HasType Γ e₁ .num → HasType Γ e₂ .num →
HasType Γ (.echoEq e₁ e₂) (.echo (.prod .num .num) .bool)
| tEchoEqStr (Γ : Ctx) (e₁ e₂ : Expr) : -- [T-Echo-Eq-Str]
HasType Γ e₁ .str → HasType Γ e₂ .str →
HasType Γ (.echoEq e₁ e₂) (.echo (.prod .str .str) .bool)
| tVar (Γ : Ctx) (i : Nat) (τ : Ty) : -- [T-Var]
Γ[i]? = some τ → HasType Γ (.var i) τ
| tLet (Γ : Ctx) (e₁ e₂ : Expr) (σ τ : Ty) : -- [T-Let]
HasType Γ e₁ σ → HasType (σ :: Γ) e₂ τ →
HasType Γ (.lett e₁ e₂) τ
-- ═══════════════════════════════════════════════════════════════════════
-- SMALL-STEP SEMANTICS
-- ═══════════════════════════════════════════════════════════════════════
/-- Small-step reduction relation e ⟶ e'.
Encodes the evaluation rules from §4 of FORMAL-SEMANTICS.md. -/
inductive Step : Expr → Expr → Prop where
-- Compose: congruence
| composeLeft : Step e₁ e₁' → Step (.compose e₁ e₂) (.compose e₁' e₂)
| composeRight : IsValue e₁ → Step e₂ e₂' → Step (.compose e₁ e₂) (.compose e₁ e₂')
-- Compose: computation (E-Compose-Word, etc.)
| composeWords : Step (.compose (.braidLit gs₁) (.braidLit gs₂)) (.braidLit (gs₁ ++ gs₂))
| composeIdL : Step (.compose .identity (.braidLit gs)) (.braidLit gs)
| composeIdR : Step (.compose (.braidLit gs) .identity) (.braidLit gs)
| composeIdId : Step (.compose .identity .identity) .identity
-- Tensor: congruence
| tensorLeft : Step e₁ e₁' → Step (.tensor e₁ e₂) (.tensor e₁' e₂)
| tensorRight : IsValue e₁ → Step e₂ e₂' → Step (.tensor e₁ e₂) (.tensor e₁ e₂')
-- Tensor: computation (E-Tensor-Word)
| tensorWords : Step (.tensor (.braidLit gs₁) (.braidLit gs₂))
(.braidLit (gs₁ ++ shiftGenerators gs₂ (generatorWidth gs₁)))
| tensorIdL : Step (.tensor .identity (.braidLit gs)) (.braidLit gs)
| tensorIdR : Step (.tensor (.braidLit gs) .identity) (.braidLit gs)
| tensorIdId : Step (.tensor .identity .identity) .identity
-- Pipeline desugaring (E-Pipeline)
| pipeline : Step (.pipeline e₁ e₂) (.compose e₁ e₂)
-- Close (E-Close-Word)
| closeStep : Step e e' → Step (.close e) (.close e')
| closeWord : Step (.close (.braidLit gs)) .identity
| closeId : Step (.close .identity) .identity
-- Add (E-Add-Num)
| addLeft : Step e₁ e₁' → Step (.add e₁ e₂) (.add e₁' e₂)
| addRight : IsValue e₁ → Step e₂ e₂' → Step (.add e₁ e₂) (.add e₁ e₂')
| addNums : Step (.add (.num n₁) (.num n₂)) (.num (n₁ + n₂))
-- Eq (E-Eq-Word, E-Eq-Num, E-Eq-Str)
| eqLeft : Step e₁ e₁' → Step (.eq e₁ e₂) (.eq e₁' e₂)
| eqRight : IsValue e₁ → Step e₂ e₂' → Step (.eq e₁ e₂) (.eq e₁ e₂')
| eqNums : Step (.eq (.num n₁) (.num n₂)) (.boolLit (n₁ == n₂))
| eqStrs : Step (.eq (.str s₁) (.str s₂)) (.boolLit (s₁ == s₂))
| eqBraids : Step (.eq (.braidLit gs₁) (.braidLit gs₂)) (.boolLit (braidEquiv gs₁ gs₂))
| eqIdId : Step (.eq .identity .identity) (.boolLit true)
| eqIdBraid : Step (.eq .identity (.braidLit gs)) (.boolLit (isTrivialBraid gs))
| eqBraidId : Step (.eq (.braidLit gs) .identity) (.boolLit (isTrivialBraid gs))
-- Epistemic: `warrant` is a redex reducing into a formed `epiVal`; `evidence`
-- is the sole projection off it, and yields the TOKEN. There is deliberately
-- no projection yielding the claim.
| warrantClaim : Step c c' → Step (.warrant κ c ev) (.warrant κ c' ev)
| warrantEv : IsValue c → Step ev ev' → Step (.warrant κ c ev) (.warrant κ c ev')
| warrantForm : IsValue c → IsValue ev → Step (.warrant κ c ev) (.epiVal κ c ev)
| epiValClaim : Step c c' → Step (.epiVal κ c ev) (.epiVal κ c' ev)
| epiValEv : IsValue c → Step ev ev' → Step (.epiVal κ c ev) (.epiVal κ c ev')
| evidenceStep : Step e e' → Step (.evidence e) (.evidence e')
| evidenceVal : IsValue c → IsValue ev → Step (.evidence (.epiVal κ c ev)) ev
-- Echo (structured loss): `echoClose` is a redex that reduces into a formed
-- echo value `echoVal residue result`; `lower`/`residue` are the two generic
-- projections off a formed echo value. `lower` yields the result component
-- (the codomain point identity : Word[0]); `residue` recovers the witness
-- braid retained in the residue component — the fibre element echo-types keeps.
| echoCloseStep : Step e e' → Step (.echoClose e) (.echoClose e')
| echoCloseWord : Step (.echoClose (.braidLit gs)) (.echoVal (.braidLit gs) .identity)
| echoCloseId : Step (.echoClose .identity) (.echoVal .identity .identity)
| echoValLeft : Step r r' → Step (.echoVal r v) (.echoVal r' v)
| echoValRight : IsValue r → Step v v' → Step (.echoVal r v) (.echoVal r v')
| lowerStep : Step e e' → Step (.lower e) (.lower e')
| lowerVal : IsValue r → IsValue v → Step (.lower (.echoVal r v)) v
| residueStep : Step e e' → Step (.residue e) (.residue e')
| residueVal : IsValue r → IsValue v → Step (.residue (.echoVal r v)) r
-- Product: congruence + projections
| pairLeft : Step a a' → Step (.pair a b) (.pair a' b)
| pairRight : IsValue a → Step b b' → Step (.pair a b) (.pair a b')
| fstStep : Step e e' → Step (.fst e) (.fst e')
| fstPair : IsValue a → IsValue b → Step (.fst (.pair a b)) a
| sndStep : Step e e' → Step (.snd e) (.snd e')
| sndPair : IsValue a → IsValue b → Step (.snd (.pair a b)) b
-- Echo-preserving addition: residue retains the summand pair; result is the sum.
| echoAddLeft : Step e₁ e₁' → Step (.echoAdd e₁ e₂) (.echoAdd e₁' e₂)
| echoAddRight : IsValue e₁ → Step e₂ e₂' → Step (.echoAdd e₁ e₂) (.echoAdd e₁ e₂')
| echoAddNums : Step (.echoAdd (.num n₁) (.num n₂))
(.echoVal (.pair (.num n₁) (.num n₂)) (.num (n₁ + n₂)))
-- Echo-preserving equality: residue retains the operand pair; result is the
-- boolean. Mirrors the 8 `eq` rules; each computation produces
-- `echoVal (pair <operands>) (boolLit <same bool as the matching eq rule>)`.
| echoEqLeft : Step e₁ e₁' → Step (.echoEq e₁ e₂) (.echoEq e₁' e₂)
| echoEqRight : IsValue e₁ → Step e₂ e₂' → Step (.echoEq e₁ e₂) (.echoEq e₁ e₂')
| echoEqNums : Step (.echoEq (.num n₁) (.num n₂))
(.echoVal (.pair (.num n₁) (.num n₂)) (.boolLit (n₁ == n₂)))
| echoEqStrs : Step (.echoEq (.str s₁) (.str s₂))
(.echoVal (.pair (.str s₁) (.str s₂)) (.boolLit (s₁ == s₂)))
| echoEqBraids : Step (.echoEq (.braidLit gs₁) (.braidLit gs₂))
(.echoVal (.pair (.braidLit gs₁) (.braidLit gs₂)) (.boolLit (braidEquiv gs₁ gs₂)))
| echoEqIdId : Step (.echoEq .identity .identity)
(.echoVal (.pair .identity .identity) (.boolLit true))
| echoEqIdBraid : Step (.echoEq .identity (.braidLit gs))
(.echoVal (.pair .identity (.braidLit gs)) (.boolLit (isTrivialBraid gs)))
| echoEqBraidId : Step (.echoEq (.braidLit gs) .identity)
(.echoVal (.pair (.braidLit gs) .identity) (.boolLit (isTrivialBraid gs)))
-- Let-binding: congruence on the bound expression, then β-reduction once it
-- is a value (the bound value is substituted into the body's variable 0).
| letStep : Step e₁ e₁' → Step (.lett e₁ e₂) (.lett e₁' e₂)
| letRed : IsValue v → Step (.lett v e₂) (subst 0 v e₂)
-- ═══════════════════════════════════════════════════════════════════════
-- LEMMAS
-- ═══════════════════════════════════════════════════════════════════════
/-- Values are in normal form. Recursive on the value structure because a
formed echo value `echoVal r v` is a value exactly when both components are. -/
theorem value_no_step {e e' : Expr} (hv : IsValue e) (hs : Step e e') : False := by
induction hv generalizing e' with
| echoVal _ _ ihr ihv => cases hs with
| echoValLeft h => exact ihr h
| echoValRight _ h => exact ihv h
| pair _ _ iha ihb => cases hs with
| pairLeft h => exact iha h
| pairRight _ h => exact ihb h
| epiVal _ _ ihc ihe => cases hs with
| epiValClaim h => exact ihc h
| epiValEv _ h => exact ihe h
| _ => cases hs
/-- Canonical forms for Num. -/
theorem canonical_num : IsValue e → HasType [] e .num → ∃ n, e = .num n := by
intro hv ht; cases hv <;> cases ht; exact ⟨_, rfl⟩
/-- Canonical forms for Str. -/
theorem canonical_str : IsValue e → HasType [] e .str → ∃ s, e = .str s := by
intro hv ht; cases hv <;> cases ht; exact ⟨_, rfl⟩
/-- Canonical forms for Word[n]. -/
theorem canonical_word : IsValue e → HasType [] e (.word n) →
(e = .identity ∧ n = 0) ∨ (∃ gs, e = .braidLit gs ∧ n = generatorWidth gs) := by
intro hv ht
cases hv with
| num => cases ht
| str => cases ht
| boolLit => cases ht
| identity => left; cases ht with | tIdentity => exact ⟨rfl, rfl⟩
| braidLit gs => right; cases ht with | tBraid => exact ⟨gs, rfl, rfl⟩
| echoVal _ _ => cases ht
| pair _ _ => cases ht
| epiVal _ _ => cases ht
/-- Canonical forms for Echo[ρ, τ]: a value of echo type is a formed echo value
`echoVal r v` whose residue `r` and result `v` are themselves values. This
is the canonical form that lets `lower`/`residue` make progress. -/
theorem canonical_echo : IsValue e → HasType [] e (.echo ρ τ) →
∃ r v, e = .echoVal r v ∧ IsValue r ∧ IsValue v := by
intro hv ht
cases hv with
| num => cases ht
| str => cases ht
| boolLit => cases ht
| identity => cases ht
| braidLit => cases ht
| echoVal hr hv => exact ⟨_, _, rfl, hr, hv⟩
| pair _ _ => cases ht
| epiVal _ _ => cases ht
/-- Canonical forms for Epi[κ, ρ, τ]: a value of epistemic type is a formed
warrant `epiVal κ c ev` whose claim and token are themselves values. This is
the canonical form that lets `evidence` make progress. Note it yields the
TOKEN's value-hood, not the claim's truth — the claim rides along in the
value but no rule projects it out. -/
theorem canonical_epi : IsValue e → HasType [] e (.epi κ ρ τ) →
∃ c ev, e = .epiVal κ c ev ∧ IsValue c ∧ IsValue ev := by
intro hv ht
cases hv with
| num => cases ht
| str => cases ht
| boolLit => cases ht
| identity => cases ht
| braidLit => cases ht
| echoVal _ _ => cases ht
| pair _ _ => cases ht
| epiVal hc he => cases ht; exact ⟨_, _, rfl, hc, he⟩
/-- Canonical forms for products: a value of product type is a `pair a b` whose
components `a` and `b` are themselves values. This is the canonical form
that lets `fst`/`snd` make progress. -/
theorem canonical_prod : IsValue e → HasType [] e (.prod α β) →
∃ a b, e = .pair a b ∧ IsValue a ∧ IsValue b := by
intro hv ht
cases hv with
| num => cases ht
| str => cases ht
| boolLit => cases ht
| identity => cases ht
| braidLit => cases ht
| echoVal _ _ => cases ht
| pair ha hb => exact ⟨_, _, rfl, ha, hb⟩
| epiVal _ _ => cases ht
-- Width distribution lemmas
private theorem foldl_max_init (gs : List Generator) (a : Nat) :
gs.foldl (fun acc g => max acc (g.idx + 1)) a =
max a (gs.foldl (fun acc g => max acc (g.idx + 1)) 0) := by
induction gs generalizing a with
| nil => simp [List.foldl]
| cons g rest ih =>
simp only [List.foldl]
rw [ih (max a (g.idx + 1)), ih (max 0 (g.idx + 1))]
omega
theorem generatorWidth_append (gs₁ gs₂ : List Generator) :
generatorWidth (gs₁ ++ gs₂) = max (generatorWidth gs₁) (generatorWidth gs₂) := by
simp only [generatorWidth, List.foldl_append]; rw [foldl_max_init]
private theorem foldl_shift_init (gs : List Generator) (n a : Nat) :
(gs.map fun g => { idx := g.idx + n, exp := g.exp : Generator}).foldl
(fun acc g => max acc (g.idx + 1)) a =
if gs = [] then a
else max a (gs.foldl (fun acc g => max acc (g.idx + 1)) 0 + n) := by
induction gs generalizing a with
| nil => simp
| cons g rest ih =>
simp only [List.map, List.foldl, List.cons_ne_nil, if_false]
rw [ih]
rw [foldl_max_init rest (max 0 (g.idx + 1))]
by_cases hrest : rest = []
· subst hrest; simp [List.foldl]; omega
· simp [hrest]; omega
theorem generatorWidth_shift (gs : List Generator) (n : Nat) :
generatorWidth (shiftGenerators gs n) =
if gs = [] then 0 else generatorWidth gs + n := by
simp only [generatorWidth, shiftGenerators]; rw [foldl_shift_init]
split <;> simp_all
-- ═══════════════════════════════════════════════════════════════════════
-- METATHEORY: WEAKENING + SUBSTITUTION (TG-1)
-- ═══════════════════════════════════════════════════════════════════════
--
-- The two structural lemmas underpinning `let`-binding. `weakening` inserts a
-- fresh hypothesis `σ` at position `Γ₁.length` (shifting the term to skip the
-- new binder); `subst_preserves` is the substitution lemma — typing is closed
-- under replacing the variable at `Γ₁.length` by a term `s` of its type.
--
-- Implementation notes (deviations from the naive POPLmark recipe):
-- * Variable lookup uses `Γ[i]?` (`List.getElem?`), not the deprecated
-- `List.get?`, so the append splits go through `List.getElem?_append_left`
-- / `List.getElem?_append_right`.
-- * Each derivation is taken apart with a bare `cases h` followed by
-- `rename_i`, rather than `cases h with | tCtor …`. Under
-- `induction e`, the binder/index arguments of `tVar`/`tLet` are unified
-- with the surrounding context, so the positional `with`-arm naming does
-- not line up; `rename_i` names exactly the residual hypotheses.
-- * `subst_preserves` carries the hypothesis `s` typed in the COMBINED
-- context `Γ₁ ++ Γ₂` (not merely `Γ₂`). This is the genuine inductive
-- invariant: the naive `HasType Γ₂ s σ` form is *false* for a non-empty
-- prefix (e.g. `Γ₁ = [α]`, `s = .var 0` pointing into `Γ₂`). The `letRed`
-- consumer instantiates `Γ₁ := []`, where `Γ₁ ++ Γ₂ = Γ₂`, so it still
-- accepts a closed-context premise directly. Because `s` is already in
-- the combined context, the `var = Γ₁.length` case closes by `exact hs`
-- and no separate `front_weakening` / shift-composition lemma is needed.
/-- **Weakening (insertion)**: inserting a fresh hypothesis `σ` at de Bruijn
position `Γ₁.length` preserves typing, provided the term is shifted to
skip the new binder. -/
theorem weakening {Γ₁ Γ₂ : Ctx} {e : Expr} {τ σ : Ty} :
HasType (Γ₁ ++ Γ₂) e τ → HasType (Γ₁ ++ σ :: Γ₂) (shift 1 Γ₁.length e) τ := by
intro h
induction e generalizing Γ₁ τ with
| var k =>
cases h; rename_i hi; simp only [shift]
by_cases hk : k < Γ₁.length
· simp only [hk, if_true]
rw [List.getElem?_append_left hk] at hi
exact .tVar _ _ _ (by rw [List.getElem?_append_left hk]; exact hi)
· simp only [hk, if_false]
rw [List.getElem?_append_right (by omega)] at hi
refine .tVar _ _ _ ?_
rw [List.getElem?_append_right (by omega)]
have hrw : k + 1 - Γ₁.length = (k - Γ₁.length) + 1 := by omega
rw [hrw]; simpa using hi
| lett e₁ e₂ ih₁ ih₂ =>
cases h; rename_i a h₁ h₂; simp only [shift]
refine .tLet _ _ _ a _ (ih₁ h₁) ?_
have hr := ih₂ (Γ₁ := a :: Γ₁) h₂
simpa using hr
| num _ => cases h; exact .tNum _ _
| str _ => cases h; exact .tStr _ _
| boolLit _ => cases h; exact .tBool _ _
| identity => cases h; exact .tIdentity _
| braidLit _ => cases h; exact .tBraid _ _
| compose a b iha ihb =>
cases h; rename_i n m h₁ h₂; simp only [shift]; exact .tComposeWord _ _ _ n m (iha h₁) (ihb h₂)
| tensor a b iha ihb =>
cases h; rename_i n m h₁ h₂; simp only [shift]; exact .tTensorWord _ _ _ n m (iha h₁) (ihb h₂)
| pipeline a b iha ihb =>
cases h; rename_i hc; simp only [shift]
cases hc; rename_i n m h₁ h₂
exact .tPipeline _ _ _ _ (.tComposeWord _ _ _ n m (iha h₁) (ihb h₂))
| close a iha =>
cases h; rename_i n h₁; simp only [shift]; exact .tCloseWord _ _ n (iha h₁)
| add a b iha ihb =>
cases h; rename_i h₁ h₂; simp only [shift]; exact .tAddNum _ _ _ (iha h₁) (ihb h₂)
| eq a b iha ihb =>
cases h <;> simp only [shift]
· rename_i n m h₁ h₂; exact .tEqWord _ _ _ n m (iha h₁) (ihb h₂)
· rename_i h₁ h₂; exact .tEqNum _ _ _ (iha h₁) (ihb h₂)
· rename_i h₁ h₂; exact .tEqStr _ _ _ (iha h₁) (ihb h₂)
| echoClose a iha =>
cases h; rename_i n h₁; simp only [shift]; exact .tEchoClose _ _ n (iha h₁)
| lower a iha =>
cases h; rename_i ρ h₁; simp only [shift]; exact .tLower _ _ ρ _ (iha h₁)
| residue a iha =>
cases h; rename_i τ' h₁; simp only [shift]; exact .tResidue _ _ _ τ' (iha h₁)
| echoVal a b iha ihb =>
cases h; rename_i ρ τ' h₁ h₂; simp only [shift]; exact .tEchoVal _ _ _ ρ τ' (iha h₁) (ihb h₂)
| pair a b iha ihb =>
cases h; rename_i α β h₁ h₂; simp only [shift]; exact .tPair _ _ _ α β (iha h₁) (ihb h₂)
| warrant κ cl ev ihc ihe =>
cases h; rename_i ρ τ' h₁ h₂; simp only [shift]
exact .tWarrant _ _ _ _ _ _ (ihc h₁) (ihe h₂)
| epiVal κ cl ev ihc ihe =>
cases h; rename_i ρ τ' h₁ h₂; simp only [shift]
exact .tEpiVal _ _ _ _ _ _ (ihc h₁) (ihe h₂)
| evidence a iha =>
cases h; rename_i κ τ' h₁; simp only [shift]; exact .tEvidence _ _ _ _ _ (iha h₁)
| fst a iha =>
cases h; rename_i β h₁; simp only [shift]; exact .tFst _ _ _ β (iha h₁)
| snd a iha =>
cases h; rename_i α h₁; simp only [shift]; exact .tSnd _ _ α _ (iha h₁)
| echoAdd a b iha ihb =>
cases h; rename_i h₁ h₂; simp only [shift]; exact .tEchoAdd _ _ _ (iha h₁) (ihb h₂)
| echoEq a b iha ihb =>
cases h <;> simp only [shift]
· rename_i n h₁ h₂; exact .tEchoEqWord _ _ _ n (iha h₁) (ihb h₂)
· rename_i h₁ h₂; exact .tEchoEqNum _ _ _ (iha h₁) (ihb h₂)
· rename_i h₁ h₂; exact .tEchoEqStr _ _ _ (iha h₁) (ihb h₂)
/-- **Substitution**: typing is preserved by substituting the variable at de
Bruijn position `Γ₁.length` by a term `s` of its type, with `s` taken in
the combined context `Γ₁ ++ Γ₂` (the inductive invariant; see note above). -/
theorem subst_preserves {Γ₁ Γ₂ : Ctx} {e s : Expr} {τ σ : Ty} :
HasType (Γ₁ ++ σ :: Γ₂) e τ → HasType (Γ₁ ++ Γ₂) s σ →
HasType (Γ₁ ++ Γ₂) (subst Γ₁.length s e) τ := by
intro h hs
induction e generalizing Γ₁ s τ with
| var k =>
cases h; rename_i hi; simp only [subst]
by_cases hlt : k < Γ₁.length
· simp only [hlt, if_true]
rw [List.getElem?_append_left hlt] at hi
exact .tVar _ _ _ (by rw [List.getElem?_append_left hlt]; exact hi)
· by_cases heq : k = Γ₁.length
· subst heq
simp only [Nat.lt_irrefl, if_false]
rw [List.getElem?_append_right (by omega)] at hi
simp only [Nat.sub_self, List.getElem?_cons_zero, Option.some.injEq] at hi
subst hi; exact hs
· simp only [hlt, if_false, heq, if_false]
rw [List.getElem?_append_right (by omega)] at hi
refine .tVar _ _ _ ?_
rw [List.getElem?_append_right (by omega)]
have e1 : k - Γ₁.length = (k - 1 - Γ₁.length) + 1 := by omega
rw [e1] at hi; simpa using hi
| lett e₁ e₂ ih₁ ih₂ =>
cases h; rename_i a h₁ h₂; simp only [subst]
refine .tLet _ _ _ a _ (ih₁ h₁ hs) ?_
have hws : HasType ((a :: Γ₁) ++ Γ₂) (shift 1 0 s) σ := by
have hw := weakening (Γ₁ := []) (σ := a) hs
simpa using hw
have hr := ih₂ (Γ₁ := a :: Γ₁) (s := shift 1 0 s) h₂ hws
simpa using hr
| num _ => cases h; exact .tNum _ _
| str _ => cases h; exact .tStr _ _
| boolLit _ => cases h; exact .tBool _ _
| identity => cases h; exact .tIdentity _
| braidLit _ => cases h; exact .tBraid _ _
| compose a b iha ihb =>
cases h; rename_i n m h₁ h₂; simp only [subst]; exact .tComposeWord _ _ _ n m (iha h₁ hs) (ihb h₂ hs)
| tensor a b iha ihb =>
cases h; rename_i n m h₁ h₂; simp only [subst]; exact .tTensorWord _ _ _ n m (iha h₁ hs) (ihb h₂ hs)
| pipeline a b iha ihb =>
cases h; rename_i hc; simp only [subst]
cases hc; rename_i n m h₁ h₂
exact .tPipeline _ _ _ _ (.tComposeWord _ _ _ n m (iha h₁ hs) (ihb h₂ hs))
| close a iha =>
cases h; rename_i n h₁; simp only [subst]; exact .tCloseWord _ _ n (iha h₁ hs)
| add a b iha ihb =>
cases h; rename_i h₁ h₂; simp only [subst]; exact .tAddNum _ _ _ (iha h₁ hs) (ihb h₂ hs)
| eq a b iha ihb =>
cases h <;> simp only [subst]
· rename_i n m h₁ h₂; exact .tEqWord _ _ _ n m (iha h₁ hs) (ihb h₂ hs)
· rename_i h₁ h₂; exact .tEqNum _ _ _ (iha h₁ hs) (ihb h₂ hs)
· rename_i h₁ h₂; exact .tEqStr _ _ _ (iha h₁ hs) (ihb h₂ hs)
| echoClose a iha =>
cases h; rename_i n h₁; simp only [subst]; exact .tEchoClose _ _ n (iha h₁ hs)
| lower a iha =>
cases h; rename_i ρ h₁; simp only [subst]; exact .tLower _ _ ρ _ (iha h₁ hs)
| residue a iha =>
cases h; rename_i τ' h₁; simp only [subst]; exact .tResidue _ _ _ τ' (iha h₁ hs)
| echoVal a b iha ihb =>
cases h; rename_i ρ τ' h₁ h₂; simp only [subst]; exact .tEchoVal _ _ _ ρ τ' (iha h₁ hs) (ihb h₂ hs)
| pair a b iha ihb =>
cases h; rename_i α β h₁ h₂; simp only [subst]; exact .tPair _ _ _ α β (iha h₁ hs) (ihb h₂ hs)
| warrant κ cl ev ihc ihe =>
cases h; rename_i ρ τ' h₁ h₂; simp only [subst]
exact .tWarrant _ _ _ _ _ _ (ihc h₁ hs) (ihe h₂ hs)
| epiVal κ cl ev ihc ihe =>
cases h; rename_i ρ τ' h₁ h₂; simp only [subst]
exact .tEpiVal _ _ _ _ _ _ (ihc h₁ hs) (ihe h₂ hs)
| evidence a iha =>
cases h; rename_i κ τ' h₁; simp only [subst]; exact .tEvidence _ _ _ _ _ (iha h₁ hs)
| fst a iha =>
cases h; rename_i β h₁; simp only [subst]; exact .tFst _ _ _ β (iha h₁ hs)
| snd a iha =>
cases h; rename_i α h₁; simp only [subst]; exact .tSnd _ _ α _ (iha h₁ hs)
| echoAdd a b iha ihb =>
cases h; rename_i h₁ h₂; simp only [subst]; exact .tEchoAdd _ _ _ (iha h₁ hs) (ihb h₂ hs)
| echoEq a b iha ihb =>
cases h <;> simp only [subst]
· rename_i n h₁ h₂; exact .tEchoEqWord _ _ _ n (iha h₁ hs) (ihb h₂ hs)
· rename_i h₁ h₂; exact .tEchoEqNum _ _ _ (iha h₁ hs) (ihb h₂ hs)
· rename_i h₁ h₂; exact .tEchoEqStr _ _ _ (iha h₁ hs) (ihb h₂ hs)
-- ═══════════════════════════════════════════════════════════════════════
-- THEOREM 1: PROGRESS
-- ═══════════════════════════════════════════════════════════════════════
/-- **Progress**: Every well-typed closed term is either a value or can
take a step. This is the standard progress theorem from TAPL §8. -/
theorem progress : HasType [] e τ → IsValue e ∨ ∃ e', Step e e' := by
-- Recurse structurally on the expression (the typing derivation cannot drive
-- structural recursion once `tLet` is present, since its body premise lives
-- in an extended context). Each constructor inverts the typing hypothesis;
-- the recursive `progress` calls become the Expr induction hypotheses.
intro ht
induction e generalizing τ with
| var k => cases ht; rename_i hi; simp at hi -- vacuous: `[][i]? = some τ`
| lett e₁ e₂ ih₁ _ =>
cases ht; rename_i h₁ h₂
right
rcases ih₁ h₁ with hv | ⟨e₁', hs⟩
· exact ⟨_, .letRed hv⟩
· exact ⟨_, .letStep hs⟩
| num _ => cases ht; left; exact .num _
| str _ => cases ht; left; exact .str _
| boolLit _ => cases ht; left; exact .boolLit _
| identity => cases ht; left; exact .identity
| braidLit _ => cases ht; left; exact .braidLit _
| compose a b iha ihb =>
cases ht; rename_i h₁ h₂
right
rcases iha h₁ with hv₁ | ⟨e₁', hs₁⟩
· rcases ihb h₂ with hv₂ | ⟨e₂', hs₂⟩
· rcases canonical_word hv₁ h₁ with ⟨rfl, _⟩ | ⟨gs₁, rfl, _⟩ <;>
rcases canonical_word hv₂ h₂ with ⟨rfl, _⟩ | ⟨gs₂, rfl, _⟩
· exact ⟨_, .composeIdId⟩
· exact ⟨_, .composeIdL⟩
· exact ⟨_, .composeIdR⟩
· exact ⟨_, .composeWords⟩
· exact ⟨_, .composeRight hv₁ hs₂⟩
· exact ⟨_, .composeLeft hs₁⟩
| tensor a b iha ihb =>
cases ht; rename_i h₁ h₂
right
rcases iha h₁ with hv₁ | ⟨e₁', hs₁⟩
· rcases ihb h₂ with hv₂ | ⟨e₂', hs₂⟩
· rcases canonical_word hv₁ h₁ with ⟨rfl, _⟩ | ⟨gs₁, rfl, _⟩ <;>
rcases canonical_word hv₂ h₂ with ⟨rfl, _⟩ | ⟨gs₂, rfl, _⟩
· exact ⟨_, .tensorIdId⟩
· exact ⟨_, .tensorIdL⟩
· exact ⟨_, .tensorIdR⟩
· exact ⟨_, .tensorWords⟩
· exact ⟨_, .tensorRight hv₁ hs₂⟩
· exact ⟨_, .tensorLeft hs₁⟩
| pipeline a b _ _ => cases ht; exact .inr ⟨_, .pipeline⟩
| close a iha =>
cases ht; rename_i h
right
rcases iha h with hv | ⟨e', hs⟩
· rcases canonical_word hv h with ⟨rfl, _⟩ | ⟨gs, rfl, _⟩
· exact ⟨_, .closeId⟩
· exact ⟨_, .closeWord⟩
· exact ⟨_, .closeStep hs⟩
| add a b iha ihb =>
cases ht; rename_i h₁ h₂
right
rcases iha h₁ with hv₁ | ⟨e₁', hs₁⟩
· rcases ihb h₂ with hv₂ | ⟨e₂', hs₂⟩
· obtain ⟨n₁, rfl⟩ := canonical_num hv₁ h₁
obtain ⟨n₂, rfl⟩ := canonical_num hv₂ h₂
exact ⟨_, .addNums⟩
· exact ⟨_, .addRight hv₁ hs₂⟩
· exact ⟨_, .addLeft hs₁⟩
| eq a b iha ihb =>
right
cases ht with
| tEqWord =>
rename_i n h₁ h₂
rcases iha h₁ with hv₁ | ⟨e₁', hs₁⟩
· rcases ihb h₂ with hv₂ | ⟨e₂', hs₂⟩
· rcases canonical_word hv₁ h₁ with ⟨rfl, _⟩ | ⟨gs₁, rfl, _⟩ <;>
rcases canonical_word hv₂ h₂ with ⟨rfl, _⟩ | ⟨gs₂, rfl, _⟩
· exact ⟨_, .eqIdId⟩
· exact ⟨_, .eqIdBraid⟩
· exact ⟨_, .eqBraidId⟩
· exact ⟨_, .eqBraids⟩
· exact ⟨_, .eqRight hv₁ hs₂⟩
· exact ⟨_, .eqLeft hs₁⟩
| tEqNum =>
rename_i h₁ h₂
rcases iha h₁ with hv₁ | ⟨e₁', hs₁⟩
· rcases ihb h₂ with hv₂ | ⟨e₂', hs₂⟩
· obtain ⟨n₁, rfl⟩ := canonical_num hv₁ h₁
obtain ⟨n₂, rfl⟩ := canonical_num hv₂ h₂