forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompletion.tex
1921 lines (1741 loc) · 140 KB
/
completion.tex
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
\documentclass[../generics]{subfiles}
\begin{document}
\chapter{Completion}\label{completion}
\IndexDefinition{Knuth-Bendix algorithm}%
\index{completion!z@\igobble|seealso{Knuth-Bendix algorithm}}
\lettrine{K}{nuth-Bendix completion} is the central algorithm in the Requirement Machine. Completion attempts to construct a \index{convergent rewrite system}convergent rewrite system from a list of rewrite rules, and a convergent rewrite system allows us to decide if two terms have the same reduced form in a finite number of steps, solving the word problem. As we saw in the previous chapter, our initial rewrite rules are defined by the explicit requirements of a generic signature and its protocol dependencies. A desirable property of this mapping was given by Theorem~\ref{derivation to path}: a \emph{derived} requirement defines a rewrite path over these rewrite rules representing explicit requirements. All of this means that completion gives us a \emph{decision procedure} for the \index{derived requirement}derived requirements formalism: the question of whether any given derived requirement is satisfied---that is, if there exists a valid derivation built from explicit requirements---is easily solved by term reduction in a convergent rewrite system. This is the foundation on which we build both \index{generic signature query}generic signature queries and \index{requirement minimization}minimization.
\paragraph{The algorithm.} We'll give a self-contained description first, with much of the rest of the chapter devoted to examples. Our description can be supplemented with any text on rewrite systems, such as \cite{book2012string} or \cite{andallthat}. The algorithm is somewhat clever; to really ``get it'' might require several attempts. \index{Donald~Knuth}Donald~E.~Knuth and \index{Peter Bendix}Peter Bendix described the algorithm for term rewrite systems in a 1970 paper \cite{Knuth1983}; a correctness proof was later given by \index{Gerard Huet@G\'erard Huet}G\'erard Huet in \cite{HUET198111}. In our application, the terms are elements of a free monoid, so we have a string rewrite system; this special case was studied in \cite{narendran}. A survey of related techniques appears in \cite{BUCHBERGER19873}.
The entry point into the Knuth-Bendix completion procedure is Algorithm~\ref{knuthbendix}, but we break off four smaller pieces before we get there, so that only the top-level loop remains:
\begin{itemize}
\item Algorithm~\ref{overlap trie lookup} finds all rules that overlap with a fixed rule at a fixed position.
\item Algorithm~\ref{find overlapping rule algo} finds all pairs of rules that overlap at any position.
\item Algorithm~\ref{critical pair algo} builds a critical pair from a pair of overlapping rules.
\item Algorithm~\ref{add rule derived algo} resolves a critical pair.
\end{itemize}
We begin with Algorithm \ref{critical pair algo}~and~\ref{add rule derived algo}, proceeding from the inside out. The twin concepts of overlapping rule and critical pair are fundamental to the algorithm, and they provide the theoretical justification for the rest.
\paragraph{Local confluence.} We would like our \index{reduction relation}reduction relation $\rightarrow$ to satisfy the \index{Church-Rosser property}Church-Rosser property: if $x\sim y$ are two equivalent terms, then $x\rightarrow z$ and $y\rightarrow z$ for some term $z$. By Theorem~\ref{church rosser theorem}, this is equivalent to $\rightarrow$ being \index{confluence}confluent, meaning any two \index{positive rewrite path}positive rewrite paths diverging from a common source can be extended to meet each other. This is difficult to verify directly, but a 1941 paper by Max~Newman~\cite{newman} shows there is a simpler equivalent condition when the reduction relation is \index{terminating reduction relation}terminating.
\begin{definition}
A reduction relation $\rightarrow$ is \IndexDefinition{local confluence}\emph{locally confluent}, if whenever $s_1$ and $s_2$ are two positive rewrite steps with $\Src(s_1)=\Src(s_2)$, there exists a term $z$ such that $\Dst(s_1)\rightarrow z$ and $\Dst(s_2)\rightarrow z$.
\end{definition}
To test for local confluence, we ``diverge'' from a term by only one step in two different directions, and then check if both sides reduce to some common term. We will see this can be decided algorithmically, and also that we can ``repair'' any local \index{confluence violation}confluence violations we do find. Thus, \index{Newman's lemma}Newman's result is fundamental:
\begin{theorem}[Newman's Lemma]
If a reduction relation $\rightarrow$ is terminating and locally confluent, then $\rightarrow$ is confluent.
\end{theorem}
\paragraph{Overlapping rules.} A pair of positive rewrite steps with a common source define a \IndexDefinition{critical pair}\emph{critical pair}. A critical pair shows that some term can be reduced in ``two different ways.'' We can answer if our rewrite rules define a locally confluent reduction relation by inspecting each critical pair. With any non-trivial list of rewrite rules, there are infinitely many such critical pairs, however, all but a finite subset can be disregarded. Suppose we have a rewrite system over an alphabet $A$ with two rules:
\begin{gather*}
u_1\Rightarrow v_1\\
u_2\Rightarrow v_2
\end{gather*}
For any term $x\in A^*$, we can form the ``sandwich'' term $t := u_1xu_2$. Every such choice of $x$ defines a new critical pair; the occurrences of $u_1$ and $u_2$ within $t$ can be rewritten in two ways, by $s_1 := (u_1\Rightarrow v_1)xu_2$ and $s_2 := u_1x(u_2\Rightarrow v_2)$. However, since $s_1$ and $s_2$ rewrite disjoint subterms of $t$, we say this critical pair is \IndexDefinition{orthogonal rewrite step}\emph{orthogonal}. Orthogonal critical pairs are not interesting because they cannot witness a local confluence violation. To see why, notice that regardless of whether we apply $s_1$ or $s_2$ first, there exists a complementary rewrite step $s_1^\prime$ or $s_2^\prime$ to rewrite $\Dst(s_1)$ or $\Dst(s_2)$ into the ``reduced sandwich'' $v_1xv_2$. In fact, we get a \index{commutative diagram}commutative diagram like this for any orthogonal critical pair:
\[
\begin{tikzcd}
&u_1xu_2\arrow[ld, Rightarrow, "s_1:=(u_1\Rightarrow v_1)xu_2"', bend right]\arrow[rd, Rightarrow, "s_2:=u_1x(u_2\Rightarrow v_2)", bend left]\\
v_1xu_2\arrow[rd, Rightarrow, "s_1^\prime := v_1x(u_2\Rightarrow v_2)"', bend right]&&u_1xv_2\arrow[ld, Rightarrow, "s_2^\prime:=v_1x(u_2\Rightarrow v_2)", bend left]\\
&v_1xv_2
\end{tikzcd}
\]
We can also visualize an orthogonal critical pair using the ``pictorial'' notation for rewrite steps we devised in Section~\ref{rewrite graph}:
\[
\begin{array}{cc}
\text{$s_1$ first:}&
\text{$s_2$ first:}\\
\begin{array}{|c|c|c|}
\hline
\multicolumn{3}{|c|}{u_1xu_2}\\
\hline
\hline
u_1&&\\
\Downarrow&y&u_2\\
v_1&&\\
\hline
\hline
\multicolumn{3}{|c|}{v_1xu_2}\\
\hline
\hline
&&u_2\\
v_1&y&\Downarrow\\
&&v_2\\
\hline
\hline
\multicolumn{3}{|c|}{v_1xv_2}\\
\hline
\end{array}
&
\begin{array}{|c|c|c|}
\hline
\multicolumn{3}{|c|}{u_1xu_2}\\
\hline
\hline
&&u_2\\
u_1&y&\Downarrow\\
&&v_2\\
\hline
\hline
\multicolumn{3}{|c|}{u_1xv_2}\\
\hline
\hline
u_1&&\\
\Downarrow&y&v_2\\
v_2&&\\
\hline
\hline
\multicolumn{3}{|c|}{v_1xv_2}\\
\hline
\end{array}
\end{array}
\]
Clearly, in our quest to uncover local \index{confluence violation}confluence violations, we only need to inspect critical pairs that are \emph{not} orthogonal; that is, they must rewrite \emph{overlapping} subterms of their common source term. There are only finitely many such critical pairs, and they are all generated by inspecting the left-hand sides of rewrite rules in our rewrite system. We can completely characterize them with the below definition.
\begin{definition}\label{overlappingrules}
Two rules $u_1\Rightarrow v_1$ and $u_2\Rightarrow v_2$ \IndexDefinition{overlapping rules}\emph{overlap} if one of the following holds:
\begin{enumerate}
\item The left-hand side of the second rule is contained entirely within the left-hand side of the first. That is, $u_1=xyz$ and $u_2=y$ for some $x$, $y$, $z\in A^*$. If we write down the terms $u_1$ and $u_2$ and shift $u_2$ over until they line up, we get this:
\begin{align*}
x&yz\\
&y
\end{align*}
\item The left-hand side of the second rule has a prefix equal to a suffix of the left-hand side of the first. That is, $u_1=xy$ and $u_2=yz$ for some $x$, $y$, $z\in A^*$, with $|x|>0$ and $|z|>0$. If we write down the terms $u_1$ and $u_2$ and shift $u_2$ over until they line up, we get this:
\begin{align*}
x&y\\
&yz
\end{align*}
\end{enumerate}
The above are the two ways in which a non-orthogonal critical pair can rewrite the same term. When the case distinction is important, we can talk about an overlap of the \emph{first kind}, or \emph{second kind}, respectively. In both cases, after a suitable assignment of $x$, $y$ and $z$, we define the \IndexDefinition{overlap term}\emph{overlap term} to be $xyz$, and the \IndexDefinition{overlap position}\emph{overlap position} to be $|x|$.
\end{definition}
\begin{example}
Consider these three rules:
\begin{gather*}
\ttgp{0}{0}.\assocsym{Collection}{SubSequence}.\protosym{Equatable}\tag{1}\\
\ttgp{0}{0}.\assocsym{Collection}{SubSequence}\Rightarrow\ttgp{0}{1}\tag{2}\\
\assocsym{Collection}{SubSequence}.\assocsym{Collection}{Element}\Rightarrow\assocsym{Collection}{Element}\tag{3}
\end{gather*}
There is an overlap of the first kind between (1) and (2) at position 0; the left-hand side of (2) is contained entirely in the left-hand side of (1). Here, the overlap term is $\ttgp{0}{0}.\assocsym{Collection}{SubSequence}.\protosym{Equatable}$:
\begin{align*}
&\ttgp{0}{0}.\assocsym{Collection}{SubSequence}.\protosym{Equatable}\\
&\ttgp{0}{0}.\assocsym{Collection}{SubSequence}
\end{align*}
There is an overlap of the second kind between (1) and (3) at position 1; the left-hand side of (3) begins with the prefix $\assocsym{Collection}{SubSequence}$, which is also a suffix of the left-hand side of (1). The overlap term is $\ttgp{0}{0}.\assocsym{Collection}{SubSequence}.\protosym{Equatable}$:
\begin{align*}
\ttgp{0}{0}.&\assocsym{Collection}{SubSequence}\\
&\assocsym{Collection}{SubSequence}.\assocsym{Collection}{Element}
\end{align*}
The definition of an overlap of the second kind requires both $x$ and $z$ to be non-empty. If we relaxed this condition, then we would \emph{also} have an overlap of the second kind between rule (2) and (1) at position 0:
\begin{align*}
&\ttgp{0}{0}.\assocsym{Collection}{SubSequence}\\
&\ttgp{0}{0}.\assocsym{Collection}{SubSequence}.\protosym{Equatable}
\end{align*}
The overlap term and position is the same as the first case we saw already, so attempting to \index{resolving critical pair}resolve this critical pair would not reveal anything new. We adjust our definition to avoid duplicated work in this situation.
It can happen that two rules overlap more than once at \emph{different} positions; in this case we must consider every possible overlap. For example, these two rules generate four overlaps in total:
\begin{gather*}
\assocsym{P}{A}.\assocsym{P}{B}.\assocsym{P}{A}.\assocsym{P}{B}\Rightarrow \assocsym{P}{C}\tag{4}\\
\assocsym{P}{B}.\assocsym{P}{A}.\assocsym{P}{B}.\assocsym{P}{A}\Rightarrow \assocsym{P}{D}\tag{5}
\end{gather*}
Rule (4) overlaps with (5) at position 1:
\begin{align*}
\assocsym{P}{A}.&\assocsym{P}{B}.\assocsym{P}{A}.\assocsym{P}{B}\\
&\assocsym{P}{B}.\assocsym{P}{A}.\assocsym{P}{B}.\assocsym{P}{A}
\end{align*}
Rrule (4) overlaps with (5) at position 3:
\begin{align*}
\assocsym{P}{A}.\assocsym{P}{B}.\assocsym{P}{A}.&\assocsym{P}{B}\\
&\assocsym{P}{B}.\assocsym{P}{A}.\assocsym{P}{B}.\assocsym{P}{A}
\end{align*}
Rule (5) overlaps with (4) at position 1:
\begin{align*}
\assocsym{P}{B}.&\assocsym{P}{A}.\assocsym{P}{B}.\assocsym{P}{A}\\
&\assocsym{P}{A}.\assocsym{P}{B}.\assocsym{P}{A}.\assocsym{P}{B}
\end{align*}
Last but not least, rule (5) overlaps with (4) at position 3:
\begin{align*}
\assocsym{P}{B}.\assocsym{P}{A}.\assocsym{P}{B}.&\assocsym{P}{A}\\
&\assocsym{P}{A}.\assocsym{P}{B}.\assocsym{P}{A}.\assocsym{P}{B}
\end{align*}
\end{example}
\paragraph{Resolving critical pairs.}
A critical pair exhibits some term $t$ being rewritten in two distinct ways. If we take the destination term of each of the two rewrite steps, we get a pair of terms that are known to be equivalent to $t$, and each other. For an overlap of the first kind, the two terms are $(v_1,\,xv_2z)$; for the second kind, $(v_1z,\,xv_2)$:
\begin{quote}
\begin{tabular}{cc}
Overlap of the first kind&
Overlap of the second kind\\
\begin{tikzcd}
&xyz\arrow[ld, Rightarrow, "(u_1\Rightarrow v_1)"', bend right]\arrow[rd, Rightarrow, "x(u_2\Rightarrow v_2)z", bend left]\\
v_1&&xv_2z
\end{tikzcd}&
\begin{tikzcd}
&xyz\arrow[ld, Rightarrow, "(u_1\Rightarrow v_1)z"', bend right]\arrow[rd, Rightarrow, "x(u_2\Rightarrow v_2)", bend left]\\
v_1z&&xv_2
\end{tikzcd}
\end{tabular}
\end{quote}
We \IndexDefinition{resolving critical pair}\emph{resolve} a critical pair $(t_1,t_2)$ by reducing both sides with the reduction relation as constructed so far and comparing the reduced terms. There are four possible outcomes:
\begin{enumerate}
\item If $t_1$ and $t_2$ reduce to the same term $t^\prime$, we say the \IndexDefinition{trivial critical pair}critical pair is \emph{trivial}. (Note that this terminology offers an alternate definition of local confluence: a reduction relation is locally confluent if all critical pairs are trivial.)
\item If $t_1\rightarrow t_1^\prime$ and $t_2\rightarrow t_2^\prime$ with $t_1^\prime\neq t_2^\prime$, we found two distinct \index{reduced term}reduced terms in the same \index{equivalence class}equivalence class: a \index{confluence violation}\emph{confluence violation}. If $t_2^\prime < t_1^\prime$, we repair the confluence violation by adding a new rewrite rule $t_1^\prime\Rightarrow t_2^\prime$. Having done so, if we then define $t^\prime:=t_2^\prime$, we once again see that both $t_1$ and $t_2$ reduce to the same term $t^\prime$.
\item If instead $t_1^\prime<t_2^\prime$, we have the same situation except we resolve it by adding a new rewrite rule $t_2^\prime\Rightarrow t_1^\prime$, and we let $t^\prime:=t_1^\prime$.
\item If $t_1^\prime$ and $t_2^\prime$ are distinct but incomparable, we have a \index{non-orientable relation}non-orientable relation, and we must report an error. This cannot happen under the reduction order used by the Requirement Machine.
\end{enumerate}
We can draw a diagram for each case, showing a \index{subgraph}subgraph of the \index{rewrite graph}rewrite graph; dashed arrows indicate new rules being added:
\begin{center}
\begin{tabular}{ccc}
Trivial overlap&
Adding a new rule&
Adding a new rule\\
\begin{tikzcd}
&t\arrow[ld, Rightarrow, bend right]\arrow[rd, Rightarrow, bend left]\\
t_1\arrow[d, Rightarrow]&&t_2\arrow[d, Rightarrow]\\
\vphantom{P}\cdots\arrow[rd, Rightarrow, bend right]&&\vphantom{P}\cdots\arrow[ld, Rightarrow, bend left]\\
&t^\prime
\end{tikzcd}&
\begin{tikzcd}
&t\arrow[ld, Rightarrow, bend right]\arrow[rd, Rightarrow, bend left]\\
t_1\arrow[d, Rightarrow]&&t_2\arrow[d, Rightarrow]\\
t_1^\prime\arrow[rd, Rightarrow, dashed, bend right]&&\vphantom{P}\cdots\arrow[ld, Rightarrow, bend left]\\
&t^\prime
\end{tikzcd}&
\begin{tikzcd}
&t\arrow[ld, Rightarrow, bend right]\arrow[rd, Rightarrow, bend left]\\
t_1\arrow[d, Rightarrow]&&t_2\arrow[d, Rightarrow]\\
\vphantom{P}\cdots\arrow[rd, Rightarrow, bend right]&&t_2^\prime\arrow[ld, Rightarrow, bend left, dashed]\\
&t^\prime
\end{tikzcd}
\end{tabular}
\end{center}
After adding a new rewrite rule if necessary, we have a pair of rewrite paths $p_1$ and $p_2$, and a term $t^\prime$. Note that $\Src(p_1)=\Src(p_2)=t$ and $\Dst(p_1)=\Dst(p_2)=t^\prime$, so both paths have the same source and destination. We say $p_1$ and $p_2$ are \IndexDefinition{parallel rewrite paths}\emph{parallel} rewrite paths.
\paragraph{Rewrite loops.}
Now we slightly change our point of view and introduce a new concept. If we take two parallel rewrite paths $p_1$ and $p_2$, we can form the rewrite path $\ell:=p_1\circ p_2^{-1}$ by composing the first path with the inverse of the second:
\[
\begin{array}{ccc}
\text{$p_1$:}&\text{$p_2$:}&\text{$p_1\circ p_2^{-1}$}\\
\begin{tikzcd}
&t\arrow[ld, Rightarrow, bend right]\\
\vphantom{P}\cdots\arrow[rd, Rightarrow, bend right]\\
&t^\prime
\end{tikzcd}&
\begin{tikzcd}
t\arrow[rd, Rightarrow, bend left]\\
&\vphantom{P}\cdots\arrow[ld, Rightarrow, bend left]\\
t^\prime
\end{tikzcd}&
\begin{tikzcd}
&t\arrow[ld, Rightarrow, bend right]\\
\vphantom{P}\cdots\arrow[rd, Rightarrow, bend right]&&\vphantom{P}\cdots\arrow[lu, Rightarrow, bend right]\\
&t^\prime\arrow[ru, Rightarrow, bend right]
\end{tikzcd}
\end{array}
\]
This new rewrite path $\ell$ has the property that it begins and ends at the \emph{same} term $t$:
\begin{gather*}
\Src(\ell)=\Src(p_1)=t\qquad\qquad\Dst(\ell)=\Dst(p_2^{-1})=\Src(p_2)=t
\end{gather*}
We say that $\ell$ is a \IndexDefinition{rewrite loop}\emph{rewrite loop} with \IndexDefinition{basepoint}basepoint $t$. A rewrite loop applies some sequence of rewrite rules to the basepoint term $t$, then rewrites it ``back'' to $t$, via a possibly \emph{different} mix of rewrite rules. In the \index{rewrite graph}rewrite graph, a rewrite loop is a \index{cycle}cycle (sometimes called a ``closed path'' by graph theorists). Note that for each $t\in A^*$, the \index{empty rewrite path}empty rewrite path $1_t$ can also be seen as a trivial rewrite loop with basepoint $t$.
Now, we give two algorithms that together form the inner loop of the completion procedure. It is also convenient to view a \index{critical pair}critical pair as a rewrite path of length 2, rather than a pair of rewrite steps with the same source term---we compose the first step with the inverse of the second. In this new formulation, critical pair resolution ``completes'' the critical pair to form a rewrite loop.
\begin{algorithm}[Construct critical pair]\label{critical pair algo}
Takes two rules $u_1\Rightarrow v_1$ and $u_2\Rightarrow v_2$, together with an overlap position $i$ where $0\leq i<|u_1|$. Returns a triple $(t_1, t_2, p)$ where $t_1$ and $t_2$ are terms, and $p$ is a rewrite path with $\Src(p)=t_1$ and $\Dst(p)=t_2$.
\begin{enumerate}
\item If $i+|u_2|\leq|u_1|$, we have an overlap of the first kind; $u_1=xu_2z$ for some $x$ and $z$.
\begin{enumerate}
\item Let $x:=u_1[:i]$ (the prefix of $u_1$ of length $i$), and $z:=u_1[i+|u_2|:]$ (the suffix of $u_1$ of length $|u_1|-|u_2|-i$).
\item Set $t_1:=v_1$, the result of rewriting $u_1$ with the first rule.
\item Set $t_2:=xv_2z$, the result of rewriting $u_1$ with the second rule.
\item Set $p:=(v_1\Rightarrow u_1)\circ x(u_2\Rightarrow v_2)z$. This is a rewrite path from $t_1$ to $t_2$.
\end{enumerate}
\item Otherwise, we have an overlap of the second kind; $u_1=xy$ and $u_2=yz$ for some $x$, $y$ and $z$.
\begin{enumerate}
\item Let $x:=u_1[:i]$ (the prefix of $u_1$ of length $i$), $z:=u_2[|u_1|-i:]$ (the suffix of $u_2$ of length $|u_2|-|u_1|+i$). (We don't actually need $y:=u_1[i:]=u_2[:|u_1|-i]$.)
\item Set $t_1:=v_1z$, the result of rewriting $xyz$ with the first rule.
\item Set $t_2:=xv_2$, the result of rewriting $xyz$ with the second rule.
\item Set $p:=(v_1\Rightarrow u_1)z\circ x(u_2\Rightarrow v_2)$.
\end{enumerate}
\item Return the triple $(t_1, t_2, p)$.
\end{enumerate}
\end{algorithm}
\begin{algorithm}[Resolve critical pair]\label{add rule derived algo}
As input, takes terms $t_1$ and $t_2$, and a rewrite path $p$ with $\Src(p)=t_1$ and $\Dst(p)=t_2$. Records a rewrite loop, and possibly adds a new rule, returning true if a rule was added.
\begin{enumerate}
\item (Fast path) If $t_1=t_2$, $p$ is already a loop; record it and return false.
\item (Left) Apply Algorithm~\ref{term reduction trie algo} to $t_1$, to reduce $t_1\rightarrow t_1^\prime$ with rewrite path $p_1$.
\item (Right) Apply Algorithm~\ref{term reduction trie algo} to $t_2$, to reduce $t_2\rightarrow t_2^\prime$ with rewrite path $p_2$.
\item (Compare) Use Algorithm~\ref{rqm reduction order} to compare $t_1^\prime$ with $t_2^\prime$.
\item (Trivial) \index{trivial critical pair}If $t_1^\prime=t_2^\prime$, record a loop $p_1^{-1}\circ p\circ p_2$ with basepoint $t_1^\prime=t_2^\prime$, and return false.
\item (Smaller) If $t_2^\prime<t_1^\prime$, add the rule $t_1^\prime\Rightarrow t_2^\prime$, record a loop $p_2^{-1}\circ p^{-1}\circ p_1\circ (t_1^\prime\Rightarrow t_2^\prime)$ with basepoint $t_1^\prime$, and return true.
\item (Larger) If $t_1^\prime<t_2^\prime$, add the rule $t_2^\prime\Rightarrow t_1^\prime$, record a loop $p_1^{-1}\circ p \circ p_2 \circ (t_2^\prime\Rightarrow t_1^\prime)$ with basepoint $t_2^\prime$, and return true.
\item (Error) Otherwise, $t_1^\prime$ and $t_2^\prime$ are incomparable; signal an error.
\end{enumerate}
\end{algorithm}
Rewrite loops are not just a theoretical tool; our implementation of the Knuth-Bendix algorithm follows \cite{loggedrewriting} and \cite{homotopicalcompletion} in encoding and recording the rewrite loops that describe resolved critical pairs. This enables the computation of minimal requirements in Section~\ref{homotopy reduction}. Only local rules are subject to \index{requirement minimization}minimization, so we only record rewrite loops involving local rules. If a requirement machine instance is only to be used for generic signature queries and not minimization, rewrite loops are not recorded at all.
\paragraph{An optimization.}
Now that we know how to process a single overlap and resolve a critical pair, the next chunk of code concerns enumerating all candidate overlaps. In an arbitrary string rewrite system, we must consider all possible combinations: for every rewrite rule $u_1\Rightarrow v_1$, for every rewrite rule $u_2\Rightarrow v_2$, and for every position $i<|u_1|$, we would need to check if the corresponding subterms of $u_1$ and $u_2$ are identical. In our application, the bottom-up construction of a rewrite system from protocol components, and the partition of rewrite rules into \index{imported rule}imported rules and \index{local rule}local rules, enables an optimization where overlaps between certain pairs of rules need not be considered at all:
\begin{itemize}
\item We don't need to look for overlaps between imported rules. While an imported rule can overlap with another imported rule, all such critical pairs are trivial and do not need to be resolved again.
\item We don't need to look for overlaps between an imported rule and a local rule. An imported rule cannot overlap with a local rule.
\end{itemize}
Only two interesting pairings remain:
\begin{itemize}
\item A local rule can overlap with another local rule.
\item A local rule can overlap with an imported rule.
\end{itemize}
We now proceed to prove that this is indeed the case. First, suppose two imported rules overlap. We will consider three possibilities in turn:
\begin{itemize}
\item There is an overlap of the first kind.
\item There is an overlap of the second kind, and the second rule's left-hand side starts with an associated type symbol.
\item There is an overlap of the second kind, and the second rule's left-hand side starts with a protocol symbol.
\end{itemize}
In all three cases, we will conclude that both rules either originate from the same \index{protocol component}protocol component, or two distinct components where one imports the other. This implies that the \index{trivial critical pair}critical pair is now trivial, having been resolved by completion of that protocol component which contains the other.
In the first case, it is immediate that both rules were imported from the same protocol component for \texttt{P}:
\begin{align*}
&\assocsym{P}{A}.\assocsym{Q}{B}\\
&\assocsym{P}{A}
\end{align*}
In the second case, \texttt{P} and \texttt{Q} are either in the same protocol component, or \texttt{Q} is a protocol dependency of \texttt{P}, because we have $G_\texttt{P}\vDash\ConfReq{Self.A}{Q}$:
\begin{align*}
\assocsym{P}{A}.&\assocsym{Q}{B}\\
&\assocsym{Q}{B}.\assocsym{R}{C}
\end{align*}
The final case similarly implies that \texttt{Q} is a protocol dependency of \texttt{P}:
\begin{align*}
\assocsym{P}{A}.&\protosym{Q}\\
&\protosym{Q}.\protosym{R}
\end{align*}
Next, we claim that imported rules cannot overlap with local rules. In a generic signature rewrite system, the local rules are precisely those whose left-hand side starts with a \index{generic parameter symbol}generic parameter symbol. The left-hand side of an imported rule cannot start with, or contain, a generic parameter symbol, proving the claim. In a protocol component rewrite system, we can similarly rule out overlap of the first kind between an imported rule and a local rule, because the two rules must start with the same \index{protocol symbol}protocol or \index{associated type symbol}associated type symbol, and thus originate from the same protocol component. Now, suppose a protocol component rewrite system has an overlap of the second kind. We show that if the second rule, the one with left-hand side $\assocsym{Q}{B}.\assocsym{R}{C}$, is a local rule, then the first rule is as well:
\begin{align*}
\assocsym{P}{A}.&\assocsym{Q}{B}\\
&\assocsym{Q}{B}.\assocsym{R}{C}
\end{align*}
As before, \texttt{Q} must be a \index{protocol dependency graph}protocol dependency of \texttt{P}. But this time, we have the further assumption that \texttt{Q} belongs to the \emph{current} protocol component, so the appearance of \texttt{P} means that \texttt{P} must \emph{also} be a protocol dependency of \texttt{Q}. Thus, \texttt{P} and \texttt{Q} depend on each other, and are actually part of the same component; therefore both rules are local.
\paragraph{Another optimization.} If we fix a rule and position, we can find all overlaps involving this rule and position by performing a lookup into the rule trie, which we previously used to speed up term reduction in Section~\ref{term reduction}. This further cuts down the work in enumerating overlaps. While the underlying data structure is the same, the lookup algorithm here differs from that used by term reduction; we must enumerate all matches, instead of stopping after the first one.
Consider a set of rewrite rules having the terms $a$, $ab$, $bc$, $bd$ and $acd$ as their left-hand sides. The rule with left-hand side $ab$ has overlaps with all other rules except for $acd$. Here is the rule trie, with thick borders denoting nodes associated with rewrite rules:
\[
\begin{tikzpicture}
[level distance=10mm,
every node/.style={fill=light-gray!60,circle,inner sep=1pt},
level 1/.style={sibling distance=30mm},
level 2/.style={sibling distance=20mm},
level 3/.style={sibling distance=10mm}]
\node [rounded corners, rectangle] {\strut root}
child {node [thick, draw=black] {$\strut a$}
child {node [thick, draw=black] {$\strut b$}}
child {node {$\strut c$}
child {node [thick, draw=black] {$\strut d$}}
}
}
child {node {$\strut b$}
child {node [thick, draw=black] {$\strut c$}}
child {node [thick, draw=black] {$\strut d$}}
};
\end{tikzpicture}
\]
When checking the left-hand side $ab$ for overlaps, we perform two lookups:
\begin{itemize}
\item At position 0, we look up $ab$. Starting from the root, we encounter the rule for $a$, followed by $ab$ (which is the left-hand side of our rule itself, so we skip it). The latter node is a leaf so we end the search.
\item At position 1, we look up $b$. The node for $b$ doesn't store a rewrite rule, however, it has child nodes. We've reached the end of our input sequence, so we recursively visit all children, and find the two final overlap candidates, $bc$ and $bd$.
\end{itemize}
This new kind of trie lookup can be thought of as a \index{coroutine}coroutine or an iterator, yielding zero or more results as the search proceeds. We implement it as a higher-order function taking a callback.
\begin{algorithm}[Overlap lookup in rule trie]\label{overlap trie lookup}
Takes a term $t$, position $i$ with $0\leq i<|t|$, and a callback. For each rule $u\Rightarrow v$ where $t[i:]$ is a prefix of $u$ or $u$ is a prefix of $t[i:]$, invokes the the callback with the rule $u\Rightarrow v$.
\begin{enumerate}
\item (Initialize) Set \texttt{N} to the root node of the trie.
\item (End) If $i=|t|$, we've reached the end of the term. Perform a pre-order traversal of all child nodes of \texttt{N}, and for those children that have an associated rewrite rule, invoke the callback with that rule (this is the case where $t[i:]$ is a prefix of each $u$).
\item (Traverse) Let $s_i$ be the $i$th symbol of $t$. Let \texttt{M} be the child node of \texttt{N} associated with $s_i$. If the lookup fails, return.
\item (Child) Otherwise, if \texttt{M} has an associated rule $u\Rightarrow v$, invoke the callback with this rule (in this case, $u$ is a prefix of $t[i:]$).
\item (Advance) Set $\texttt{N}:=\texttt{M}$. Increment $i$ and go back to Step~2.
\end{enumerate}
\end{algorithm}
The next algorithm feeds the results of Algorithm~\ref{overlap trie lookup} into Algorithm~\ref{critical pair algo} to build a list of all critical pairs in the rewrite system. After \index{resolving critical pair}resolving these critical pairs, we will have to check for overlaps again, in case there are any involving the newly-added rules. To avoid repeated work, the below algorithm maintains a set of visited overlaps, so that we can avoid building and resolving a critical pair we already know has been resolved.
\begin{algorithm}[Finding overlapping rules]\label{find overlapping rule algo}
Takes a rewrite system as input, and outputs a list of critical pairs. Also queries and updates the set of visited overlaps.
\begin{enumerate}
\item (Initialize) Set $n:=0$. Let \texttt{N} be the number of local rules in the rewrite system. Initialize an empty output list.
\item (Outer check) If $n=\texttt{N}$, we're done. Return the output list.
\item (Get rule) Denote the $n$th local rule in the rewrite system by $u_1\Rightarrow v_1$ (not a typo; that's 1 not $n$). If this rule is marked as \index{left-simplified rule}\textbf{left-simplified}, \index{right-simplified rule}\textbf{right-simplified} or \index{substitution-simplified rule}\textbf{substitution-simplified}, skip it entirely and go to Step~7. Otherwise, set $i:=0$.
\item (Inner check) If $i=|u_1|$, we're done. Go to Step~9.
\item (Find overlaps) Use Algorithm~\ref{overlap trie lookup} to find all rules whose left-hand side is a prefix of the symbol range $u_1[i:]$ or vice versa.
\item (Visit) For each matching rule $u_2\Rightarrow v_2$ found above, check if this rule is marked as \textbf{left-simplified}, \textbf{right-simplified} or \textbf{substitution-simplified}. Also, check if $(u_1\Rightarrow v_1,\,u_2\Rightarrow v_2,\,i)$ is already in the visited set. In either case, move on to the next matching rule.
\item (Record) Otherwise, add $(u_1\Rightarrow v_1,\,u_2\Rightarrow v_2,\,i)$ to the visited set, and build a critical pair for this overlap using Algorithm~\ref{critical pair algo}. This produces a triple $(t_1, t_2, p)$ describing the critical pair; add this critical pair to the output list.
\item (Inner loop) Increment $i$, and go back to Step~3.
\item (Outer loop) Increment $n$, and go back to Step~2.
\end{enumerate}
\end{algorithm}
We can now describe the main loop of the Knuth-Bendix completion procedure, which repeatedly finds and resolves critical pairs until no more non-trivial critical pairs remain. This process might not terminate, and we might find ourselves discovering new critical pairs and adding new rules to resolve them, forever. To prevent an infinite loop in the case of failure, we implement a termination check; if we think we've done too much work already, we give up on constructing a covergent rewrite system. We already mentioned the \textbf{left-simplified}, \textbf{right-simplified}, and \textbf{substitution-simplified} flags a few times; they are set by the rule simplification passes, with the first two described in Section~\ref{rule reduction} and the third one in Section~\ref{subst simplification}. These passes are invoked at appropriate times in the main loop below.
\begin{algorithm}[Knuth-Bendix completion procedure]\label{knuthbendix} Takes a rewrite system as input, and outputs success or failure. On success, the rewrite system is now convergent, with all resolved critical pairs described by recorded rewrite loops. Failure occurs if we encounter a non-orientable relation, or if we trigger the termination check.
\begin{enumerate}
\item (Initialize) Clear the flag.
\item (Overlaps) Use Algorithm~\ref{find overlapping rule algo} to build a list of critical pairs.
\item (Left simpify) Invoke Algorithm~\ref{left simplification}.
\item (Resolve) For each critical pair, invoke Algorithm~\ref{add rule derived algo} and set the flag if any new rewrite rules were added.
\item (Right simplify) Invoke Algorithm~\ref{right simplification}.
\item (Substitution simplify) Invoke Algorithm~\ref{subst simplification algo}.
\item (Termination) If we exceeded the rule count, term length or concrete nesting limits, return failure.
\item (Repeat) If the flag was set, go back to Step~1. Otherwise, return success.
\end{enumerate}
\end{algorithm}
\paragraph{Termination.} \index{limitation}Our termination check is controlled by a handful of command-line flags:
\begin{itemize}
\item \IndexFlag{requirement-machine-max-rule-count} \texttt{-requirement-machine-max-rule-count} controls the maximum number of local rules. Imported rules do not count toward this total, so this is hard to hit with realistic code. The default is a maximum of 4000 local rules.
\item \IndexFlag{requirement-machine-max-rule-length} \texttt{-requirement-machine-max-rule-count} controls the maximum length of a rule's left-hand side. To compute the actual quantity, we add the length of the longest \emph{user-written} rule; so the restriction in on the relative ``growth'' and not on the length of a type parameter written by the user. The default value is 12.
\item \IndexFlag{requirement-machine-max-concrete-nesting} \texttt{-requirement-machine-max-concrete-nesting} controls the maximum nesting of concrete types, to prevent \index{substitution simplification}substitution simplification from constructing an infinite type like \texttt{G<G<G<...>>>}. This is an absolute limit, so we will arbitrarily reject user-written requirements with deeply-nested concrete types. The default value is 30.
\end{itemize}
In a runaway critical pairs scenario, it can take several seconds for completion to reach the rule count limit. The rule length limit enables earlier detection of situations where completion has clearly gone off the rails. The rule length limit being relative instead of just a total ban on terms of length 12 allows various pathological cases to succeed which would otherwise be needlessly rejected. We can type check a protocol representing the monoid $\mathbb{Z}/14\mathbb{Z}$ without fear:
\begin{Verbatim}
protocol Z14 {
associatedtype A: Z14
where Self == Self.A.A.A.A.A.A.A.A.A.A.A.A.A.A
}
\end{Verbatim}
A future improvement would be to change the concrete nesting limit to also be relative to the complexity of user-written requirements. There is no technical reason not to support deeply-nested concrete types here, it is only needed to catch runaway substitution simplification.
If completion fails when building a rewrite system for \index{requirement minimization}minimization, we have a source location associated with some protocol or generic declaration. An error is diagnosed at this source location, and we proceed with minimization producing an empty list of requirements. If completion fails on a rewrite system built from an existing generic signature or \index{protocol component}protocol component, there is no source location we can use for diagnostics; the compiler dumps the entire rewrite system and aborts with a fatal error. The latter scenario is unusual; if we successfully constructed a generic signature from user-written requirements, we should be able to build a rewrite system for it again.
\paragraph{Debugging flags}
A pair of debugging options can help us understand the operation of the completion procedure; both can be set together\footnote{With a single \texttt{-debug-requirement-machine=} flag, separating the subflags with commas.}, but be warned that they produce a large volume of output:
\begin{itemize}
\item \IndexTwoFlag{debug-requirement-machine}{completion} \texttt{-debug-requirement-machine=completion} will dump all overlapping rules and critical pairs.
\item \IndexTwoFlag{debug-requirement-machine}{add} \texttt{-debug-requirement-machine=add} will dump all rewrite rules and rewrite loops obtained while resolving critical pairs.
\end{itemize}
\newcommand{\AssocIntro}[2]{\protosym{#1}.\texttt{#2}\Rightarrow\assocsym{#1}{#2}}
\newcommand{\AssocIntroInv}[2]{\assocsym{#1}{#2}\Rightarrow\protosym{#1}.\texttt{#2}}
\newcommand{\InheritAssocIntro}[3]{\protosym{#1}.\assocsym{#2}{#3}\Rightarrow\assocsym{#1}{#3}}
\newcommand{\InheritAssocIntroInv}[3]{\assocsym{#1}{#3}\Rightarrow\protosym{#1}.\assocsym{#2}{#3}}
\newcommand{\ProtoConf}[2]{#1.\protosym{#2}\Rightarrow #1}
\newcommand{\ProtoConfInv}[2]{#1\Rightarrow #1.\protosym{#2}}
\newcommand{\ProtoInherit}[2]{\ProtoConf{\protosym{#1}}{#2}}
\newcommand{\ProtoInheritInv}[2]{\ProtoConfInv{\protosym{#1}}{#2}}
\newcommand{\FourLoopDerived}[8]{%
\begin{tikzcd}[ampersand replacement=\&]%
\\arrow[ld, Rightarrow, "#5"', bend right]\&\\
#2\arrow[rd, Rightarrow, "#6"', bend right, dashed]\&\\arrow[lu, Rightarrow,"#8"', bend right]\\
\\arrow[ru, Rightarrow, "#7"', bend right]\&
\end{tikzcd}}
\newcommand{\FourLoopDerivedOther}[8]{%
\begin{tikzcd}[ampersand replacement=\&]%
\\arrow[ld, Rightarrow, "#5"', bend right]\&\\
#2\arrow[rd, Rightarrow, "#6"', bend right]\&\\arrow[lu, Rightarrow,"#8"', bend right]\\
\\arrow[ru, Rightarrow, "#7"', bend right, dashed]\&
\end{tikzcd}}
\newcommand{\FourLoopTrivial}[8]{%
\begin{tikzcd}[ampersand replacement=\&]%
\\arrow[ld, Rightarrow, "#5"', bend right]\&\\
#2\arrow[rd, Rightarrow, "#6"', bend right]\&\\arrow[lu, Rightarrow,"#8"', bend right]\\
\\arrow[ru, Rightarrow, "#7"', bend right]\&
\end{tikzcd}}
\section{Rule Simplification}\label{rule reduction}
We impose two further conditions on our \index{convergent rewrite system}convergent rewrite system:
\begin{enumerate}
\item No rule has a left-hand side that can be reduced by any other rule.
\item No rule has a right-hand side that can be reduced by any other rule.
\end{enumerate}
Such rewrite systems are called \IndexDefinition{left-reduced rewrite system}\emph{left-reduced} or \IndexDefinition{right-reduced rewrite system}\emph{right-reduced}, respectively, or simply \emph{reduced} if both conditions are met. Any convergent rewrite system can be transformed into a reduced rewrite system with a pair of simplification passes that possibly delete and add rules.
In our implementation, we don't \emph{actually} delete rules, because we use the index of each rule as a stable reference elsewhere; instead, we set a pair of rule flags, \index{left-simplified rule}\textbf{left-simplified} and \index{right-simplified rule}\textbf{right-simplified}, and delete the rule from the \index{rule trie}\index{trie}rule trie. We've seen these flags mentioned already, so now we reveal their purpose. This will motivate the subsequent theory, setting the stage for the remaining two sections of this chapter.
\paragraph{Left simplification.} If the left-hand side of a rewrite rule $u_1\Rightarrow v_1$ can be reduced by another rewrite rule $u_2\Rightarrow v_2$, then $u_1=xu_2z$ for some $x$, $z\in A^*$, so we have an \index{overlapping rules}overlap of the first kind in the sense of Definition~\ref{overlappingrules}. Once we resolve all critical pairs, we don't need the first rule at all; we know that in a convergent rewrite system, both ways of reducing the overlap term $u_1:=xu_2z$ produce the same result:
\[
\begin{tikzcd}
&u_1
\arrow[ld, Rightarrow, bend right, "(u_1\Rightarrow v_1)"']
\arrow[rd, Rightarrow, bend left, "x(u_2\Rightarrow v_2)z"]
\\
v_1\arrow[d, Rightarrow]&&xv_2z\arrow[d, Rightarrow]\\
\ldots\arrow[rd, Rightarrow, bend right]&&\ldots\arrow[ld, Rightarrow, bend left]\\
&t^\prime&
\end{tikzcd}
\]
The \IndexDefinition{left simplification}left simplification algorithm considers the left-hand side of each rule, and marks the rule if it finds a subterm matching some other rule.
\begin{algorithm}[Left-simplify rewrite system]\label{left simplification}
Takes a rewrite system as input. Sets rule flags and modifies the rule trie as needed.
\begin{enumerate}
\item (Initialize) Let \texttt{N} be the number of local rules in our rewrite system, and set $i:=0$.
\item (Outer check) If $i=\texttt{N}$, return. Otherwise, say $u\Rightarrow v$ is the $i$th rule in \texttt{R}, and set $j:=0$.
\item (Inner check) If $j=|u|$, go to Step~8.
\item (Search) Look up $u[:j]$ in the \index{rule trie}rule \index{trie}trie, where $u[:j]$ is the suffix of $u$ of length $|u|-j$.
\item (Decide) If the trie lookup returns no results, or it returns $u\Rightarrow v$ itself (which can only happen if $j=0$, so $u[:j]=u$), go to Step~7.
\item (Mark) Otherwise, $u$ has a subterm equal to the left-hand side of some other rule. Mark $u\Rightarrow v$ as \textbf{left-simplified}, remove it from the rule trie, and go to Step~7.
\item (Inner loop) Increment $j$ and go back to Step~3.
\item (Outer loop) Increment $i$ and go back to Step~2.
\end{enumerate}
\end{algorithm}
\paragraph{Right simplification.} The other case is when we have a rule $u\Rightarrow v$ whose right-hand side $v$ is not reduced, so $v\rightarrow v^\prime$ via some \index{positive rewrite path}positive rewrite path $p_v$. Now suppose we have a positive rewrite path $x(u\Rightarrow v)z\circ p$, where $\Dst(p)$ is some reduced term $t^\prime$. If we reduce $xuz$ to $xvz$ via $x(u\Rightarrow v)z$, we have two choices on how to proceed: we can follow $p$, or reduce $xvz$ to $xv^\prime z$ via \index{whiskering}$x\star p_v \star z$. By confluence, the second choice must take us to $t^\prime$ via a positive rewrite path $p^\prime$ with $\Src(p^\prime)=xv^\prime z$ and $\Dst(p^\prime)=t^\prime$. Thus, we record a new rule $u\Rightarrow v^\prime$ that obsoletes $u\Rightarrow v$:
\[
\begin{tikzcd}
&xuz\arrow[dd, Rightarrow, "x(u\Rightarrow v)z"']\arrow[rrddd, Rightarrow, bend left, "x(u\Rightarrow v^\prime)z", dashed]&\\
&\arrow[d, Rightarrow]&\\
&xvz\arrow[dd, Rightarrow, "p"']\arrow[rrd, Rightarrow, "x\star p_v\star z"', bend left]\\
&&&xv^\prime z\arrow[lld, "p^\prime", Rightarrow, bend left]\\
&t^\prime&
\end{tikzcd}
\]
The \IndexDefinition{right simplification}right simplification algorithm outputs a right-reduced rewrite system by attempting to reduce the right-hand side of each rewrite rule. While left simplification does not need to record new rewrite rules because completion has already resolved all overlaps of the first kind, right simplification actually records new rules as well as marking existing rules as having been simplified. The new rule is related with the existing rule by a rewrite loop:
\[
\begin{tikzcd}
&v\arrow[ld, Rightarrow, "(v\Rightarrow u)"', bend right]&\\
u\arrow[rr, Rightarrow, "(u\Rightarrow v^\prime)"', dashed, bend right]&&v^\prime\arrow[lu, Rightarrow, "p_v^{-1}"', bend right]
\end{tikzcd}
\]
\begin{algorithm}[Right-simplify rewrite system]\label{right simplification}
Takes a rewrite system as input, and modifies its rules as needed.
\begin{enumerate}
\item (Initialize) Let \texttt{N} be the number of local rules in our rewrite system, and set $i:=0$.
\item (Check) If $i=\texttt{N}$, return. Otherwise, let $u\Rightarrow v$ be the $i$th local rule.
\item (Reduce) Apply Algorithm~\ref{term reduction trie algo} to $v$ to get a rewrite path $p_v$. If $p_v$ is the \index{empty rewrite path}empty rewrite path $1_{v}$, the right-hand side $v$ is already reduced, so go to Step~7.
\item (Record) Let $v^\prime=\Dst(p_v)$. Add a new rewrite rule $u\Rightarrow v^\prime$ to the list of local rules, and insert it into the rule trie with the key $u$, replacing the old rule $u\Rightarrow v$.
\item (Relate) Add the rewrite loop $(u\Rightarrow v)\circ p\circ(v^\prime\Rightarrow u)$ with basepoint $u$, relating the old rule $u\Rightarrow v$ with the new rule $u\Rightarrow v^\prime$.
\item (Mark) Mark the old rule as \textbf{right-simplified}.
\item (Loop) Increment $i$ and go back to Step~2.
\end{enumerate}
\end{algorithm}
Our justification for the validity of these passes worked from the assumption that we had a convergent rewrite system; that is, that completion had already been performed. In practice, Algorithm~\ref{knuthbendix} repeatedly runs both passes during completion, once per round of \index{critical pair}critical pair resolution. This is advantageous, because we can subsequently avoid considering overlaps that involve simplified rules. This strategy remains sound as long as we perform left simplification after computing critical pairs, but \emph{before} resolving them, which might add new rules. This narrows the candidates for left simplification to those rules whose overlaps have already been considered. As for the right simplification pass, it is actually fine to run it at any point; we choose to run it after \index{resolving critical pair}resolving critical pairs.
\paragraph{Related concepts.}
We previously saw in Section~\ref{minimal requirements} that the same-type requirements in a generic signature are subject to similar conditions of being left-reduced and right-reduced. There is a connection here, because as we will see in Section~\ref{requirement builder}, the minimal requirements of a generic signature are ultimately constructed from the rules of a reduced rewrite system. However, there are a few notational differences:
\begin{itemize}
\item The roles of ``left'' and ``right'' are reversed because requirements use a different convention; in a reduced same-type requirement $\FormalReq{U == V}$, we have $\texttt{U} < \texttt{V}$, whereas in a rewrite rule $u\Rightarrow v$ we have $v<u$.
\item Reduced same-type requirements have the ``shortest'' distance between the left-hand and right-hand side, so if \texttt{T}, \texttt{U} and \texttt{V} are all equivalent and $\texttt{T}<\texttt{U}<\texttt{V}$, the corresponding requirements are $\FormalReq{T == U}$, $\FormalReq{U == V}$. On the other hand, if we have three terms $t$, $u$ and $v$ with $t<u<v$, then the two corresponding rewrite rules would be $u\Rightarrow t$, $v\Rightarrow t$.
\end{itemize}
These differences are explained by the original \Index{GenericSignatureBuilder@\texttt{GenericSignatureBuilder}}\texttt{GenericSignatureBuilder} minimization algorithm, described as finding a minimum \index{spanning tree}spanning tree for a graph of connected components. The notion of reduced requirement output by this algorithm became part of the Swift stable \index{ABI}ABI. In Section~\ref{requirement builder} we show that a list of rewrite rules in a reduced rewrite system defines a list of reduced requirements via a certain transformation.
What we call reduced rewrite systems are sometimes ``normalized'', ``canonical'', or ``inter-reduced'' in the literature. Our rewrite system also implements a third \emph{substitution simplification} pass for rewrite system simplification. Substitution simplification reduces substitution terms appearing in superclass, concrete type and concrete conformance symbols. We will discuss it in Chapter~\ref{propertymap}.
\section{Associated Types}\label{critical pairs}
A conformance rule $t.\protosym{P}\Rightarrow t$ always overlaps with an associated type introduction rule $\protosym{P}.\texttt{A}\Rightarrow\assocsym{P}{A}$, and resolving this critical pair defines a rule $t.\texttt{A}\Rightarrow t.\assocsym{P}{A}$ (unless something further reduces the right-hand side). These rewrite rules reduce those terms representing \index{unbound type parameter}unbound type parameters to \index{bound type parameter}bound type parameters. Thus, we will see how the bound and unbound type parameters from Section~\ref{reducedtypes} manifest in our rewrite system.
\begin{example}\label{assoc type completion example}
We're going to look at this pair of protocol declarations, and the \index{protocol generic signature}protocol generic signature $G_\texttt{P}$:
\begin{Verbatim}
protocol Q {
associatedtype B
}
protocol P {
associatedtype A: Q
}
\end{Verbatim}
Protocol \texttt{P} has an \index{associated conformance requirement}associated conformance requirement $\ConfReq{Self.[P]A}{Q}_\texttt{P}$, and $G_\texttt{P}$ has a conformance requirement $\ConfReq{\ttgp{0}{0}}{P}$, so the \index{protocol dependency graph}protocol dependency graph has the two edges $G_\texttt{P}\prec\texttt{P}$ and $\texttt{P}\prec\texttt{Q}$. We first build a rewrite system for \texttt{Q}. The rewrite system for $G_\texttt{P}$ imports rules from \texttt{P} and \texttt{Q}:
\begin{flalign*}
\toprule
&\AssocIntro{Q}{B}\tag{1}&\\
\midrule
&\AssocIntro{P}{A}\tag{2}&\\
&\ProtoConf{\assocsym{P}{A}}{Q}\tag{3}&\\
&\assocsym{P}{A}.\texttt{B}\Rightarrow\assocsym{P}{A}.\assocsym{Q}{B}\tag{*4}&\\
\midrule
&\ProtoConf{\ttgp{0}{0}}{P}\tag{5}&\\
&\ttgp{0}{0}.\texttt{A}\Rightarrow\ttgp{0}{0}.\assocsym{P}{A}\tag{*6}&\\
\bottomrule
\end{flalign*}
We can categorize these rewrite rules as follows:
\begin{itemize}
\item Associated type introduction rules: (1) and (2).
\item Conformance requirements: (3) and (5).
\item Rules added by completion are indicated with an asterisk: (*4) and (*6).
\end{itemize}
We omit the identity conformance rules $\ProtoConf{\protosym{Q}}{Q}$ and $\ProtoConf{\protosym{P}}{P}$; in this example they would only clutter the presentation. They will serve a useful purpose later, in Example~\ref{proto assoc rule}.
We now go through the construction step by step. Protocol \texttt{Q} does not depend on any other protocols. The rewrite system for \texttt{Q} is just rule (1):
\begin{gather*}
\AssocIntro{Q}{B}\tag{1}
\end{gather*}
Protocol \texttt{P} imports the single rule of \texttt{Q}, and adds rules (2) and (3):
\begin{gather*}
\AssocIntro{P}{A}\tag{2}\\
\ProtoConf{\assocsym{P}{A}}{Q}\tag{3}
\end{gather*}
We need to check the left-hand side of rules (2) and (3) for overlaps with other rules. Rule (2) does not overlap with any other rules. Rule (3) overlaps with rule (1) on the term $\assocsym{P}{A}.\protosym{Q}.\texttt{B}$:
\begin{align*}
\assocsym{P}{A}.&\protosym{Q}\\
&\protosym{Q}.\texttt{B}
\end{align*}
Rule (3) is local to \texttt{P}, while (1) was imported from \texttt{Q}. The two sides of the critical pair reduce to $\assocsym{P}{A}.\texttt{B}$ and $\assocsym{P}{A}.\assocsym{Q}{B}$. Resolving this critical pair introduces rule (*4):
\[
\assocsym{P}{A}.\texttt{B}\Rightarrow\assocsym{P}{A}.\assocsym{Q}{B}\tag{*4}
\]
We also record a rewrite loop that defines rule (*4) via rules (3) and (1):
\[
\begin{tikzcd}
&\assocsym{P}{A}.\protosym{Q}.\texttt{B}
\arrow[ld, Rightarrow, bend right, "(\ProtoConf{\assocsym{P}{A}}{Q}).\texttt{B}"']\\
\assocsym{P}{A}.\texttt{B}\arrow[rr, Rightarrow, bend right, dashed, "(\assocsym{P}{A}.\texttt{B}\Rightarrow\assocsym{P}{A}.\assocsym{Q}{B})"']
&&
\assocsym{P}{A}.\assocsym{Q}{B}\arrow[lu, Rightarrow, bend right, "\assocsym{P}{A}.(\AssocIntroInv{Q}{B})"']
\end{tikzcd}
\]
Once again, we check for overlaps in the left-hand sides of our local rules---now (2), (3) and (4). We see that no more critical pairs remain, and we have a convergent rewrite system for \texttt{P}.
Finally, we build the rewrite system for $G_\texttt{P}$. We import all rules from \texttt{Q} and \texttt{P}, and add one new local rule corresponding to the conformance requirement $\ConfReq{\ttgp{0}{0}}{P}$:
\[
\ProtoConf{\ttgp{0}{0}}{P}\tag{5}
\]
We need to check the left-hand side of rule (5) for overlaps with other rules. Indeed, rule (5) overlaps with rule (2) on the term
$\ttgp{0}{0}.\protosym{P}.\texttt{A}$:
\begin{align*}
\ttgp{0}{0}.&\protosym{P}\\
&\protosym{P}.\texttt{A}
\end{align*}
Resolving this critical pair introduces rule (*6):
\[
\ttgp{0}{0}.\texttt{A}\Rightarrow\ttgp{0}{0}.\assocsym{P}{A}\tag{*6}
\]
We also record a rewrite loop that defines rule (*6) via rules (5) and (2):
\[
\begin{tikzcd}
&\ttgp{0}{0}.\protosym{P}.\texttt{A}\arrow[ld, Rightarrow, "(\ProtoConf{\ttgp{0}{0}}{P}).\texttt{A}"', bend right]\\
\ttgp{0}{0}.\texttt{A}\arrow[rr, Rightarrow, "(\ttgp{0}{0}.\texttt{A}\Rightarrow\ttgp{0}{0}.\assocsym{P}{A})"', bend right, dashed]&&
\ttgp{0}{0}.\assocsym{P}{A}\arrow[ul, Rightarrow, "\ttgp{0}{0}.(\AssocIntroInv{P}{A})"', bend right]
\end{tikzcd}
\]
At this point, there might be overlaps involving one of rule (5) or (*6); a quick check shows none remain, so we have a convergent rewrite system for $G_\texttt{P}$.
Now, we get to the interesting part. Consider these two type parameters of $G_\texttt{P}$, and their corresponding \index{type-like term}type-like terms:
\begin{enumerate}
\item The unbound type parameter \texttt{\ttgp{0}{0}.A.B}, and term $\ttgp{0}{0}.\texttt{A}.\texttt{B}$.
\item The bound type parameter \texttt{\ttgp{0}{0}.[P]A.[Q]B}, and term $\ttgp{0}{0}.\assocsym{P}{A}.\assocsym{Q}{B}$.
\end{enumerate}
The second term is reduced, so the first term must reduce to the second term. Term reduction outputs a \index{positive rewrite path}positive rewrite path $p$ with $\Src(p)=\ttgp{0}{0}.\texttt{A}.\texttt{B}$ and $\Dst(p)=\ttgp{0}{0}.\assocsym{P}{A}.\assocsym{Q}{B}$. This path involves rules (4) and (6) added by completion:
\[
p := (\ttgp{0}{0}.\texttt{A}\Rightarrow\ttgp{0}{0}.\assocsym{P}{A}).\texttt{B} \circ \ttgp{0}{0}.(\assocsym{P}{A}.\texttt{B}\Rightarrow\assocsym{P}{A}.\assocsym{B}{Q})
\]
Here is a diagram for $p$:
\[
\begin{tikzcd}[column sep=huge]
\ttgp{0}{0}.\texttt{A}.\texttt{B}\arrow[r, Rightarrow]&
\ttgp{0}{0}.\assocsym{P}{A}.\texttt{B}\arrow[r, Rightarrow]&
\ttgp{0}{0}.\assocsym{P}{A}.\assocsym{Q}{B}
\end{tikzcd}
\]
There is a ``telescoping'' effect, as term reduction processes the name symbols from left to right, replacing them with associated type symbols. As an aside, if we have an \emph{invalid} type parameter, such as \texttt{\ttgp{0}{0}.A.A}, the term reduces to $\ttgp{0}{0}.\assocsym{P}{A}.\texttt{A}$ but no further; the final name symbol \texttt{A} cannot be ``resolved'' because the type parameter \texttt{\ttgp{0}{0}.A} does not \emph{have} a member type named \texttt{A}.
The type-like term $\ttgp{0}{0}.\texttt{A}.\texttt{B}$ reduces to $\ttgp{0}{0}.\assocsym{P}{A}.\assocsym{Q}{B}$ because the unbound type parameter \texttt{\ttgp{0}{0}.A.B} is equivalent to the bound type parameter \texttt{\ttgp{0}{0}.[P]A.[Q]B}, and the latter is the reduced type of the former. The equivalence follows because we can derive a same-type requirement, and the left-hand side of this same-type requirement is the reduced type because no smaller type parameter can be shown to be equivalent:
\[G_\texttt{P}\vDash\FormalReq{\ttgp{0}{0}.[P]A.[Q]B == \ttgp{0}{0}.A.B}\]
Here is one possible derivation for this same-type requirement:
\begin{gather*}
\vdash\ConfReq{\ttgp{0}{0}}{P}\tag{1}\\
(1)\vdash\FormalReq{\ttgp{0}{0}.[P]A == \ttgp{0}{0}.A}\tag{2}\\
(2)\vdash\FormalReq{\ttgp{0}{0}.A == \ttgp{0}{0}.[P]A}\tag{3}\\
\vdash\ConfReq{Self.[P]A}{Q}_\texttt{P}\tag{4}\\
(1),\,(4)\vdash\ConfReq{\ttgp{0}{0}.[P]A}{Q}\tag{5}\\
(2),\,(5)\vdash\FormalReq{\ttgp{0}{0}.A.B == \ttgp{0}{0}.[P]A.B}\tag{6}\\
(6)\vdash\FormalReq{\ttgp{0}{0}.[P]A.B == \ttgp{0}{0}.A.B}\tag{7}\\
(4)\vdash\FormalReq{\ttgp{0}{0}.[P]A.[Q]B == \ttgp{0}{0}.[P]A.B}\tag{8}\\
(8),\,(7)\vdash\FormalReq{\ttgp{0}{0}.[P]A.[Q]B == \ttgp{0}{0}.A.B}\tag{9}
\end{gather*}
By Theorem~\ref{derivation to path swift}, we can transform this derivation into a rewrite path from $\ttgp{0}{0}.\texttt{A}.\texttt{B}$ to $\ttgp{0}{0}.\assocsym{P}{A}.\assocsym{Q}{B}$, involving the initial rewrite rules only. We call this rewrite path $p^\prime$:
\begin{multline*}
p^\prime := (\ProtoConfInv{\ttgp{0}{0}}{P}).\texttt{A}.\texttt{B} \circ \ttgp{0}{0}.(\AssocIntro{P}{A}).\texttt{B}\\
\circ \ttgp{0}{0}.(\ProtoConfInv{\assocsym{P}{A}}{Q}).\texttt{B} \circ \ttgp{0}{0}.\assocsym{P}{A}.(\AssocIntro{Q}{B})
\end{multline*}
Unlike $p$, $p^\prime$ is \emph{not} a positive rewrite path, because the first and third steps are negative; each one applies a conformance rule backwards. We can visualize $p^\prime$ as a path in the rewrite graph, with the \index{negative rewrite step}negative rewrite steps going up:
\begin{center}
\begin{tikzcd}[column sep=small]
&\ttgp{0}{0}.\protosym{P}.\texttt{A}.\texttt{B}\arrow[rd, Rightarrow, bend left]
&&\ttgp{0}{0}.\assocsym{P}{A}.\protosym{Q}.\texttt{B}\arrow[rd, Rightarrow, bend left]\\
\ttgp{0}{0}.\texttt{A}.\texttt{B}\arrow[ru, Rightarrow, bend left]&&
\ttgp{0}{0}.\assocsym{P}{A}.\texttt{B}\arrow[ru, Rightarrow, bend left]&&
\ttgp{0}{0}.\assocsym{P}{A}.\assocsym{Q}{B}
\end{tikzcd}
\end{center}
We now have two \index{parallel rewrite paths}parallel rewrite paths: $p$ (from term reduction), and $p^\prime$ (constructed from our derivation). Their composition $p^\prime\circ p^{-1}$ is a rewrite loop; we can represent it as a diagram, with rules (*4) and (*6) indicated by dashed arrows:
\begin{center}
\begin{tikzcd}[column sep=small]
&\ttgp{0}{0}.\protosym{P}.\texttt{A}.\texttt{B}\arrow[ld, Rightarrow, bend right]
&&\ttgp{0}{0}.\assocsym{P}{A}.\protosym{Q}.\texttt{B}\arrow[ld, Rightarrow, bend right]\\
\ttgp{0}{0}.\texttt{A}.\texttt{B}\arrow[rr, Rightarrow, bend right, dashed]&&
\ttgp{0}{0}.\assocsym{P}{A}.\texttt{B}\arrow[lu, Rightarrow, bend right]\arrow[rr, Rightarrow, bend right, dashed]&&
\ttgp{0}{0}.\assocsym{P}{A}.\assocsym{Q}{B}\arrow[lu, Rightarrow, bend right]
\end{tikzcd}
\end{center}
Recall the pair of rewrite loops defined by the critical pairs of our rewrite system. We take the first rewrite loop, and \index{whiskering}whisker it on the right by \texttt{B}; then, we whisker the second rewrite loop on the left by \ttgp{0}{0}. Now, the two rewrite loops visit the common term $\ttgp{0}{0}.\assocsym{P}{A}.\texttt{B}$. Informally, we can ``glue'' them together at this point, and then we get $p^\prime\circ p^{-1}$.
In fact, given any two parallel rewrite paths in a \index{convergent rewrite system}convergent rewrite system, we can always ``tile'' the two-dimensional space between them if we take the finite set of rewrite loops generated by \index{resolving critical pair}resolving critical pairs, and glue them together along common edges or vertices after putting the loops ``in context'' via whiskering. We will develop this idea further in Chapter~\ref{rqm minimization}, but here is a thought to ruminate on in the meantime:
\begin{quote}
Terms, generated by a finite set of symbols, are the zero-dimensional objects in the rewrite graph. Rewrite paths, generated by a finite set of rewrite rules, define an equivalence relation on terms; they are the one-dimensional objects. Rewrite loops, generated by a finite set of critical pairs, define an equivalence relation on paths; they are the two-dimensional objects.
\end{quote}
An equivalence relation on paths is called a \emph{homotopy relation}.
\end{example}
\begin{example}\label{overlap of first kind example}
Let's build on our previous example and look at how unbound type parameters reduce when they appear in requirements. We add a new protocol \texttt{R}, and declare a \index{constrained extension}constrained \index{protocol extension}protocol extension of \texttt{P} where \texttt{Self.A.B} conforms to \texttt{R}:
\begin{Verbatim}
protocol R {}
protocol Q {
associatedtype B
}
protocol P {
associatedtype A: Q
}
extension P where Self.A.B: R {}
\end{Verbatim}
When type checking these declarations, we need to build a generic signature for this \index{protocol extension}protocol extension. We start with requirement $\ConfReq{\ttgp{0}{0}}{P}$ from the \index{extended type}extended type, and add the user-written requirement $\ConfReq{\ttgp{0}{0}.A.B}{R}$. The rewrite system looks like the previous example but with two new rules:
\begin{flalign*}
\toprule
&\ProtoConf{\ttgp{0}{0}.\texttt{A}.\texttt{B}}{R}\tag{7}&\\
&\ProtoConf{\ttgp{0}{0}.\assocsym{P}{A}.\assocsym{Q}{B}}{R}\tag{8*}&\\
\bottomrule
\end{flalign*}
Rule (7) corresponds to the user-written requirement. Rule (*8) is added by completion, resolving the overlap between rule (7) and (6) on the term $\ttgp{0}{0}.\texttt{A}.\texttt{B}.\protosym{R}$:
\begin{align*}
&\ttgp{0}{0}.\texttt{A}.\texttt{B}.\protosym{R}\\
&\ttgp{0}{0}.\texttt{A}
\end{align*}
We record a rewrite loop defining rule (*8) via rule (4), (6) and (7):
\[
\begin{tikzcd}
&\ttgp{0}{0}.\texttt{A}.\texttt{B}.\protosym{R}
\arrow[ld, Rightarrow, bend right, "(\ttgp{0}{0}.\texttt{A}\Rightarrow\ttgp{0}{0}.\assocsym{P}{A}).\texttt{B}.\protosym{R}"']\\
\ttgp{0}{0}.\assocsym{P}{A}.\texttt{B}.\protosym{R}
\arrow[dd, Rightarrow, "\ttgp{0}{0}.(\assocsym{P}{A}.\texttt{B}\Rightarrow\assocsym{P}{A}.\assocsym{Q}{B}).\protosym{R}"']&&
\ttgp{0}{0}.\texttt{A}.\texttt{B}
\arrow[lu, Rightarrow, bend right, "(\ProtoConfInv{\ttgp{0}{0}.\texttt{A}.\texttt{B}}{R})"']
\\
&&
\ttgp{0}{0}.\assocsym{P}{A}.\texttt{B}
\arrow[u, Rightarrow, "(\ttgp{0}{0}.\assocsym{P}{A}\Rightarrow\ttgp{0}{0}.\texttt{A}).\texttt{B}"']
\\
\ttgp{0}{0}.\assocsym{P}{A}.\assocsym{Q}{B}.\protosym{R}
\arrow[rr, Rightarrow, dashed, bend right, "(\ProtoConf{\ttgp{0}{0}.\assocsym{P}{A}.\assocsym{Q}{B}}{R})"']
&&
\ttgp{0}{0}.\assocsym{P}{A}.\assocsym{Q}{B}
\arrow[u, Rightarrow, "\ttgp{0}{0}.(\assocsym{P}{A}.\assocsym{Q}{B}\Rightarrow\assocsym{P}{A}.\texttt{B})"']&&
\end{tikzcd}
\]
Note that this was an overlap of the first kind, so rule (7) is now marked \index{left-simplified rule}\textbf{left-simplified}. Thus, rule (*8) completely supercedes rule (7). Rule (*8) survives minimization and maps to the requirement $\ConfReq{\ttgp{0}{0}.[P]A.[Q]B}{R}$, which appears in the generic signature that we output for this protocol extension:
\begin{quote}
\begin{verbatim}
<τ_0_0 where τ_0_0: P, τ_0_0.[P]A.[Q]B: R>
\end{verbatim}
\end{quote}
If our compiler invocation is generating a \index{serialized module}serialized module, we serialize the protocol extension's generic signature and do not compute it again when this module is imported in the future. We might still need a rewrite system for generic signature queries though, in which scenario we build a ``second-generation'' rewrite system:
\begin{enumerate}
\item We originally built a convergent rewrite system from the user-written requirements of the protocol extension.
\item After finding a minimal set of rules, we convert minimal rules to requirements, and serialize the resulting \index{generic signature}generic signature.
\item In a subsequent compiler invocation, we deserialize this generic signature.
\item Then, we build a convergent rewrite system from the requirements of this generic signature; rule (8) is now one of our initial rules.
\end{enumerate}
The rewrite system after step (1) is equivalent to that after step (4). That is, if we ignore \textbf{left-simplified} and \textbf{right-simplified} rules, both will have the same rules, up to permutation. (We can't completely prove this fact, because \index{requirement minimization}minimization is tricky. But this is the intended invariant here.)
\end{example}
\begin{example}
Now we're going to change \texttt{Q} to require that \texttt{B} conform to \texttt{R}. Intuitively, the conformance requirement $\ConfReq{\ttgp{0}{0}.A.B}{R}$ in the protocol extension's \texttt{where} clause is now redundant, because every \texttt{B} (of a type conforming to \texttt{Q}) now conforms to \texttt{R}:
\begin{Verbatim}
protocol R {}
protocol Q {
associatedtype B: R
}
protocol P {
associatedtype A: Q
}
extension P where Self.A.B: R {}
\end{Verbatim}
The rewrite system for building the protocol extension's generic signature starts out as in the previous example, but now one more imported rule comes from protocol \texttt{Q}:
\[\ProtoConf{\assocsym{Q}{B}}{R}\]
The conformance rule $\ProtoConf{\ttgp{0}{0}.\texttt{A}.\texttt{B}}{R}$ overlaps with $\ttgp{0}{0}.\texttt{A}\Rightarrow\ttgp{0}{0}.\assocsym{P}{A}$ on the term $\ttgp{0}{0}.\texttt{A}.\texttt{B}.\protosym{R}$, as before. This is an overlap of the first kind, so the original rule $\ProtoConf{\ttgp{0}{0}.\texttt{A}.\texttt{B}}{R}$ is marked \IndexDefinition{left-simplified rule}\textbf{left-simplified}. This time though, the critical pair is \index{trivial critical pair}trivial; both sides already reduce to $\ttgp{0}{0}.\assocsym{P}{A}.\assocsym{Q}{B}$:
\[
\begin{tikzcd}
&\ttgp{0}{0}.\texttt{A}.\texttt{B}.\protosym{R}
\arrow[ld, Rightarrow, bend right, "(\ttgp{0}{0}.\texttt{A}\Rightarrow\ttgp{0}{0}.\assocsym{P}{A}).\texttt{B}.\protosym{R}"']\\
\ttgp{0}{0}.\assocsym{P}{A}.\texttt{B}.\protosym{R}
\arrow[dd, Rightarrow, "\ttgp{0}{0}.(\assocsym{P}{A}.\texttt{B}\Rightarrow\assocsym{P}{A}.\assocsym{Q}{B}).\protosym{R}"']&&
\ttgp{0}{0}.\texttt{A}.\texttt{B}
\arrow[lu, Rightarrow, bend right, "(\ProtoConfInv{\ttgp{0}{0}.\texttt{A}.\texttt{B}}{R})"']
\\
&&
\ttgp{0}{0}.\assocsym{P}{A}.\texttt{B}
\arrow[u, Rightarrow, "(\ttgp{0}{0}.\assocsym{P}{A}\Rightarrow\ttgp{0}{0}.\texttt{A}).\texttt{B}"']
\\
\ttgp{0}{0}.\assocsym{P}{A}.\assocsym{Q}{B}.\protosym{R}
\arrow[rr, Rightarrow, bend right, "\ttgp{0}{0}.\assocsym{P}{A}.(\ProtoConf{\assocsym{Q}{B}}{R})"']
&&
\ttgp{0}{0}.\assocsym{P}{A}.\assocsym{Q}{B}
\arrow[u, Rightarrow, "\ttgp{0}{0}.(\assocsym{P}{A}.\assocsym{Q}{B}\Rightarrow\assocsym{P}{A}.\texttt{B})"']&&
\end{tikzcd}
\]
\end{example}
\begin{example}\label{two protocols same assoc}
Our next goal is to understand what happens when a type parameter conforms to two unrelated protocols that both declare an associated type with the same name:
\begin{Verbatim}
protocol P1 {
associatedtype A
}
protocol P2 {
associatedtype A
}
\end{Verbatim}
We're going to look at this generic signature:
\begin{quote}
\texttt{<\ttgp{0}{0} where \ttgp{0}{0}:~P1, \ttgp{0}{0}:~P2>}
\end{quote}
Every \index{equivalence class}equivalence class of type parameters can be uniquely identified by some \index{unbound type parameter}unbound type parameter. In the above, the type parameters \texttt{\ttgp{0}{0}.[P1]A} and \texttt{\ttgp{0}{0}.[P2]A} must therefore be equivalent to \texttt{\ttgp{0}{0}.A}. We're going to see how this works out in the rewrite system. Here is the convergent rewrite system for the above generic signature:
\begin{flalign*}
\toprule
&\AssocIntro{P1}{A}\tag{1}&\\
\midrule
&\AssocIntro{P2}{A}\tag{2}&\\
\midrule
&\ProtoConf{\ttgp{0}{0}}{P1}\tag{3}&\\
&\ProtoConf{\ttgp{0}{0}}{P2}\tag{4}&\\
&\ttgp{0}{0}.\texttt{A}\Rightarrow\ttgp{0}{0}.\assocsym{P1}{A}\tag{*5}&\\
&\ttgp{0}{0}.\assocsym{P2}{A}\Rightarrow\ttgp{0}{0}.\assocsym{P1}{A}\tag{*6}&\\
\bottomrule
\end{flalign*}
Rules (1) and (2) are imported from \texttt{P1} and \texttt{P2}, and rules (3) and (4) correspond to the conformance requirements $\ConfReq{\ttgp{0}{0}}{P1}$ and $\ConfReq{\ttgp{0}{0}}{P2}$. Completion also adds two additional rules. Rule (*5) is added when resolving the overlap between rule (3) and rule (1), exactly as in Example~\ref{assoc type completion example}.
Rule (4) overlaps with rule (2) on the term $\ttgp{0}{0}.\protosym{P2}.\texttt{A}$:
\begin{align*}
\ttgp{0}{0}.&\protosym{P2}\\
&\protosym{P2}.\texttt{A}
\end{align*}
This gives us rule (*6), which has a new form we haven't seen before. One side of the critical pair reduces to $\ttgp{0}{0}.\assocsym{P2}{A}$, and the other reduces to $\ttgp{0}{0}.\assocsym{P1}{A}$ via rule (5).
We record a rewrite loop defining rule (*6) via (2), (4) and (5):
\[
\FourLoopDerived%
{\ttgp{0}{0}.\protosym{P2}.\texttt{A}}%
{\ttgp{0}{0}.\assocsym{P2}{A}}%
{\ttgp{0}{0}.\assocsym{P1}{A}}%
{\ttgp{0}{0}.\texttt{A}}%
{\ttgp{0}{0}.(\AssocIntro{P2}{A})}%
{(\ttgp{0}{0}.\assocsym{P2}{A}\Rightarrow \ttgp{0}{0}.\assocsym{P1}{A})}%
{(\ttgp{0}{0}.\assocsym{P1}{A}\Rightarrow \ttgp{0}{0}.\texttt{A})}%
{(\ProtoConf{\ttgp{0}{0}}{P2}}
\]
We can ``glue'' the rewrite loops defining rule (*5) and (*6) together into a single diagram:
\[
\begin{tikzcd}
&\ttgp{0}{0}.\protosym{P2}.\texttt{A}\arrow[ld, Rightarrow, bend right]&\\
\ttgp{0}{0}.\assocsym{P2}{A}\arrow[rd, Rightarrow, bend right, dashed]&&\ttgp{0}{0}.\texttt{A}\arrow[lu, Rightarrow, bend right]\\
&\ttgp{0}{0}.\assocsym{P1}{A}\arrow[ru, Rightarrow, bend right, dashed]\arrow[rd, Rightarrow, bend right]&\\
&&\ttgp{0}{0}.\protosym{P1}.\texttt{A}\arrow[uu, Rightarrow, bend right]
\end{tikzcd}
\]
The two dashed arrows are rules (*5) and (*6). The solid arrows indicate a rewrite path joining $\ttgp{0}{0}.\assocsym{P1}{A}$ with $\ttgp{0}{0}.\assocsym{P2}{A}$ involving the initial rules only. This rewrite path corresponds to the following derivation:
\begin{gather*}
\vdash\ConfReq{\ttgp{0}{0}}{P1}\tag{1}\\
(1)\vdash\FormalReq{\ttgp{0}{0}.[P1]A == \ttgp{0}{0}.A}\tag{2}\\
\vdash\ConfReq{\ttgp{0}{0}}{P2}\tag{3}\\
(3)\vdash\FormalReq{\ttgp{0}{0}.[P2]A == \ttgp{0}{0}.A}\tag{4}\\
(4)\vdash\FormalReq{\ttgp{0}{0}.\texttt{A} == \ttgp{0}{0}.[P2]A}\tag{5}\\
(2),\,(5)\vdash\FormalReq{\ttgp{0}{0}.[P1]A == \ttgp{0}{0}.[P2]A}\tag{6}
\end{gather*}
Indeed, we see that the equivalence class with reduced type \texttt{\ttgp{0}{0}.[P1]A} contains three type parameters. Here they are with corresponding terms, in type parameter order. In this case, the reduced type and the reduced term coincide:
\begin{quote}
\begin{tabular}{ll}
\textbf{Type}&\textbf{Term}\\
\toprule
\texttt{\ttgp{0}{0}.[P1]A}&$\ttgp{0}{0}.\assocsym{P1}{A}$\\
\texttt{\ttgp{0}{0}.[P2]A}&$\ttgp{0}{0}.\assocsym{P2}{A}$\\
\texttt{\ttgp{0}{0}.A}&$\ttgp{0}{0}.\texttt{A}$
\end{tabular}
\end{quote}
\end{example}
\section{More Critical Pairs}
\begin{example}\label{protocol inheritance completion example}
Consider this protocol inheritance hierarchy, where \texttt{Bot} inherits from \texttt{Mid}, which inherits from \texttt{Top}, and \texttt{Mid} declares an associated type:
\begin{Verbatim}
protocol Top {}
protocol Mid: Top {
associatedtype A
}
protocol Bot: Mid {}
\end{Verbatim}
We're going to examine the rewrite system for the generic signature $G_\texttt{Bot}$, made up rules imported from \texttt{Mid} and \texttt{Bot}, and the local rules (as before, we omit the identity conformance rules):
\begin{flalign*}
\toprule
&\AssocIntro{Mid}{A}\tag{1}&\\
&\ProtoInherit{Mid}{Top}\tag{2}&\\
\midrule
&\AssocIntro{Bot}{A}\tag{3}&\\
&\ProtoInherit{Bot}{Mid}\tag{4}&\\
&\protosym{Bot}.\assocsym{Mid}{A}\Rightarrow\assocsym{Bot}{A}\tag{*5}&\\
&\ProtoInherit{Bot}{Top}\tag{*6}&\\
\midrule
&\ProtoConf{\ttgp{0}{0}}{Bot}\tag{7}&\\
&\ProtoConf{\ttgp{0}{0}}{Mid}\tag{*8}&\\
&\ProtoConf{\ttgp{0}{0}}{Top}\tag{*9}&\\
&\ttgp{0}{0}.\texttt{A}\Rightarrow\ttgp{0}{0}.\assocsym{Bot}{A}\tag{*10}&\\
&\ttgp{0}{0}.\assocsym{Mid}{A}\Rightarrow\ttgp{0}{0}.\assocsym{Bot}{A}\tag{*11}&\\
\bottomrule
\end{flalign*}
We're going to focus on a handful of interesting rules:
\begin{itemize}
\item While \texttt{Bot} does declare any associated types, it inherits \texttt{A} from \texttt{Mid}; rule (3) is the \index{inherited associated type rule}inherited associated type introduction rule for \texttt{A}.
\item Rules (*5) and (*11) are added by completion as are a consequence of the inherited associated type introduction rule.
\item Rules (*6), (*8) and (*9) are also added by completion. They express the ``transitive'' conformance requirements $\ConfReq{Self}{Top}_\texttt{Bottom}$, $\ConfReq{\ttgp{0}{0}}{Top}$ and $\ConfReq{\ttgp{0}{0}}{Mid}$.
\end{itemize}
Rule (4) overlaps with rule (1) on the term $\protosym{Bot}.\protosym{Mid}.\texttt{A}$:
\begin{align*}
\protosym{Bot}.&\protosym{Mid}\\
&\protosym{Mid}.\texttt{A}
\end{align*}
Resolving this critical pair records a rewrite loop defining rule (*5) via rule (1), (3) and (4):
\[
\FourLoopDerived%
{\protosym{Bot}.\protosym{Mid}.\texttt{A}}%
{\protosym{Bot}.\assocsym{Mid}{A}}%
{\assocsym{Bot}{A}}%
{\protosym{Bot}.\texttt{A}}%
{\protosym{Bot}.(\AssocIntro{Mid}{A})}%
{(\protosym{Bot}.\assocsym{Mid}{A}\Rightarrow\assocsym{Bot}{A})}%
{(\AssocIntroInv{Bot}{A})}%
{(\ProtoInheritInv{Bot}{Mid}).\texttt{A}}
\]
Rule (*5) says, if a \index{type-like term}type-like term conforming to \texttt{Bot} is followed by $\assocsym{Mid}{A}$, we can reduce it to $\assocsym{Bot}{A}$.
Rule (4) overlaps with rule (3) on the term $\protosym{Bot}.\protosym{Mid}.\protosym{Top}$:
\begin{align*}
\protosym{Bot}.&\protosym{Mid}\\
&\protosym{Mid}.\protosym{Top}
\end{align*}
Resolving this critical pair records a rewrite loop defining rule (*6) via rule (2) and (4):
\[
\FourLoopDerived%
{\protosym{Bot}.\protosym{Mid}.\protosym{Top}}%
{\protosym{Bot}.\protosym{Top}}%
{\protosym{Bot}}%
{\protosym{Bot}.\protosym{Mid}}%
{(\ProtoInherit{Bot}{Mid}).\protosym{Top}}%
{(\ProtoInherit{Bot}{Top})}%
{(\ProtoInheritInv{Bot}{Mid})}%
{\protosym{Bot}.(\ProtoInheritInv{Mid}{Top})}
\]
Rule (*6) says, if a type-like term conforms to \texttt{Bot}, it also conforms to \texttt{Top}. In general, after completion, rewrite rules of the form $\protosym{P}.\protosym{Q}\Rightarrow\protosym{P}$ will encode the \index{transitive closure}transitive closure of the \index{inherited protocol}protocol inheritance relation.
This completes the rewrite system for \texttt{Bot}. Moving on to $G_\texttt{Bot}$, we see that rule (7) overlaps with rule (4) on the term $\ttgp{0}{0}.\protosym{Bot}.\protosym{Mid}$:
\begin{align*}
\ttgp{0}{0}.&\protosym{Bot}\\
&\protosym{Bot}.\protosym{Mid}
\end{align*}
Resolving this critical pair defines rule (*8) via rules (4), (7) and (*8):
\[
\FourLoopDerived%
{\ttgp{0}{0}.\protosym{Bot}.\protosym{Mid}}%
{\ttgp{0}{0}.\protosym{Mid}}%
{\ttgp{0}{0}}%
{\ttgp{0}{0}.\protosym{Bot}}%
{(\ProtoConf{\ttgp{0}{0}}{Bot}).\protosym{Mid}}%
{(\ProtoConf{\ttgp{0}{0}}{Mid})}%
{(\ProtoConfInv{\ttgp{0}{0}}{Bot})}%
{\ttgp{0}{0}.(\ProtoInheritInv{Bot}{Mid})}
\]
Rule (*8) is the derived requirement $\ConfReq{\ttgp{0}{0}}{Mid}$. Rule (7) overlaps with rule (5) in the same way, defining rule (*9), which is the derived requirement $\ConfReq{\ttgp{0}{0}}{Top}$. Once again, we see the transitive closure of the protocol inheritance relation being computed.
Rule (7) overlaps with rule (3) on the term $\ttgp{0}{0}.\protosym{Bot}.\texttt{A}$, defining rule (*10), by the same general principle as in Example~\ref{assoc type completion example}.
Finally, rule (*8) overlaps with rule (1) on the term $\ttgp{0}{0}.\protosym{Mid}.\texttt{A}$:
\begin{align*}
\ttgp{0}{0}.&\protosym{Mid}\\
&\protosym{Mid}.\texttt{A}
\end{align*}
Resolving this critical pair defines rule (*11) via rule (1), (3) and (*8):
\[
\FourLoopDerived%
{\ttgp{0}{0}.\protosym{Mid}.\texttt{A}}%
{\ttgp{0}{0}.\assocsym{Mid}{A}}%
{\ttgp{0}{0}.\assocsym{Bot}{A}}%
{\ttgp{0}{0}.\texttt{A}}%
{\ttgp{0}{0}.(\AssocIntro{Mid}{A})}%
{(\ttgp{0}{0}.\assocsym{Mid}{A}\Rightarrow\ttgp{0}{0}.\assocsym{Bot}{A})}%
{\ttgp{0}{0}.(\AssocIntroInv{Bot}{A})}%
{(\ProtoConfInv{\ttgp{0}{0}}{Mid}).\texttt{A}}
\]
In this example, the relationship between \index{type parameter}type parameters and \index{type-like term}type-like terms is more subtle than we've previously seen, because the two distinct \index{associated type symbol}associated type symbols $\assocsym{Mid}{A}$ and $\assocsym{Bot}{A}$ both correspond to the same associated type \emph{declaration}. On one hand, the \index{equivalence class}equivalence class of \texttt{\ttgp{0}{0}.[Mid]A} contains one other type parameter, \texttt{\ttgp{0}{0}.A}. However, we have \emph{three} equivalent type-like terms: $\ttgp{0}{0}.\assocsym{Mid}{A}$, $\ttgp{0}{0}.\assocsym{Bot}{A}$, and $\ttgp{0}{0}.\texttt{A}$. Not only that, but applying Algorithm~\ref{build term generic} to the \index{reduced type parameter}reduced type parameter \texttt{\ttgp{0}{0}.[Mid]A} outputs $\ttgp{0}{0}.\assocsym{Mid}{A}$, which is \emph{not} a \index{reduced term}reduced term; the reduced term here is $\ttgp{0}{0}.\assocsym{Bot}{A}$, because $\assocsym{Bot}{A}<\assocsym{Mid}{A}$ in the \index{reduction order!in requirement machine}reduction order (Algorithm~\ref{protocol reduction order}):
\begin{quote}
\begin{tabular}{ll}