-
Notifications
You must be signed in to change notification settings - Fork 6
/
paper.mng
1446 lines (1229 loc) · 77.9 KB
/
paper.mng
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
% vim: set ft=tex:
\documentclass{jfp}
%\documentclass[a4paper]{article}
%\usepackage{a4wide}
\journaltitle{JFP}
\jnlDoiYr{2021}
\cpr{Cambridge University Press}
\doival{10.1017/xxxxx}
\newcommand{\citeinline}{\cite}
\newcommand{\citeparens}[1]{(\cite{#1})}
\usepackage{amsmath,amsfonts,amssymb,amsthm}
\tracinglostchars=2
\usepackage[utf8]{inputenc}
\usepackage[T2A]{fontenc}
%\usepackage{fontspec}
%\usepackage{unicode-math}
\usepackage{hyperref,cleveref}
\usepackage{mathtools}
\usepackage{xcolor}
\usepackage[implicitLineBreakHack]{ottalt}
\usepackage{subcaption}
\usepackage{url,natbib}
\usepackage{todonotes}
\usepackage{minted}
\usepackage[english]{babel}
\usepackage{newunicodechar}
\usepackage[toc,page]{appendix}
\newunicodechar{ℓ}{\ensuremath{\mathnormal\ell}}
\newunicodechar{ρ}{\ensuremath{\mathnormal\rho}}
\newunicodechar{σ}{\ensuremath{\mathnormal\sigma}}
\newunicodechar{ε}{\ensuremath{\mathnormal\varepsilon}}
\newunicodechar{ι}{\ensuremath{\mathnormal\iota}}
%\nonstopmode{}
\newtheorem{theorem}{Theorem}
\newtheorem{corollary}{Corollary}
\newtheorem{lemma}{Lemma}
\newtheorem{remark}{Remark}
\crefname{lemma}{lemma}{lemmas}
\crefname{remark}{remark}{remarks}
\crefname{theorem}{theorem}{theorems}
\newtheorem*{lemma*}{Lemma}
\newtheorem*{theorem*}{Theorem}
\newcommand{\unit}{\textbf{u}}
\newcommand{\Unit}{\textbf{Unit}}
\newcommand{\unitc}{\hat{\textbf{u}}}
\newcommand{\Unitc}{\widehat{\textbf{Unit}}}
\newcommand{\Basec}{\hat{B}}
\newcommand{\Int}{\textbf{Int}}
\newcommand{\ctxok}{\text{~ok}}
\newcommand{\fresh}{\text{~fresh name}}
\newcommand{\evalsto}{\rightsquigarrow}
\newcommand{\eqrefl}{\text{eq-refl~}}
\newcommand{\secondDP}{\text{second-dp~}}
\newcommand{\prooftermname}[1]{\texttt{#1}}
\begin{document}
\newNTclass{nonterm}
\newnonterm{e}{\varepsilon}
\newnonterm{es}{\varepsilon}
\newnonterm{ec}{\hat\varepsilon}
\newnonterm{r}{\rho}
\newnonterm{ts}{\tau}
\newnonterm{tc}{\hat\tau}
\newnonterm{s}{s}
\newnonterm{l}{l}
\newnonterm{B}{B}
\newnonterm{G}{\Gamma}
\newnonterm{GC}{\hat\Gamma}
\newnonterm{vs}{\varpi}
\newnonterm{vc}{\hat\varpi}
\newnonterm{f}{f}
\newnonterm{gamma}{\gamma}
\newNTclass{gterm}
\newgterm{x}{x}
\newgterm{v}{v}
\newgterm{n}{n}
\newgterm{p}{\pi}
\newcommand{\figref}[1]{Figure~\ref{fig:#1}}
\inputott{surface.ott}
\newcommand{\rae}[1]{\textcolor{magenta}{RAE: #1}}
\newcommand{\gr}[1]{\textcolor{green}{G: #1}}
\title{Compiling refinement types to dependent types}
\begin{abstract}
\end{abstract}
\maketitle
\section{Introduction}
Type systems are a powerful tool for internal specification and verification of programs,
ensuring that programs exhibit certain desirable properties and do not exhibit undesirable ones.
In particular, dependent types~\citeparens{FindSomethingForDTs} are powerful enough to encode pretty much arbitrary specifications,
going as far as encoding mathematics itself~\citeparens{FindSomethingForCurryHoward},
but this power comes at a cost: term finding (or, equivalently, proof finding) for dependent types is undecidable,
and so is type inference.
Or, practically speaking, the programmer must care about the details of the proofs,
even if the proofs lie within decidable theories
(like some flavours of arithmetic, sufficient for reasoning about array accesses and preventing out-of-bounds errors).
Even if the language supports some form of proof automation (such as proof by reflection, or Coq's tactics, or Idris' elaborator reflection),
this is still something that the programmer has to pay attention to.
Not only this consumes a part of human attention span (which is quite limited, compared to computers),
but we believe it also prevents widespread adoption of dependent types for mainstream programming.
A different point on the spectrum is represented by \emph{liquid types}~\citeparens{LiquidTypes08},
where the expressive power is limited, and the type system only allows specifying properties that can be efficiently proven (or disproven) by an SMT solver.
Liquid types are a special case of a more general concept of \emph{refinement types}~\citeparens{Constable87,Rushby98},
which are some base types endowed with a predicate, possibly dependent on other values, like \verb+{ v : Int | v >= 0 & v < len arr }+.
The logical implication on predicates
(or, equivalently, the set inclusion relation on the sets defined by predicates)
gives rise to a natural \emph{subtyping relation}:
for example, the aforementioned type is a subtype of \verb+{ v : Int | v >= -1 }+,
and the corresponding implication (which, in this case, is a tautology) is known as a \emph{verification condition} (VC).
The core idea of liquid types then is to ensure that this subtype relation is efficiently decidable by an SMT solver.
Another useful property of refinement types is that they have a natural mental model:
indeed, it feels more approachable to treat \verb+{ v : Int | v >= 0 & v < len arr }+ as just an integer that is within some array's bounds
as opposed to the typical interpretation of
``a dependent pair consisting of an integer and a pair of proofs,
one for said integer being non-negative and another one for it being less than the length of \verb+arr+''.
Thus, refinement types are arguably more accessible and more usable in mainstream programming.
The downside is that efficiently decidable refinement types are less expressive, limiting what can be specified and proven.
Even though there are new developments pushing the envelope of what can be expressed with liquid types~\citeparens{Reflection18},
the natural question is what would it take to combine full dependent types and refinement types in a single language.
Our work lays the theoretical foundation for positively answering this question, which, to the best of our knowledge, is a new contribution.
We consider a dependently typed language as some ``core'' language,
to which a ``surface'' language with just the refinement types is translated.
Moreover, we do not consider the peculiarities of a specific algorithm performing the subtyping check in the refinements language,
introducing instead the abstraction of a \emph{subtyping oracle}.
This allows plugging in not just SMT solvers but arbitrary decision procedures as long as they have certain properties we describe later.
This translation to a core dependently typed language provides several nice metatheoretical properties, most importantly:
\begin{itemize}
\item Dependent types are a well-studied and well-understood subject,
so taking them as the translation target automatically provides us with the existing array of metatheorems.
\item Since we require the subtyping oracle to produce a proof of the subtyping relation,
the result of the translation satisfies the de Bruijn criterion:
even if the solver makes a mistake and produces an incorrect proof,
this mistake would be caught by the type checker for the core language.
We deem this a desirable property as it reduces the trusted code base size,
since type checkers are typically simpler and have smaller ``error surface'' than SMT solvers,
and, moreover, the core type checker has to be trusted anyway.
\end{itemize}
Of course, there are related developments. Perhaps the closest one is F* and, in particular, Meta-F*~\citeparens{MetaFStar} (which is also based on F* core).
(Meta-)F* also supports dependent types, but they are rather used to manipulate the VCs to turn them into an SMT-decidable form,
or discharge certain proof obligations not decidable via SMT\@.
The main difference between (Meta-)F* and our approach is that F*'s core type checker still relies on an SMT solver,
while our approach keeps the core type checker limited to a dependent type theory.
Another example of a closely related work is Hammer~\citeparens{CoqHammer}, which brings some form of automation to Coq.
Although it achieves a similar goal of producing proof terms that are then verified using the core Coq type checker,
using either a decidable fragment of Coq's logic in case of the \verb+sauto+ tactic,
or machine learning and external automated theorem provers in case of the \verb+hammer+ tactic,
it still requires the programmer to think in terms of full dependent types.
Since verification of programs for safer software is the ultimate goal of all these type systems,
it seems important to have firm foundations and verify that the type systems themselves do make sense.
Thus, we also present mechanically verified proofs in Agda of all the key theorems about our surface language and its translation procedure.
This is, as far as we are aware, also a new contribution,
and no prior papers strived to mechanically verify the metatheoretical properties of refinement types to this extent.
\rae{I was expecting to find contributions here. We need to write out the paper's
contributions.}
\section{Motivation}
Having refinement types and dependent types in a single language is useful for many reasons.
Firstly, refinement types indeed lower the cognitive load and the amount of (both keyboard and mathematical) typing the programmer has to do.
As an example, consider a function taking two non-negative numbers $x, y$ and returning $x + y + x$ along with a proof that each summand is less than or equal to the sum.
In a language with refinement types writing such a function is at most\footnote{Some implementations \citeparens{LiquidTypes08} can infer refinements automatically}
a matter of decorating its type with the right refinements, along the lines of:
\begin{minted}{idris}
funnyAdd : (x : { v : Int | v >= 0 })
→ (y : { v : Int | v >= 0 })
→ { v : Int | v >= x & v >= y }
funnyAdd x y = x + y + x
\end{minted}
Then, it's up to the SMT solver to verify that the function satisfies the refinements.
What if we wanted to write a similar function with similar guarantees in a dependently typed language with explicit proofs?
First of all, the question of representing integers in a proof-friendly way is non-obvious,
with different approaches taken in different works and ranging from
a positional representation of strictly positive integers along with a three-constructor algebraic data type for the whole range of integers~\citeparens{CoqBinNums},
to the Grothendieck group over the monoid of natural numbers.
To avoid digressing into the pros and cons of each approach,
let's give the dependently typed implementation a leg-up and assume Peano natural numbers everywhere.
Even with this allowance, the task is non-trivial, with an example Idris solution:
\begin{minted}{idris}
ltePlusLeft : (x, y : Nat) -> x `LTE` y + x
ltePlusLeft x Z = lteRefl
ltePlusLeft x (S y) = lteSuccRight (ltePlusLeft x y)
ltePlusFunny : (x, y : Nat) -> y `LTE` x + y + x
ltePlusFunny x y = rewrite plusCommutative (x + y) x
in rewrite plusAssociative x x y
in ltePlusLeft y (x + x)
funnyAdd : (x : Nat)
-> (y : Nat)
-> (v : Nat ** (x `LTE` v, y `LTE` v))
funnyAdd x y = (x + y + x ** (ltePlusLeft x (x + y), ltePlusFunny x y))
\end{minted}
Despite extensive use of library lemmas like \verb+lteRefl+, \verb+lteSuccRight+, \verb+plusCommutative+ and \verb+plusAssociative+,
the code is considerably longer and is riddled with unnecessary details.
More than that, slight variations of the pre- and post-conditions are just a matter of updating the signature with refinement types:
\begin{minted}{idris}
funnyAdd' : (x : { v : Int | v > 0 })
→ (y : { v : Int | v > 0 })
→ { v : Int | v > x & v > y }
funnyAdd' x y = x + y + x
\end{minted}
On the other hand, updating the code with explicit proofs requires more human work and is left as an exercise to the reader.
As an another example, consider the function calculating the maximum of three numbers.
Implementing it with refinement types is about as straightforward as it might get:
\begin{minted}{idris}
max3 : (x : Int) → (y : Int) → (z : Int)
→ { v : Int | v >= x & v >= y & v >= z }
max3 x y z = if x > y then
if x > z then x else z
else
if y > z then y else z
\end{minted}
Casting integers aside and working with plain naturals again, the dependently typed solution might look a bit move involved:
\begin{minted}{idris}
notLTE : (x, y : Nat)
-> (x `LTE` y -> Void)
-> y `LTE` x
notLTE x Z not = LTEZero
notLTE Z (S y) not = void (not LTEZero)
notLTE (S x) (S y) notS = LTESucc (notLTE x y (\not => notS (LTESucc not)))
max3 : (x, y, z : Nat)
-> (v : Nat ** (x `LTE` v, y `LTE` v, z `LTE` v))
max3 x y z =
case y `isLTE` x of
Yes y_LTE_x =>
case z `isLTE` x of
Yes z_LTE_x => (x ** (lteRefl, y_LTE_x, z_LTE_x))
No contra => let x_LTE_z = notLTE _ _ contra
in (z ** (x_LTE_z,
lteTransitive y_LTE_x x_LTE_z,
lteRefl))
No contra =>
let x_LTE_y = notLTE _ _ contra
in case z `isLTE` y of
Yes z_LTE_y => (y ** (x_LTE_y, lteRefl, z_LTE_y))
No contra => let y_LTE_z = notLTE _ _ contra
in (z ** (lteTransitive x_LTE_y y_LTE_z,
y_LTE_z,
lteRefl))
\end{minted}
In general, refinement types are expressive enough to eliminate a fair share~\citeparens{LiquidTypes08} of run-time errors such as out-of-bounds array accesses or division by zero.
On the other hand, certain things are not expressible with refinement types.
In particular, we claim without proof that refinement types cannot affect run-time behaviour of the program
(and the reader familiar with the notion of run-time irrelevance or Coq's \verb+Prop+ universe might find those concepts useful to build the intuitive agreement with our claim).
For example, a type-safe variadic \verb+printf+ (whose arguments count, their \emph{types}, and run-time behaviour \emph{depend} on the formatting string argument \emph{value}) is not expressible with refinement types.
Although, it is worth noting that it seems to be possible to recover the full expressive power of dependent types via a \verb+Top+ type with the corresponding subtyping relation, at the cost of moving the typing checks to run-time.
\todo[inline]{Illustrate this via a Top-based printf.}
Moreover, for fundamental reasons such as Rice's theorem, there is no algorithm that decides arbitrary non-trivial semantic properties of a program,
so human assistance will always be needed for sufficiently complex programs, and this is where dependent types also come useful.
And, in practice, most existing SMT solvers do not support higher-order reasoning (in fact, it is not supported in the current SMT-LIB v2), or reasoning beyond some simple arithmetic or arrays,
so, for instance, formally proving the properties of the type system proposed in this very paper is something that, currently, a human should do.
There is also a certain synergy coming from uniting dependent types and refinement types:
for intance, since types are first-class in a dependently typed language, the refinements can also be treated as first-class.
As an example, \verb+filter+ function is conceivable which amends (arbitrary) refinements on the input, along the lines of
\begin{minted}{idris}
filter : forall Pred.
→ List { v | Pred }
→ (f : {v | Pred} → Bool)
→ List {v | Pred & f v = True}
\end{minted}
Given all of the above, it is desirable to have both refinement types and dependent types in a single language.
But having both in a single core type checker seems extravagant, and, since refinement types can be seen as a subset of dependent types,
a reasonable way to go is to have a core type checker for full dependent types, a surface language with both type systems,
and translating, respectively, refinements to dependent types and SMT decisions to proof terms.
This paper focuses on formulating the translation part and proving that the translation preserves semantics and has certain reasonable and useful properties.
We believe that the approach proposed in this paper is implementable in existing dependently typed languages such as Idris or Agda.
A language might allow both ``refinemently typed'' and dependently typed terms in a single module,
reserving a certain syntax such as \verb+foo : { v : Ty | Predicate v }+ to indicate that \verb+foo+ uses refinement types,
while also allowing to use the former in the latter and vice versa.
This enables the programmer to mostly write code with refinement types,
only resorting to the full power of dependent types when refinements are not enough.
\section{Overview}
\paragraph{Surface language}
We define a surface language with refinement types inspired by~\citeinline{LiquidTypes08,Reflection18}.
Broadly speaking, it is a simply-typed lambda calculus with several extensions,
including refinement types.
The other extensions are:
\begin{itemize}
\item dependent arrow types, to allow subsequent refinements refer preceding arguments,
\item a limited form of algebraic data types (ADTs) and dependent pattern matching, inspired by~\citeinline{TAPLVariants,Eisenberg16},
to illustrate reasoning about these widely used constructs, as well as generalizing path sensitivity~\citeparens{FindSomethingForPathSensitivity}.
\end{itemize}
We also formulate and prove type safety of our language via the usual progress and preservation theorems.
One major difference between our surface language and the languages in~\citeinline{LiquidTypes08,Reflection18} is that both parametric polymorphism as well as recursion are omitted.
This simplifies the formal model of the surface language considerably, while still giving meaningful results.
\paragraph{Core language}
Our core language is a full dependently typed language based on $\lambda C$ \citeparens{Schmidt1994,Barendregt92}
and extended with a unit type and a restricted form of algebraic data types.
\paragraph{Subtyping oracle}
The refinements in our surface language may contain arbitrary terms, including function application.
In general, this makes the subtyping check undecidable: even though our surface language turns out to be strongly normalizing, in practice most languages allow potentially non-terminating terms.
We sidestep this by abstracting the subtyping checker away and introducing a notion of an oracle.
As a nice side effect, this way we also do not have to consider the specifics of the subtyping check and instead focus on compiling refinement types to dependent types.
\todo[inline]{Reword this.}
The interface of said oracle boils down to a single function:
it takes a typing context $[[ G ]]$ and two refinements $[[ r1 ]], [[ r2 ]]$ over some argument $ v $, and decides whether one is the subtype of the other.
We denote the logical context arising from the typing context $[[ G ]]$ as $[| [[ G ]] |]$, so the oracle just decides whether $[[ [| G |] => A v. (r1 => r2) ]]$ holds.
The oracle abstraction allows keeping type-checking decidable even in the presence of non-terminating terms in refinements, assuming the oracle runs in finite time.
Practically, this means that any implementation of an oracle (that always completes in finite time) will have either false negatives (deciding that some types are not in subtype relationship when, in fact, they are) or false positives.
False negatives may limit the expressive power of the language, but they do not break its type safety, and what matters is the lack of false positives.
It is also worth noting that if an implementation cannot decide a query (that is, it can neither prove nor disprove it), it might leave it as a lemma to be filled out by the user in the full dependently typed core language.
We also require the oracle to satisfy certain properties for the aforementioned surface language metatheorems to hold.
As an example, if the oracle yields a ``positive'' decision in some typing context, then it also must yield a ``positive'' decision in any bigger context,
extended with variable bindings irrelevant to the subtyping problem being considered.
All the required properties are mentioned in each individual metatheorem directly relying on them,
and those properties are listed in \cref{sect:oracle_requirements}.
It is worth noting that the work on liquid types usually assumes the subtyping checks are done via an SMT solver, which can be seen to fit our oracle abstraction.
\paragraph{Combining refinement and dependent types}
After formulating our surface and core languages, we define a translation from the former to the latter.
We also formulate two key theorems proving that the translation makes sense.
First, we prove that any well-typed surface language term has a translation to a well-typed core language term.
Then, we prove that the small-step operational semantics of the languages match and commute with the translation:
if a surface language term $[[ es ]]$ evaluates to some other term $[[ es' ]]$ in one step,
then the translation of $[[ es ]]$ to the core language evaluates into the translationof $[[ es' ]]$, although, perhaps, in several steps.
\section{Calculi definitions}
\subsection{Surface language}
The syntax of the surface language is presented in \figref{surface_syntax}.
The (small-step) operational semantics for the surface language are laid out in \figref{surface_opsem}.
That is largely the usual call-by-value evaluation model
with some extra rules for the ADTs and pattern matching.
The (restricted) type ``equivalence'' is presented in \figref{surface_tyequiv}.
The typing rules for the surface language are presented in \figref{surface_typing}.
As usual, to simplify the exposition,
all bindings in contexts are assumed to have different names, and all labels in each ADT are assumed to be different.
We also have the following concessions:
\begin{itemize}
\item The syntax only allows refinements on base types.
Note that this does not severely restrict the expressive power of the language.
To see that, consider the following examples:
\begin{description}
\item[A functional argument.] Suppose we wish to write:
\[
(x : \Int) \rightarrow \{ v : \Int \rightarrow \Int | v x = 0 \} \rightarrow \Int
\]
With our syntax, we instead introduce a dummy parameter and write the same refinement modulo variable naming:
\[
(x : \Int) \rightarrow (f : \Int \rightarrow \Int) \rightarrow \{ \_ : \Unit | f x = 0 \} \rightarrow \Int.
\]
\item[An ADT argument] is treated similarly.
\item[A function that is returned.] This time, suppose we wish to express
\[
(x : \Int) \rightarrow \{ v : \Int \rightarrow \Int | v (x + 1) = 0 \land v (x - 1) = 0 \}
\]
Instead, we shift the refinement to the right, refining the last value and turning the arguments into antecedents of an implication:
\[
(x : \Int) \rightarrow (y : \Int) \rightarrow \{ v : \Int | (y = x + 1 \Rightarrow v = 0) \land (y = x - 1 \Rightarrow v = 0) \}
\]
\item[An ADT that is returned.] Suppose we now wish to write, for some function $f$, the following:
\[
(x : \Int) \rightarrow \{ v : [[ < </ li : tsi // i /> > ]] | f x v = 0 \}
\]
Informally, the only way $f$ can consume a value of type $[[ < </ li : tsi // i /> > ]]$ is by pattern-matching on it.
Thus, for each $[[ tsi ]]$ the function $f$ gives rise to a refinement $[[ ri ]]$, which is basically the right-hand side of the equation for $f$ corresponding to the constructor $[[ li ]]$.
We push this refinement into the ADT, replacing each $[[ tsi ]]$ with $\{ v : [[ tsi ]] | [[ ri ]] \}$, recursively desugaring the refinement on $[[ tsi ]]$ as well.
\end{description}
\item Our algebraic data types only allow a single ``field'' in each constructor.
One way to alleviate this is to introduce tuples,
but doing so would complicate the exposition
without any benefit for illustrating the main idea of this work.
\end{itemize}
\begin{remark}\label{remark:surface_base_types}
The surface language might also have other base types (for example, $\Int$),
elements of syntax (like numbers and operations on them)
as well as typing rules relating those,
but we omit them for the sake of brevity.
\rae{Brevity is good, but having only Unit makes the language trivial. Given that
the proofs are done over the language defined here, we need to add at least Int.}
\end{remark}
\begin{remark}
Type equivalence $[[ requiv ]]$ alone is neither transitive nor reflexive,
but those properties are regained by applying \textsc{T-RConv}, the only rule relying on $[[ requiv ]]$, enough times:
zero for reflexivity and multiple times for transitivity.
Delegating reflexivity and transitivity to the typing derivations, while perhaps being non-canonical,
simplifies the proofs of the metatheoretical properties of the language.
\end{remark}
\begin{figure}[ht]
\centering
\begin{subfigure}{.6\textwidth}
\nonterms{es,l,vs}
\caption{Term level}
\end{subfigure}
\begin{subfigure}{.5\textwidth}
\nonterms{G,r,B,ts}
\caption{Type level}
\end{subfigure}
\caption{Surface language syntax}\label{fig:surface_syntax}
\end{figure}
\begin{figure}[ht]
\drules[E]{$[[ es1 ~~> es2 ]]$}{term evaluation}{AppL,AppR,AppAbs,ADT,CaseScrut,CaseMatch}
\caption{Surface language small-step operational semantics}\label{fig:surface_opsem}
\end{figure}
\begin{figure}[ht]
\drules[RTEquiv]{$[[ ts1 requiv ts2 ]]$}{type equivalence}{Forward,Backward}
\caption{Surface language type equivalence}\label{fig:surface_tyequiv}
\end{figure}
\begin{figure}[ht]
\drules[TCTX]{$[[ G ok ]]$}{context well-formedness}{Empty,Bind}
\drules[TWF]{$[[ G |- ts ]]$}{type well-formedness}{TrueRef,Base,Conj,Arr,ADT}
\drules[T]{$[[ G |- es : ts ]]$}{term typing}{Unit,Var,Abs,App,Case,Con,Sub,RConv}
\drules[ST]{$[[ G |- ts1 <: ts2 ]]$}{subtyping}{Base,Arr}
\caption{Surface language typing}\label{fig:surface_typing}
\end{figure}
The translation function $[|\ |]$ maps the typing context $\nonterm G$ to some logic that the oracle can handle, and that we leave abstract.
Generally, the translation of a whole context is the conjunction of the translations of the types of the individual bindings,
and, within each refined type, the translation of the conjunction of atomic refinements is the conjunction of the translations of the atomic refinements.
\subsubsection{Requirements on the oracle}\label{sect:oracle_requirements}
Since the surface language uses the subtyping oracle in its type system, the metatheoretical properties of the language depend on the oracle satisfying certain crucial requirements.
\begin{enumerate}
\item\label{orprop:trans}
\emph{Transitivity}: if the oracle concludes $[[ [| G |] => A v. (r1 => r2) ]]$ and $[[ [| G |] => A v. (r2 => r3) ]]$, then it must conclude $[[ [| G |] => A v. (r1 => r3) ]]$.
\item\label{orprop:thinning}
\emph{Thinning}: if $[[ G ]] \subset [[ G' ]]$ and the oracle concludes $[[ [| G |] => A v. (r1 => r2) ]]$, then it must conclude $[[ [| G' |] => A v. (r1 => r2) ]]$.
In words, if an oracle concludes that $[[ r1 ]]$ implies $[[ r2 ]]$ in some context $[[ G ]]$, then it must also conclude this implication in any bigger context $[[ G' ]]$.
Intuitively, if the bigger context $[[ G' ]]$ does not contradict the smaller one $[[ G ]]$, then the oracle ought to be able to use just the assumptions from the subset of $[[ G' ]]$ isomorphic to $[[ G ]]$.
Otherwise, if some bindings in $[[ G' ]]$ introduce a contradiction, then anything is derivable, including the required conclusion.
\item\label{orprop:narrowing}
\emph{Narrowing}: if $[[ G |- ts' <: ts ]]$, and the oracle concludes $[[ [| G, x : ts, GD |] => A v. (r1 => r2) ]]$, then it must conclude $[[ [| G, x : ts', GD |] => A v. (r1 => r2) ]]$.
To intuitively justify this requirement, note the analogy to the chained implication in logic, and, speaking in terms of logic, $[[ G |- ts' <: ts ]]$ means that the implication $\tau' \implies \tau$ holds in $[[ G ]]$.
But this also means that, given the derivation of $[[ [| G, x : ts, GD |] => A v. (r1 => r2) ]]$ and a context $[[ G, x : ts', GD ]]$, we could first derive an object of type $[[ ts ]]$ using just the context $[[ G ]]$,
and then use that object in place of $x$ in the derivation of $[[ [| G, x : ts, GD |] => A v. (r1 => r2) ]]$.
\item\label{orprop:subst}
\emph{Substitution}: if $[[ G |- es : ts ]]$ and the oracle concludes $[[ [| G, x : ts, GD |] => A v. (r1 => r2) ]]$, then it must also conclude $[[ [| G, [ x |-> es ] GD |] => A v. ( [ x |-> es ] r1 => [ x |-> es ] r2 ) ]]$.
To see why this is a natural requirement, consider $[[ es ]]$ to be a proof of the statement $[[ ts ]]$ in the context $[[ G ]]$.
Then the premise $[[ [| G, x : ts, GD |] => A v. (r1 => r2) ]]$ means that $[[ A v. (r1 => r2) ]]$ holds with $[[ ts ]]$ as the assumption (among others).
Substituting $[[ x ]]$ for $[[ es ]]$ then boils down to replacing that assumption with its proof.
\item\label{orprop:stepping}
\emph{Stepping}: if $[[ ts requiv ts' ]]$ and the oracle concludes $[[ [| G, x : ts, GD |] => A v. (r1 => r2) ]]$, then it must also conclude $[[ [| G, x : ts', GD |] => A v. (r1 => r2) ]]$.
In other words, evaluation should not affect the logical interpretation of types.
\end{enumerate}
\subsubsection{Properties}
We prove the usual metatheoretical properties of the proposed language.
Some of the lemmas directly used in the subsequent exposition as well as progress and preservation theorems are formulated below.
The full (numbered and topologically sorted) list of the proven lemmas can be found in \cref{appendix:surface_props}.
The numbers of these lemmas in that list are given here in parenthesis.
We also provide machine-verified proofs of these theorems in the supplemental code,
with the corresponding proof terms referred in lemmas names.
\begin{lemma*}[Agreement I, \cref{lma:term_wf_implies_ctx_wf}, \prooftermname{T-implies-TCTX}]
If $[[ G |- es : ts ]]$, then $[[ G ok ]]$.
\end{lemma*}
\begin{lemma*}[Agreement II, \cref{lma:type_wf_implies_ctx_wf}, \prooftermname{TWF-implies-TCTX}]
If $[[ G |- ts ]]$, then $[[G ok]]$.
\end{lemma*}
\begin{lemma*}[Agreement III, \cref{lma:term_wf_implies_type_wf}, \prooftermname{T-implies-TWF}]
If $[[ G |- es : ts ]]$, then $[[ G |- ts ]]$.
\end{lemma*}
\begin{theorem*}[Progress, \cref{thm:surface_progress}, \prooftermname{progress}]
If $[[ empty |- es : ts ]]$, then either $[[ es ]]$ is a value, or there exists $[[ es' ]]$ such that $[[ es ~~> es' ]]$.
\end{theorem*}
\begin{theorem*}[Preservation, \cref{thm:surface_preservation}, \prooftermname{preservation}]
If $[[ G |- es : ts ]]$, and $[[ es ~~> es' ]]$, then $[[ G |- es' : ts ]]$.
\end{theorem*}
\subsection{Core language}
The syntax of the core language is presented in \figref{core_syntax},
the core $\lambda C$ typing rules are defined in \figref{core_typing}
and the rules for our extensions are defined in \figref{core_typing_exts}.
We conjecture these extensions do not break the metatheoretical properties of the original $\lambda C$,
for instance, referring to~\cite{Barendregt92}:
\begin{itemize}
\item Preservation~--- Theorem 5.2.15.
\item Strong normalization~--- Theorem 5.3.33.
\item Consistency, that is, $\bot$ is not derivable in the empty context~--- follows from Theorem 5.2.31 and strong normalization.
\end{itemize}
As a general convention,
core entities corresponding to the surface language are denoted by the same symbol, but with a $\widehat{\text{hat}}$.
For instance, core typing contexts are denoted as $[[ GC ]]$ and core expressions are denoted as $[[ ec ]]$.
In addition to that, we somewhat frivolously use $\hat B$
to denote the core language analogue of a surface language base type $B$,
which exists for $\Unit$ ($\hat B$ then being $\Unitc$)
and which we assume to exist for any other surface language base type
mentioned in \cref{remark:surface_base_types}.
We also assume that $\hat B$ has sort $\star$.
Although there is no separate syntactic notion of a type,
$[[ tc ]]$ is used as a metavariable where a ``type'' (an inhabitant of $\star$) or a sort ($\star$ itself or $\square$) is expected.
$[[ ec ]]$ is understood as usual, denoting any expression in the core language, be it a ``term'', a ``type'' or a sort.
The $\_$ placeholder is used where a binding name is expected but the binding is not used in the corresponding subterm,
as in $[[ Pi _ : tc1. tc2 ]]$.
Unlike the surface language,
there is no separate rules for type or context well-formedness.
Instead, when we say that a type $[[ tc ]]$ (with the above remark about what a ``type'' means) is well-formed,
we just mean that $[[ GC |- tc : sst ]]$ or $[[ GC |- tc : ssq ]]$.
To define the notion of context well-formedness,
we say that a context $[[ GC ]]$ is well-formed iff it is possible to derive $[[ GC |- ec1 : ec2 ]]$
for some $[[ ec1 ]], [[ ec2 ]]$.
Derivability of $[[ GC |- ec1 : ec2 ]]$, in turn, can be shown to imply the derivability of $[[ GC |- sst : ssq ]]$.
The latter is by no coincidence used as a premise in the \textsc{CT-UnitType} and \textsc{CT-UnitTerm} rules:
indeed, the purpose of this premise is to ensure that those rules are only applicable in a well-formed context.
The \textsc{CT-ADTCase} rule differs slightly from a typical case matching rule.
In our system, each right-hand side of a case match on a term $[[ es ]]$ has access
not only to the variable $[[ xi ]]$ under the corresponding constructor $[[ li ]]$,
but also to a proof term $[[ pi ]]$ showing that
this $[[ xi ]]$, decorated by the constructor $[[ li ]]$, is equal to the scrutinee $[[ es ]]$.
This equality is denoted by $\equiv$, which is a derived form defined later.
\begin{remark}
One plausible way to avoid the doubt in the type safety of our core language stemming from the presence of the ADTs is to
encode them via the Boehm-Berarducci encoding~\citeparens{Bohm85}.
Unfortunately, this does not work in our case precisely due to the presence of the equality proof term:
this encoding does not provide the equality witness,
and it seemingly cannot be easily extended to account for this witness.
\end{remark}
Even though we believe that our core language enjoys the strong normalization property,
we still explicitly define the evaluation rules (\figref{core_opsem}).
Firstly, this allows fixing a specific evaluation strategy mirroring the one for the surface language,
simplifying the subsequent proofs of some key theorems.
Secondly, the rule for \textsc{CE-CaseMatch},
as well as our flavour of pattern matching in general,
deserves some special attention.
\todo[inline]{Pay said attention.}
\begin{figure}[ht]
\nonterms{ec,s,vc}
\caption{Core language syntax}\label{fig:core_syntax}
\end{figure}
\begin{figure}[ht]
\drules[CT]{$[[ GC |- ec1 : ec2 ]]$}{core typing}{Sort,Var,Weaken,Form,App,Abs,Conv}
\caption{$\lambda C$ typing rules}\label{fig:core_typing}
\end{figure}
\begin{figure}[ht]
\drules[CT]{$[[ GC |- ec1 : ec2 ]]$}{core typing, extensions}{UnitType,UnitTerm,ADTForm,ADTCon,ADTCase}
\caption{Typing rules for our extensions to $\lambda C$}\label{fig:core_typing_exts}
\end{figure}
\begin{figure}[ht]
\drules[CE]{$[[ ec1 ~~> ec2 ]]$}{term evaluation}{AppL,AppR,AppAbs,ADT,CaseScrut,CaseMatch}
\caption{Core language small-step operational semantics}\label{fig:core_opsem}
\end{figure}
\newcommand{\dast}{\ **\ }
\subsubsection{Derived forms}\label{sect:derived_forms}
We also establish some derived forms in the core language to simplify the subsequent exposition:
\begin{itemize}
\item Simplified variable typing rule which we call \textsc{CT-VarW}:
\[ \ottdruleCTXXVarW{} \]
This rule unfolds into a single \textsc{CT-Var} defining $x$,
followed by a sequence of \textsc{CT-Weaken}
to ``move'' the $x$ into the right position in the final $[[ GC ]]$.
\item Non-dependent function type:
\[
[[ tc1 -> tc2 ]] \triangleq [[ Pi _ : tc1. tc2 ]].
\]
\item Dependent pair type, or the $\Sigma$-type,
with the first component being a value $x$ of type $[[ tc ]]$
and the second component being a value of type $[[ Pred x ]]$, where $[[ Pred ]]$ is of type $[[ tc -> sst ]]$:
\[
[[ Sigma tc Pred ]] \triangleq [[ Pi alpha : sst. (Pi x : tc. Pred x -> alpha) -> alpha ]],
\]
with the corresponding constructor:
\[
[[ < ec : tc , p of Pred > ]] \triangleq [[ \ alpha : sst. \ f : (Pi x : tc. Pred x -> alpha). f ec p ]].
\]
\item Non-dependent pair type:
\[
[[ (tc1, tc2) ]] \triangleq [[ Pi alpha : sst. (tc1 -> tc2 -> alpha) -> alpha ]],
\]
with the corresponding constructor:
\[
[[ (ec1 : tc1, ec2 : tc2) ]] \triangleq [[ \ alpha : sst. \ f : (tc1 -> tc2 -> alpha). f ec1 ec2 ]].
\]
Alternatively, we could have defined non-dependent pairs via dependent pairs, along the lines of
\[
[[ (tc1, tc2) ]] \triangleq [[ Sigma tc1 (\ _ : tc1. tc2) ]],
\]
but mechanically proving this definition is well-typed (given our call-by-value operational semantics)
requires mechanically proving that the core language is strongly normalizing,
which is beyond the scope of this work.
\item Equality of expressions $[[ ec1 ]], [[ ec2 ]]$ of type $[[ tc ]]$:
\[
[[ ec1 equal ec2 of tc ]]
\triangleq
[[ Pi Pred : tc -> sst. ( Pred ec1 -> Pred ec2 , Pred ec2 -> Pred ec1 ) ]]
\]
The reader might recognize this as the Leibniz equality~\citeparens{LeibnizEq}.
The corresponding constructor $[[ eqrefl tc ec ]]$ of type $[[ ec equal ec of tc ]]$
stating that $[[ ec ]]$ of type $[[ tc ]]$ is equal to itself
is then defined as follows:
\[
[[ eqrefl tc ec ]] \triangleq [[ \ Pred : tc -> sst. (\ p : Pred x. p , \ p : Pred x. p) ]]
\]
\end{itemize}
It can be shown that, for each definition,
if the entities to the left of $\triangleq$ have the naturally expected types,
then the expression to the right of it is well-typed.
We prove this in our Agda code,
and we present the statements of the corresponding lemmas in \cref{appendix:core_derived_forms}.
\section{Translation}
\newcommand{\tranty}{\mu_\tau}
\newcommand{\tranterm}{\mu_\varepsilon}
\newcommand{\transub}{\mu_{<:}}
\newcommand{\Tranctx}{\mu_{\vdash\Gamma}}
\newcommand{\Tranty}{\mu_{\vdash\tau}}
\newcommand{\Tranterm}{\mu_{\vdash\varepsilon}}
\newcommand{\Transub}{\mu_{\vdash <:}}
%FIXME ugly, but whatever
\renewcommand{\ottdrulename}[1]{}
The surface language ultimately gets translated into the core language.
What really matters for practical purposes is the translation of the terms, since
terms, not types or contexts, will eventually be compiled down to some executable code.
On the other hand, it seems desirable to ensure that the terms
that are well-typed in the surface language
are accepted by the core type checker after the translation,
providing some level of guarantee that the translation ``makes sense''.
As the oracle plays a crucial role in type checking the surface language,
it is natural to expect that it will also be used during any such translation,
for instance, to produce core language proofs that VCs hold.
The only trace of the oracle's work is in the typing derivations
(namely, in the subtyping relation check and the \textsc{T-Sub} typing rule),
so we choose to do the translation not on \emph{terms},
but rather on \emph{well-typedness derivations} for the terms.
This way the oracle has a chance to enrich the original surface language term
with proofs and witnesses of whatever it decided.
Thus the ultimate goal of this section is to define a function $\Tranterm$
taking a typing derivation in the surface language
and producing a typing derivation in the core language.
As part of its duty
this function also needs to translate the types and contexts
encountered in the source derivation,
so we also define two helper functions.
$\Tranty$ takes a surface derivation of a \emph{type} well-formedness
and produces the corresponding core derivation.
$\Tranctx$ takes a surface derivation of a \emph{context} well-formedness
and produces a core language context.
We also define two helper functions, $\tranty$ and $\tranterm$,
invoking $\Tranty$ and $\Tranterm$ and extracting just the type and term component respectively.
All in all, we define $\Tranctx$, $\Tranty$ and $\Tranterm$
with ``metatypes''
\begin{align*}
\Tranctx & : [[ G ok ]] \longmapsto [[ GC ]], \\
\Tranty & : [[ G |- ts ]] \longmapsto [[ GC |- tc : sst ]], \\
\Tranterm & : [[ G |- es : ts ]] \longmapsto [[ GC |- ec : tc ]].
\end{align*}
Our helper functions $\tranty$ and $\tranterm$ are then defined to return the $\nonterm{tc}$ and $\nonterm{ec}$
from the respective right-hand sides.
The apparent asymmetry of $\Tranctx$, which does not produce a derivation as others do,
is due to our core language not having a separate notion of a context well-formedness.
Note that, due to \cref{lma:type_wf_implies_ctx_wf} we might assume that
there is a derivation of $[[ G ok ]]$ around whenever there is a derivation of $[[ G |- ts ]]$.
Indeed, the proof of \cref{lma:type_wf_implies_ctx_wf} is constructive,
so there is a function taking a witness of $[[ G |- ts ]]$ and producing $[[ G ok ]]$.
Analogously, \cref{lma:term_wf_implies_type_wf} and \cref{lma:term_wf_implies_ctx_wf}
allow us to use a derivation of $[[ G |- ts ]]$ and $[[ G ok ]]$ respectively
whenever there is a derivation of $[[ G |- es : ts ]]$.
\paragraph{Contexts}
As a warm-up,
we start with defining $\Tranctx$,
which is the simplest of the three.
It merely maps the types of the bindings in a (well-formed) context
from the surface language into the core language.
Since $\Tranctx$ is defined on the derivations of $[[ G ok ]]$,
consider the last rule used in a derivation:
\begin{itemize}
\item \textsc{TCTX-Empty}.
\begin{align*}
& \ottdruleTCTXXXEmpty{} \longmapsto \emptyset.
\end{align*}
The base case is trivial: the empty context is mapped to the empty context.
\item \textsc{TCTX-Bind}.
\begin{align*}
& \ottdruleTCTXXXBind{}
\longmapsto
[[ mudG ( G ok ) , x : muT ( G |- ts ) ]].
\end{align*}
We recurse on the prefix $[[ G ]]$,
which is admissible due to the $[[ G ok ]]$ premise,
and we use $\tranty$ to get the translated type of $\gterm x$,
which is also admissible due to the other premise.
\end{itemize}
\paragraph{Types}
Next, we define $\Tranty$. In short:
\begin{itemize}
\item (dependent) arrow types are translated to the corresponding $\Pi$-types,
\item refined types are translated to the corresponding $\Sigma$-types,
\item atomic refinements, being propositions about surface language terms equality,
are translated to propositions stating the equality of translated core language terms,
\item conjunctions of several (atomic) refinements are represented as tuples of the corresponding atomic translations.
\end{itemize}
More formally, consider the last rule used in the derivation of $[[ G |- ts ]]$:
\begin{itemize}
\item \textsc{TWF-TrueRef}.
\begin{align*}
& \ottdruleTWFXXTrueRef{} \longmapsto \ottdruleTWFTargetXXTrueRef{}, \\
\text{where}~&[[ GC = mudG(G ok) ]].
\end{align*}
By \cref{lma:non_dep_pair_typing}
$[[ (BC, unitc equal unitc of Unitc) ]]$ has type $\star$ in $[[ GC ]]$
if $[[ BC ]]$ and $[[ unitc equal unitc of Unitc ]]$ are well-typed in $[[ GC ]]$,
which, in turn, is easily checked.
Thus, there exists a derivation of $[[ GC |- (BC, unitc equal unitc of Unitc) : sst ]]$,
and it is effectively constructible, although omitted for brevity.
\item \textsc{TWF-Base}.
\begin{align*}
& \ottdruleTWFXXBase{} \longmapsto \ottdruleTWFTargetXXBase{}, \\
\text{where}~&[[ GC = mudG(G ok) ]], \\
&[[ ec_i = muE(G, v : { v_1 : B | top } |- es_i : { v2 : B' | r_i }) ]].
%TODO add tc mentioned in the equal stuff
\end{align*}
To see that this is well-defined, first note that
that $[[ BC ]]$ has type $\star$ by assumption on $[[ BC ]]$.
Then, $[[ ec_1 ]]$ and $[[ ec_2 ]]$ are well-typed in the context $[[ mudG (G, v : { v_1 : B | top } ok) ]]$ according to the premises,
and this context coincides with the one used to type check $[[ \v : BC. ec_1 equal ec_2 of tc ]]$.
Hence both components of the dependent pair are well-typed, so by \cref{lma:dep_pair_typing} the dependent pair itself has type $\star$.
\todo[inline]{
The ${ v : B | \top }$ in the $\nonterm G '$ desugars to a dependent pair, yet we use $\lambda v : \hat B$ — note the naked base type.
Figure out how to best fix this.
}
Just as in the previous case, the extra derivations and premises corresponding to the considerations above
are omitted and denoted by $\cdots$.
\item \textsc{TWF-Conj}.
\begin{align*}
& \ottdruleTWFXXConj{} \longmapsto \ottdruleTWFTargetXXConj{}, \\
\text{where}~&[[ GC = mudG(G ok)]], \\
&P_1 \text{~s.t.~} [[ Sigma BC (\ v : BC . Pred1 v) = muT ( G |- { v : B | r1 }) ]], \\
&P_2 \text{~s.t.~} [[ Sigma BC (\ v : BC . Pred2 v) = muT ( G |- { v : B | r2 }) ]].
\end{align*}
The proof of the right-hand side being well-defined goes similarly to the cases considered previously,
but with an extra step.
Namely, note that the last two ``patterns'' on the left-hand side are irrefutable:
it can be seen by direct inspection and inductive reasoning that $\tranty$ always yields a pair
for a derivation of the form $[[ G |- { v : B | r }]]$.
Thus we can take the predicate components $P_1, P_2$ out from the corresponding dependent pairs
and repack them obtaining $[[ \ v : BC . (Pred1 v, Pred2 v) ]]$.
\item \textsc{TWF-Arr}.
\begin{align*}
& \ottdruleTWFXXArr{} \longmapsto \ottdruleTWFTargetXXArr{}, \\
\text{where}~&[[ GC = mudG(G ok) ]], \\
&[[ tc1 = muT(G |- ts1) ]], \\
&[[ tc2 = muT(G , x : ts1 |- ts2) ]].
\end{align*}
The rule \textsc{CT-Form} is used on the right.
This is admissible,
since $[[ mudT(G |- ts1) ]]$ produces a derivation of $[[ GC |- tc1 : sst ]]$,
and similarly there is a derivation of $[[ GC , x : tc1 |- tc2 : sst ]]$
resulting from the other invocation of $[[ mudT ]]$.
\item \textsc{TWF-ADT}.
\begin{align*}
& \ottdruleTWFXXADT{} \longmapsto \ottdruleTWFTargetXXADT{}, \\
\text{where}~&[[ GC = mudG(G ok) ]], \\
&[[ tci = muT(G |- tsi) ]].
\end{align*}
It can be seen that the right-hand side is well-defined
by an argument similar to ones for the previous clauses.
\end{itemize}
\paragraph{Terms}
Finally we define $\Tranterm$.
We consider the term typing rule at the root of the derivation tree for $[[ G |- es : ts ]]$.
\begin{itemize}
\item \textsc{T-Unit}.
\begin{align*}
& \ottdruleTXXUnit{} \longmapsto \ottdruleCTXXUnitTerm{}, \\
\text{where}~&\nonterm{GC} = \Tranctx(\nonterm G \ctxok).
\end{align*}
Any other base type $B$ is treated similarly.
\item \textsc{T-Var}.
\begin{align*}
& \ottdruleTXXVar{} \longmapsto \ottdruleTTargetXXVarW{}, \\
\text{where}~&[[ GC = mudG(G ok) ]], \\
&[[ tc = muT(G |- ts) ]].
\end{align*}
To show that the right-hand side is well-defined,
first note that $x : \nonterm{tc} \in \nonterm{GC}$ holds.
Indeed, by definition of $\Tranctx$,
if $\nonterm G$ contains a binding for the name $x$,
then $\nonterm{GC}$ also contains a binding for that name,
and its type is precisely $[[ muT ( G |- ts ) ]]$.
Secondly, $[[ G |- x : ts ]]$ implies $[[ G |- ts ]]$ by \cref{lma:term_wf_implies_type_wf},
and $[[ mudT(G |- ts) ]]$ provides a judgement of the form $[[ GC |- tc : s ]]$.
All in all, this shows that all the premises
necessary for the (derived) core typing rule \textsc{CT-VarW}
hold.
\item \textsc{T-Abs}.
\begin{align*}
& \ottdruleTXXAbs{} \longmapsto \ottdruleTTargetXXAbs{}, \\
\text{where}~&[[ GC = mudG(G ok) ]], \\
&[[ tc1 = muT(G |- ts1) ]], \\
&[[ tc2 = muT(G , x : ts1 |- ts2) ]], \\
&[[ ec = muE(G , x : ts1 |- es : ts2) ]].
\end{align*}
The right-hand side here is well-formed.
Firstly, $[[ mudT ( G |- (x : ts1) -> ts2 ) ]]$
produces a derivation tree of the form $[[ GC |- Pi x : tc1. tc2 : sst ]]$,
as can be seen by inspecting the definition of $[[ mudT ]]$ for \textsc{TWF-Arr},
which is the only rule having $[[ G |- (x : ts1) -> ts2 ]]$ in the conclusion.
Then, $[[ mudE ( G , x : ts1 |- es : ts2 ) ]]$
produces a derivation of $[[ GC , x : tc1 |- ec : tc2 ]]$.
These two derivations can then be used as premises for \textsc{CT-Abs},
which is invoked on the right-hand side.
\item \textsc{T-App}.
\begin{align*}
& \ottdruleTXXApp{} \longmapsto \ottdruleTTargetXXApp{}, \\
\text{where}~&[[ GC = mudG(G ok) ]], \\
&[[ tc2 = muT(G |- ts2) ]], \\
&[[ ec1 = muE(G |- es1 : (x : ts1) -> ts2) ]], \\
&[[ ec2 = muE(G |- es2 : ts1) ]].
\end{align*}
Admissibility of the right-hand side follows from a similar argument.
\item \textsc{T-Con}.
\begin{align*}
& \ottdruleTXXCon{} \longmapsto \ottdruleTTargetXXCon{}, \\
\text{where}~&[[ GC = mudG(G ok) ]], \\
&[[ tci = muT(G |- tsi) ]], \\
&[[ ec = muE(G |- es : tsj) ]].
\end{align*}
Well-formedness of the right-hand side can be shown analogously to the previous clauses.
One extra thing to note is that,
although $[[ G |- tsi ]]$ are not present directly in the premises of \textsc{T-Con},
they are implied by the $[[ G |- < </ li : tsi // i /> > ]]$ premise and thus can be used.
\item \textsc{T-Case}.
\begin{align*}
& \ottdruleTXXCase{} \\
\longmapsto \quad & \ottdruleTTargetXXCase{}, \\
\text{where}~&[[ GC = mudG(G ok) ]], \\
&[[ tc' = muT(G |- ts') ]], \\
&[[ ec = muE(G |- es : ts) ]], \\
&[[ eci = muE(G |- esi : ts) ]], \\
&[[ tci' ]] = [[ Sigma Unitc (\ _ : Unitc. ec equal ( < li = xi > as tc ) of tc) ]].
\end{align*}
This part of the translation is perhaps one of the most involved,
and the main complication stems from the following.
In \textsc{T-Case}, each (surface) $[[esi]]$ is being type checked in the context
where $x$ (the witness of the $\mathbf{case}$ branch taken)
has type $[[ { _ : Unit | es = (< li = xi > as ts) of ts } ]]$.
After $[[esi]]$ gets translated into the (core) term $[[eci]]$,
the latter is type checked in the context where $\hat x$
has the dependent pair type $[[ Sigma Unitc (\_ : Unitc. ec equal ( < li = xi > as tc ) of tc) ]]$.
On the other hand, the $\mathbf{proof} \pi_i$ part of the $\mathbf{case}$ branch
provides the proof $\pi_i$ typed as $[[ ec equal ( < li = xi > as tc ) of tc ]]$,
so it needs to be packed into the dependent pair type that $[[eci]]$ ``expects''.
The lambda abstraction/application pair on the right-hand side of the translation
is responsible for this extra packing.
All the typing derivations showing that this is well-formed follow trivially
from the typing rules, but are again omitted and replaced by $\dots$ for the sake of brevity.
\item \textsc{T-Sub}.
This is the only part of the translation that uses the oracle,
and hence cannot be done as straightforwardly as the other ones.
Our goal is to translate a typing derivation ending with \textsc{T-Sub}:
\[
\ottdruleTXXSub{}.
\]
Note that, for languages with non-trivial subtyping, uniqueness of typing does not hold,
but it holds for the CoC modulo $\beta$-conversion
(which is an equivalence relation unlike any non-trivial subtyping relation).
Thus, intuitively,
there is no general way to prescribe both the translation of $[[ ts ]]$ and $[[ ts' ]]$
to the translation of $[[ es ]]$ simultaneously.
Instead, we produce another term that carries along the witness of the subtyping relation.
\todo[inline]{Should we give the intuition for producing a new term
based on the uniqueness of typing-like considerations or
based on VC proof witness stuff?}
We now define yet another translation function, $\Transub$,
mapping the derivations of $[[ G |- ts <: ts' ]]$
into core language terms $[[gamma]]$ of type $[[ muT(G |- ts) -> muT(G |- ts') ]]$
along with derivations of their well-typedness.
Informally, forgetting about the distinction between surface and core types,
a subtyping derivation is turned into a function $[[gamma]]$
transforming any term of the subtype into a term of the supertype.
The helper function $\transub$ is defined similarly to other helpers,
forgetting about the derivation and yielding just the final term.
So, consider the last (subtyping) rule in the derivation of $[[ G |- ts <: ts' ]]$:
\begin{itemize}
\item \textsc{ST-Base}.
In this case $[[ts]]$ and $[[ts']]$ are