Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination;...

62
Combining Proofs and Programs in a Dependently Typed Language (With technical appendix) Chris Casinghino Vilhelm Sjöberg Stephanie Weirich University of Pennsylvania {ccasin,vilhelm,sweirich}@cis. upenn.edu Abstract Most dependently-typed p rogramming languages either require that all expressions terminate (e.g. Coq, Agda, and Epigram), or al- low infinite loops but are inconsistent when viewed as logics (e.g. Haskell, ATS, Ωmega). Here, we combine these two approaches into a single dependently-typed core language. The language is composed of two fragments t hat share a common syntax and over- lapping semantics: a logic that guarantees total correctness, and a call-by-value programming language that guarantees type safety but not termination. The two fragments may interact: logical ex- pressions may b e used as programs; the logic may soundly r eason about potentially nonterminating p rograms; programs can require logical proofs as arguments; and “mobile” program values, includ- ing p roofs computed at runtime, may be used as evidence b y the logic. This language allows programmers to work with total and partial functions uniformly, p roviding a smooth path from func- tional programming t o dependently-typed programming.

Transcript of Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination;...

Page 1: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

Combining Proofs and Programsin a Dependently Typed Language

(With technical appendix)

Chris Casinghino Vilhelm Sjöberg Stephanie Weirich

University of Pennsylvaniaccasin,vilhelm,sweirich@cis. upenn.edu

Abstract

Most dependently-typed p rogramming languages either requirethat all expressions terminate (e.g. Coq, Agda, and Epigram), or al-low infinite loops but are inconsistent when viewed as logics (e.g.Haskell, ATS, Ωmega). Here, we combine these two approachesinto a single dependently-typed core language. The language iscomposed of two fragments t hat share a common syntax and over-lapping semantics: a logic that guarantees total correctness, and acall-by-value programming language that guarantees type safetybut not termination. The two fragments may interact: logical ex-pressions may b e used as programs; the logic may soundly r easonabout potentially nonterminating p rograms; programs can requirelogical proofs as arguments; and “mobile” program values, includ-ing p roofs computed at runtime, may be used as evidence b y thelogic. This language allows programmers to work with total andpartial functions uniformly, p roviding a smooth path from func-tional programming t o dependently-typed programming.

Page 2: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

Categories and Subject D escriptors D.3. 1 [Programming L an-guages]: Formal Definitions and T heory

Keywords Dependent types; Termination; General r ecursion

1. IntroductionDependently typed languages have developed along two differenttraditions, distinguished by their attitude towards nonterminatingprograms. On the one h and, languages like Cayenne [6], ATS [13],Ωmega [33] and Haskell [29] treat dependently-typed program-ming as an extension of ordinary functional programming. Theselanguages enhance ordinary functional programs, defined by gen-eral recursion, with more expressive types. On the other h and, lan-guages like Coq [40], Agda [28] and Epigram [23] treat depen-dently typed programming as a use-case of constructive theoremproving. These systems disallow nontermination because an infi-nite loop can b e given any type and would therefore make the logicinconsistent.

We would like balance between proving and p rogramming, withneither activity given preferential treatment. Although we are sym-

Permission to make digital or hard copies of all or p art of this work for personal o rclassroom use is granted without fee provided that copies are not made or d istributedfor profit or commercial advantage and that copies bear this notice and the full citationon the first page. Copyrights for components of this work owned by others t han theauthor(s) must be honored. Abstracting with credit is permitted. To c opy otherwise, o rrepublish, to p ost on servers or to r edistribute to lists, requires p rior specific permissionand/or a fee. Request permissions from [email protected] ’14, January 22–24, 2014, San D iego, CA, USA.Copyright is held by the owner/author(s). Publication rights licensed to ACM.ACM 978-1-4503-2544-8/14/01.. .$15.00.http://dx.doi.org/10. 1145/2535838.2535883pathetic t o the ideal that all programs should be proven correct, we

Page 3: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

understand that there are practical reasons not to do so. Instead,we desire a language for h eterogeneous verification, allowing pro-grammers to devote their verification budget to critical sections.Such a language must support general recursion as natively as afunctional programming language, yet at the same time must pro-vide the expressive reasoning capabilities of a constructive logicproof assistant.

In support of this goal, we propose a novel language that is com-posed of two fragments: a logicalf ragment where every expressionis known to terminate, and a programmaticf ragment that does notprovide this assurance. The key idea of our work is to distinguishbetween these fragments b y indexing the typing j udgement with aconsistency classifier θ that may b e L (“logic”) or P (“program”),thus

Γ ‘θ a : AWhen θ is L, the Curry-Howard Isomorphism applies, and we mayconsider a a proof of the theorem A. When θ is P, the only inter-pretation of a is as a functional program. Making this distinctionmeans that one language can subsume b oth functional program-ming and constructive logic by embedding each in their respectivefragments. However, these activities are not too far apart—the syn-tax and semantics of the two fragments overlap considerably, be-cause the distinction between them is made through typing.

In this paper, we explore the consequences of this design in thecontext of a dependently-typed programming language, focusingon the following m echanisms that foster interaction between thetwo fragments.

• First, we define the logical language as a sublanguage of theprogrammatic language, so that all logical expressions can beused as p rograms. (Of course, the p rogrammatic language in-cludes forms that are not available t o the logic, including gen-

Page 4: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

eral recursion and the elimination of iso-recursive types.)

• We allow uniform r easoning for logical and programmatic ex-pressions through a heterogenous equality t ype. Two expres-sions can b e shown to be equal based on their evaluation, whichis the same for b oth fragments. Equality p roofs can be used im-plicitly b y the type system.

• We internalize the labeled typing judgment as a new type formA@θ. This type can b e used by either fragment to manipulatevalues b elonging to the other.

• We identify a set of “mobile types”—those whose values canfreely move between the fragments.

To demonstrate the soundness and consistency of these mecha-nisms, we define a core dependently-typed language, called λθ, thatsupports these interactions (see Sections 2 and 3). In addition to the

Page 5: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

A@θ type, this language includes dependent functions, products,propositional equality, natural numbers, sums, recursive functionsand iso-recursive types. We prove that this language is type safe andthat the L fragment is normalizing and logically consistent (Section4). Our normalization proof uses a combination of traditional andstep-indexed logical relations. All of our metatheoretic results havebeen completely machine-checked using the Coq proof assistantand are available online1 .

We also explore how our ideas interact with other p rogramming

Zlmaoenmgnbutaaitiego,enb f ei ansateS udreceo stn.io t Wnhee5 .s h Zeaomvmeabni imtiecpselxeo tmfeneλ dnθst,eλ da θna dwp d irtiohstcof uetsaysptuet rhel asatnt hi gmautpaga leer-e,convenient for dependently-typed programming: parametric poly-morphism, type-level computation, user-defined datatypes, and im-plicit arguments. We have developed a number of examples usingZombie; the implementation is available online2.

We are not the first to consider the combination of total and par-tial programming in the setting of dependently-typed languages.Partial types [14] and the coinductive partiality monad [11] em-bed general r ecursive programs into constructive logic by mod-eling nontermination. Alternatively, languages such as Idris [10],Aura [18], and F∗ [38] identify a restricted sublanguage of pure to-tal functions. However, neither of these approaches provide equalsupport for total and partial programming. We compare them to ourwork in Section 6.

1.1 Combining Proofs and Programs

Before explaining the semantics of λθ, we conclude this sectionwith a number of examples to demonstrate the key ideas.

In Zombie, declarations must indicate whether they belong tothe logical or p rogrammatic fragment of the language. For exam-

Page 6: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

ple, a boolean negation operation is trivially terminating, so it ischeckable in the logical fragment, as indicated by the tag log in itsdefinition:

log not : Bool → Boolnot b = if b th→en False else True

Likewise, addition for natural numbers can be shown terminat-ing via natural number induction. In the case expression b elow,plus may b e called on any subterm of its argument. The argumentn_eq is a proof that n ’ is a subterm of n.

log plus : Nat → Nat → Natind plus n m =

case n [ n_eq ] ofZe ro → mSucc n ’ → Succ ( plus n ’ n_eq m )

Alternatively, the following natural number division functiondiverges when m is 0, so it must be tagged with prog. The reckeyword indicates that this function is implemented using generalrecursion.

prog div : Nat → Nat → Natrec div n m = i→f lt n m then 0

else plus 1 (div (minus n m) m)

Subsumption. All proofs can be used as p rograms. In the aboveexample, even though the plus operation is logical, we can seam-lessly use it (and other logical operations such as lt and minus)directly in a p rogrammatic term, and call it on an argument whose

1 Proofs available at http ://www. cis . upenn .edu/~ccasin/papers/combining - coq . tgz

Page 7: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

2 Implementation available at https ://code . google . com/p/t rellysin the b ranch branches/zombie - t rellys - POPL14/termination behavior is unknown. Thus, the fact that we k now thatplus terminates does not restrict how it may be used—we do notneed to duplicate its definition for it t o be available to both frag-ments.

Proofs c ontaining p rograms. The @-type allows values to beembedded from one fragment into another. For example, the logicallanguage can safely manipulate p rogrammatic values as long astheir types indicate (with @P) that they are p rogrammatic. Below,consider the definition of a Maybe datatype that could containarbitrary p rograms.

data Maybe (A : Type ) whereNothingJust of (A @ P)

As long as the p rogrammatic component is treated carefully, ex-pressions in the logical fragment can work with this data structure.This includes constructing values of the Maybe type, and patternmatching on the data structure.

log md3 : Maybe ( Nat → Nat )md3 = J ust ( \x . div 3→ x )

log foo : Maybe ( Nat → Nat ) → ( Nat → Nat @ P )foo x = case x of

Just y → yNothing → \x . x

However, if the programmatic component is ever used, thenthe definition must be marked as programmatic, as an embedded

Page 8: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

function could cause divergence.

prog bar : Maybe ( Nat → Nat ) → Nat → Maybe Natba r x y = case x of

J ust f → Just ( f y )Nothing → Nothing

prog boom : Maybe Natboom = ba r md3 0

Proofs a bout programs. Having defined the programmatic func-tion div, we might wish to verify facts about it. As a simple exam-ple, we prove that div 6 3 evaluates to 2. We can state and provethese facts using the logical language, even though the object ofstudy may not terminate.

log div63 : div 6 3 = 2div63 = refl

The proof above (refl) is valid when b oth sides of an equalityproposition evaluate to the same result. (To avoid infinite loops, thetypechecker will give up and signal an error if the expression doesnot r each a normal form within 1000 steps. If more evaluation isrequired the programmer can write e.g. refl 5000). In languageslike A ura or F ∗ , this theorem cannot even be stated because non-value expressions such as div 6 3 cannot appear in types. Thisexample illustrates an important property of our language, whichwe callf reedom of speech: although proofs cannot themselves usegeneral r ecursion, they are allowed to refer to arbitrary program-matic expressions.

As a more complicated example, we might wish to prove that ifthe divisor is not zero, then the result is less than the dividend. In

Page 9: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

other words:

log div_le : ( n : Nat ) → ( m : Nat ) → ( eq m 0 = False )→ ( le ( div→ n m ) n = →True )

Page 10: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

Above, eq is an equality function for natural numbers and lem n determines whether m ≤ n. We do not show proof of the abovetheorem here, though it is a≤vailable with our implementation. Theproof itself uses strong natural number induction to simultaneouslyshow both that division terminates and that the property aboveholds for the result.

Note that we can only show properties that are provable via fi-nite reduction sequences. For example, we cannot show that divi-sion diverges when the dividend is 0, because that divergence isnot finitely observable. (The logic does not h ave a general principlefor r easoning about nonterminating programs, such as fixed-pointinduction. We r eturn t o this issue in Section 6.)

Programs t hat r eturn proofs. An alternative to writing separateproofs about nonterminating programs is to give the programsthemselves more specific types that express their correctness. Forexample, consider writing a SAT solver that we do not want toprove terminating.

A SAT solver takes a formula of n variables and, if the formulais satisfiable, returns a satisfying assignment for some subset ofthose variables. We can r epresent the r esult of a SAT solver usingthe following datatype declaration. The r esult for a given formulais either an assignment together with a proof that that assignmentsatisfies the formula, or UNSAT when the formula is unsatisfiable.

data Ans ( n : Nat ) ( fo rm : Fo rmula n) : Type w hereSAT of ( assign : Vecto r (Maybe Bool ) n )

( proof : satisfies assign fo rm =(Just True : Maybe Bool ) )

UNSAT

The main loop of the solver itselftakes a formula and the currentassignment and returns whether that assignment can be extended to

Page 11: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

a satisfying one. Ifthe current assignment is known to be satisfying,then that one is returned. Zombie can automatically fill in the_below with the proof that assign satisfies the formula. If theassignment is k nown to invalidate the formula, then the r esult isUNSAT. Otherwise the algorithm must search for an extension to theassignment using techniques such as unit propagation, p ure literalassignment, or merely trying b oth possibilities for an unassignedvariable.

prog solve r : ( n : Nat ) → ( fo rmula : Fo rmula n)→ Vecto r (Maybe Bool ) n→ Ans n fo rmula @ L

solve r n fo r→mula assign =case ( satisfies assign fo rmula ) of

Just True → SAT assign _Just False → UNSATNothing → . . . .

Since the solver is written in the programmatic fragment, it maynot terminate. It also may fail to find an assignment even thoughthe formula was satisfiable. However, the type of this function ismore informative than if it had been written in M L or Haskell. The@L in its type indicates that if it does return a proof of satisfiability,then that value was type checked in the logical fragment.

When a program contains subexpressions from b oth fragments,values can b e handled more freely than expressions. For example,a logical expression cannot call solve r directly because of thepossibility of divergence. However, if the result of that call hasalready b een bound to a variable, then the logic has access to thatresult.

let prog f = ( . . . : Fo rmula n) inlet log empty = repeat ( Nothing : Maybe Bool ) n in

Page 12: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

let prog isSat = ( solve r n f empty : Ans n f @ L ) inlet log p rf = case isSat of

θ ::= L | Pa, b, A, B ::= ?L || (Px :A) → B | a = b

| ?N| at( |x :AA +) →B |B BΣ |xa a:A= .Bb | µx.A | A@θ|| xN a| tλ |xA . Aa+ +| rBec | |f Σ xx. :aA A| iBnd| µ f xx..A aA || aA b@|| rxef |l λ| xin.la aa| |r eincr f fbx|| rscefalse| z in laa ao|f inirnlb x ⇒ a1; inr y ⇒ a2|| ha, bi | pcasez lax xo⇒ f a(x,; ny)r y⇒⇒ ⇒ba|| hZa |, Sb ia| |p cncasaseeza aao off (xZ, ⇒ y) a ⇒1 ; bS x ⇒ a2 || rZol |l aS |a u| n nrocalsl ae

v ::= ? | (x :A) → B | a = b| ?N| at( |x :AA +) →B |B BΣ |xa a:A= .Bb | µx.A | A@θ|| xN a| tλ |xA . Aa+ +| rBec | |f Σ xx. :aA A| iBnd| µ f xx..A aA || rAef@l|| ixn|l vλ |x .inar |vr |e chvf 1 , .va2i || nZd d| fSx v.a a| |ror lel vl

a; b (λx.a) v; [ v/x]aSLAM

(recf x.a)v ; [ v/x][recf x .a/f] aSFUN

(ind f x.a)v ; [ v/x][λy.λz.(indf x .a)y /f] aSIND

scasezinlvo f inlx ⇒ a 1;inrx ⇒ a 2; [ refl/z][v/x]a1SCL

scasezinrvo f inlx ⇒ a 1;inrx ⇒ a 2; [ refl/z][v/x]a2SCR

pcasezhv1,v2io f (x,y )⇒ a ; [ refl/z][v1/x][v2/y]aSCP

Page 13: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

unroll(rollv); v SUNROLL

Figure 1. Expressions, values, and operational semantics (excerpt)

SAT assignment pf →

- - . . . use p ro→of of satisfiability . . .UNSAT → . . .

Mobile t ypes Finally, some types have the same meaning in b othfragments, so they do not benefit from b eing tagged with a consis-tency classifier. For example, a value of type Nat can never causedivergence, so it is safe to be used in logical expressions even whennot marked as @L. Similarly, the Ans type above is also mobile, sothe @L annotation on the type of solve r is actually unnecessary.This observation simplifies programming as the only function ar-guments that must b e annotated with their fragment are those thatare not mobile.

2. The λθ language

We begin our technical development with an overview of the for-mal language, λθ. T his language is based on a call-by-value (CBV)variant of lambda calculus. Its syntax is shown in Figure 1. Foruniformity, terms, types and the single kind ? (the “type” of types)are drawn from the same syntactic category, as in p ure type sys-tems [7]. The first two lines of the figure list the type forms, thefollowing lines list the terms. By convention, we use lowercasemetavariables a, b for expressions that are terms and uppercasemetavariables A, B for expressions that are types.

The λθ values v and key rules of the operational semantics are

Page 14: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

also shown in Figure 1. The reduction relation a ;b defines aaslmsaolls -hstoewpn ncai nll-F biyg-uvraelu1 e. sTehmeanr etidcusc. Tiohne selliagthiotnly aun; usuab l dbeeftain reusl eafor natural number induction (SIND) is described in Section 2.1. To

Page 15: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

save space, most r ules have b een omitted. The f ull set of rules canbe found in Appendix A.

Values include the standard components of f unctional program-ming: recursive functions rec f x.a, nonrecursive f unctions λx. a,natural numbers (constructed by Z and S a and eliminated b yncase), disjoint unions (constructed b y inl a and inr a and elim-inated by scase), dependently typed pairs (constructed b y ha, biiannadt eedlim byins acteads eb),y dpecpaesned),e anntldy rt eycpuerdsi vpea drast a(c (oinnsttrroudcutceeddb byy rao,llb ai

and eliminated by unroll a). Values also include ?, all type forms, atrivial equality p roof refl, and variables. Including variables is safebecause CBV evaluation only substitutes values for variables andit is useful because it allows the λθ type checker to reduce openterms.

We chose CBV because of its simple cost model, but this choicealso affects the interaction between the logical and p rogrammaticfragments. As shown in Sections 2.2 and 3.3, the type system takesadvantage of the fact that values cannot induce nontermination. Asa result, some typing rules apply only to values.

Note that expressions do not contain type annotations. Typesdescribe terms but do not interfere with equality. We do not wantterms with the same runtime behavior to b e considered unequalj ustbecause t hey have different annotations.

Due to the lack of annotations, it is not possible to algorithmi-cally compute the type of a λθ term. This i s not a problem becausewe do not intend programmers to write these t erms directly. In-stead, our implementation uses an annotated surface language t hatthe type checker elaborates into typing derivations (see Section 5).

The r est of this section describes the specific details of λθ, in-cluding its b asic j udgements (Section 2.1), and treatment of equal-ity (Section 2.2). In the next section, we introduce the novel fea-tures of our language that p ermit the interaction between the logicaland programmatic fragments of the language.

Page 16: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

2.1 Classifying terminating and nonterminating expressions

The starting p oint for λθ is a dependent type theory where thetyping judgment Γ ‘θ a : A is indexed b y a consistency classifiertθy. pTinheg j juuddggmemeennttΓ Γis‘ ‘designed so that expressions that type check atL always terminate.

Figure 2 shows the typing r ules for the b asic building b locks ofthe language—variables, functions and various data structures andtheir types. Because we work with a collapsed syntax, we use the

ftoyrpmes eyds ttyepmet i fo Γi d ‘eθntAify: w ? h.iche xpressionsa ret ypes:A i sa w ell-mCeodntt eyxptse iafr eΓ l i‘sts of assumptions about the types of variables.

Γ ::= ∅ | Γ, x :θ A

Each variable in the context is tagged with θ to indicate its frag-ment, and this tag is checked in the TVAR typing r ule. A contextis valid, written ‘ Γ, if each type A is valid in the correspondingifrsav gamliden,tw.

The r ules TARR, TSIGMA, T SUM, and TMU check typesfor well-kindedness. For example, TARR checks a function typeby checking the the domain and r ange. We discuss the premiseMobile (A), which asserts that A is a mobile type, in Section 3.3.

There are three ways to define functions in λθ . Rule T LAMtypes non-recursive λ-expressions in the logical fragment, whereasrule TREC types general recursive rec-expressions and can only b eused in the programmatic fragment.

Additionally, terminating r ecursion over natural numbers is pro-vided in the logical fragment by r ule T IND. W hen typechecking thebody of a terminating recursive function (ind f x.b), the recursivecall f t akes an extra argument proving that it is being applied to

Page 17: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

the p redecessor of the initial argument x. This ensures termination.When beta-reducing such an expression, this argument is ignored

‘Γ ‘Γ ‘Γ Γ‘ θA: ?

‘· CNIL ‘ Γ,‘xΓ : θ?CSTAR ‘ Γ‘ Γ,Γx‘ : θACTYPE

Γ‘ θa: A Γ‘ θA: ? Mobile(A)

(x :θA)θ∈ xΓ : A ‘Γ TVAR Γ,Γx ‘: θθA(x‘ : Aθ)B→ : ? B : ? TARR

Γ ‘θ b : (x :A) → B

Γ ‘θaΓ: ‘A θb aΓ :‘ [θa/[ax]/Bx]B: ? TAPP

Γ, x :L A ‘L b : B

ΓΓ‘ L‘ λLx(.xb : A:( )x→ :AB )→ :? B TLAM

Γ,f :P (x : A) → B, x :P A ‘P b : B

Γ ‘ΓP(‘ xP :rAe)c→ fx B .b :: ? ( x: A)→ B TREC

Γ, x :L Nat, f :L (y :Nat) → (z :S y = x) → B ‘L b : B

Γ ‘L(x :NatΓ)→ ‘ L Bind: ? f x .b: ( x: Nat)→ B TIND

Γ ‘θ A : ?

Page 18: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

ΓΓ ‘‘θ B : ?

Γ Γ‘θ‘ A+ B : ?TSUM

Γ ‘θ a : A Γ ‘θ b : BΓΓ ‘‘θ A + B : ? ΓΓ ‘‘θ A + B : ?

ΓΓ‘ ‘θ inla: A + B TINL ΓΓ‘ ‘θ inrb: A + B TINR

Γ ‘θ a : A1 + A2 Γ ‘θ B : ?

Γ, x :θ A1, z :L inl x = a ‘θ b1 : B

Γ ‘θΓsc,axse: zθAa 2of,z :i nLlinx r ⇒x= b 1;a in‘ rθ xb⇒ 2:B b 2: B TSCASE

Γ ‘θ Σx :A.B : ?

Γ ‘θ A : ? ΓΓ ‘‘θ a : A

MΓ,oxbθ :ilθΣe(AxA ‘: A)θ.BB: : ? ? TSIGMA Ñà Γθ ‘‘hθθab,[ab: /ix[ a: ]B/Σ xx] :B: ? A.BTPAIRΓ ‘θ a : Σx :A1.A2 Γ ‘θ B : ?

Γ,xΓ: θ ‘Aθ1p,yca: sθezAa2, ozf : L(xhx,,y y)i ⇒= b a ‘ : θB b: B TPCASE

Γ,Γx‘ : LL?µx‘ .ALA: : ?? TMUΓΓΓ ‘ ‘‘ θθθµarx: o.lA[ lµax: .: ? Aµ /xx.A]ATROLLΓ ‘PaΓ: ‘ µPxu.AnrollΓa: ‘ [µPx[µ.Ax/.Ax/]Ax]A: ? TUNROLL

Page 19: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

Figure 2. Typing: variables, functions, and datatypes (rules forNat omitted)

Page 20: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

by wrapping the function in an extra l ambda (rule SIND from Fig-ure 1).

The rule for function application, TAPP, differs from the usualapplication r ule in pure dependently-typed languages in the addi-tional third premise Γ ‘θ [a/x]B : s, which checks that the re-stuioltn atyl tphei rids pwreemll-ifsoermΓ ed‘ . Some rules of the language (such as β-reduction) are sensitive to whether terms are values. Because valuesinclude variables, substituting an expression a for a value x couldcause B to no longer type check.

Any dependently typed language that combines pure and effect-ful code will likely h ave to restrict the application r ule in someway. Previous work [18, 21, 38] uses a more restrictive typing forapplications, by splitting it into two rules: one which permits onlyvalue dependency and requires the argument to be a value, and onewhich allows a non-dependent function to be applied to an arbitraryargument. Since substituting a value can never violate a value re-striction in B, our application rule subsumes the value-dependentversion. Likewise, in the case of no dependency, the premise cannever fail because the substitution has no effect on B.

Being able to call dependent functions with non-value argu-ments is useful when writing explicit proofs. For example, a pro-grammer may want to first prove a lemma about addition

log plus_ze ro : ( n : Nat ) → plus n 0 = n

and then instantiate the lemma to p rove a theorem about a p articularexpression in the logical fragment.

plus_ze ro ( f x) : plus ( f x) 0 = ( f x)

The rules for sum types (TSUM, TINL, TINR, and TSCASE)provide dependent case analysis. The term scase b inds the logicalvariable z inside b oth branches of the case. This variable provides

Page 21: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

an equality between the scrutinee and the pattern of the b ranch sothat type checking is flow-sensitive. At runtime, this variable isreplaced b y refl because the scrutinee must match the pattern forthe branch to b e taken.

The r ules for dependent products (TSIGMA, TPAIR, TPCASE)allow the type of the second component of the pair to depend onthe value of the first component. As with function application, thepremise Γ ‘θ [a/x] B : ? ensures that substituting the expression adporeems nisoet Γvio ‘late any assumptions made about the value x in the typeof the second component. Analogously to sums, the eliminator forpairs makes available a logical p roof z that equates the scrutinee tothe pattern in the b ody of the match. The availability of this equalitymeans that the strong elimination forms (projections) for Σ-typesare derivable.

Finally, the rules TMU, TROLL and TUNROLL deal withgeneral r ecursive types. T hese are the standard rules for iso-recursive types (see, e.g., [30]). But recursive types with negativeoccurrences—that is, with the r ecursive variable appearing to theleft of an arrow, such as µx.(x → Nat)—are a p otential source ofnleofnto tefrma nina artrioown,. Tsuoc hen assurµ ex n.o(xrm →aliN zaatito)n—, aitr esua ffp icoetse ttoia lre ssotruicrct eto hefthe elimination rule TUNROLL to be in P. The introduction ruleTROLL can be used in b oth fragments. This reflects the fact that itis not dangerous to construct negative datatype values; the p otentialnontermination comes from their elimination.

2.2 Reasoning about equivalence

A big benefit of combining termination-checking with dependenttypes is that it is possible to write proofs about programs. For ex-ample, in the introduction we showed a proof that when the divisoris not zero, natural number division produces a r esult less than thedividend. Our r ules for propositional equality (Figure 3) are de-signed to support such r easoning uniformly, b ased only on the r un-

Page 22: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

time behavior of the expressions being equated, and independent ofthe fragment that they are defined in.

Γ‘ θa: A Γ‘ Pa: LA a =Γb ‘ : P? b :B TEQa V∗ c b V∗ cΓ ‘θ1 a : A Γ ‘θ2 b : B

Γ ‘Γ‘ Lrefl :Γa ‘ = b TREFL

Γ ‘L b : b1 = b2 Γ ‘θ a : [b1/x]A

Γ ‘θ[b2/Γx]A‘ θ: a? : [ b2/x]ATCONV

Figure 3. Typing: equality

Γ‘ θa: AΓ ‘L a : A Γ ‘θ0 A :?

ΓΓ‘ ‘ Pa: A TSUB ΓΓ‘ ‘θ A@θ0:? TAT

Γ ‘θ v : A@θ0 Γ ‘θ a : AΓ ‘‘θ0 A : ? ΓΓ ‘‘θ A :?

ΓΓ‘ ‘ θ0v: A TUNBOXVAL ΓΓ ‘P‘ a: A @θTBOXP

Γ ‘L a : A Γ ‘P v : AΓΓ ‘‘θ A : ? ΓΓ ‘‘P A : ?

ΓΓ ‘L‘ a: A @θTBOXL ΓΓ ‘L‘ v: A @PTBOXLV

Page 23: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

Figure 4 . Typing: subsumption and internalized consistency clas-sification

Therefore, the rule TEQ shows that the type a = b is well-formed and in the logical fragment even when a and b can be typechecked only programmatically. T his is freedom of speech: p roofscan r efer t o nonterminating programs.

The term refl is the p rimitive p roof of equality. Rule TREFLsays that refl is a p roof of a = b j ust when a and b r educe toa common expression. The notion of r eduction u sed in the ruleis parallel reduction, denoted a V b. T his relation extends theordinary evaluation a ;b by allowing r eduction under binders,eo.rgd.i n(λaryx.e1 +al u1a)t oVn a(λ; x.2)b b evyea nl tlhowouinggh r(eλdxuc. 1t o+n 1 u)n dise ra lbreinaddeyr sa,value. H aving this extra flexibility makes equality more expressiveand simplifies the proof of preservation.

Proven equalities are used to substitute expressions in types b ythe elimination rule T CONV. The proof term is checked in L toensure it is a valid p roof. We demand that the equality proof usedin conversion type checks in the logical fragment for type safety.All types are inhabited in the programmatic fragment, so if wepermitted the user to convert using a p rogrammatic proof of, say,Nat = Nat → Nat, it would be easy to create a stuck term.SNiamtila= r tNo aT tA →PP, Nwae ,nei tedw toou lcdhe bcke ethasaty bt o2 cdroeeast enoa t svtuioclaktet anyvalue restrictions, so the last premise checks the well-formedness ofthe type given to the converted term. Rule TCONV is quite general,and may b e used to change some small p art of A or the entire typeby picking x for A.

This treatment of equality is a variant of Sjöberg et al. [34].However, t hat setting did not include a logical sublanguage; instead

Page 24: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

it enforced soundness b y requiring the proof term used in conver-sion to b e a value.

Uses of TCONV are not marked in the term because they are notrelevant at runtime. Again, types should describe terms without in-terfering with equality; we do not want terms with the same runtimebehavior t o be considered unequal due to uses of conversion.

Page 25: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

3. Interactions between the fragments

What is interesting about λθ is how its two fragments interact. Inthe introduction, we discussed ways in which logical and program-matic terms work together. Below, we discuss the technical machin-ery of the type system that supports this interaction.

3.1 Subsumption

Every logical expression can b e safely used programmatically. Wereflect this fact into the type system by the rule TSUB, whichsays that if a term a type checks logically, then it will also typecheck programmatically. For example, a logical term can alwaysbe supplied to a function expecting a p rogrammatic argument. T hisrule is useful to avoid code duplication. A function defined in thelogical fragment can be used without penalty in the p rogrammaticfragment.

Subsumption also eliminates duplication in the design of thelanguage. For example, we need only one type a = b to talk aboutwhen two p rogrammatic or two logical terms are equal. In fact, wecan also equate logical and p rogrammatic expressions.

3.2 Internalized Consistency Classification

To provide a general mechanism for logical expressions to appearin programs and programmatic values to appear in proofs, we in-troduce a type that internalizes the typing j udgment, written A@θ.Nonterminating programs can take logical p roofs as preconditions(with functions of type (x : A@L) → B), return them as post-(cowindthitf iounnsc i(ownitsho ffutn ycptieon (sx o :f Aty@peL )(x→ →: A B) ,→r t(uBr@nLt h)e)m, a ands sptoosrte-tchoenmdi itino dnast a(w sitthrucf utunrcetsi o(wnsito hf p tyaiprse (ofx t: y pAe) Σ →x →:( (AB. @(BL@))L,a) )n. dAs tt tohreesame t ime, logical lemmas can use @ to manipulate values from theprogrammatic fragment.

Page 26: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

judgTmheen rutΓl es ‘ foθr1t ahe: A A @@θθ ty2pheoa lpdpsei fart hi en fF riaggumreen4 t.θ I n1tumitaivyels ya,ft ehleyojubdsegrmveen ttha Γt Γ‘ ‘θ2 a : A. This intuition is captured b y the threeoinbtsroedrvuectt ihoant Γr ul e‘s. The programmatic fragment can internalize anytyping j udgement (TBOXP), but in the logical fragment (TBOXLand TBOXLV) we sometimes need a restriction to ensure termina-tion. Therefore, rule TBOXLV only applies when the subject of thetyping rule is a value. (The r ule T BOXL can introduce A@θ for anyθ since logical terms are also p rogrammatic). Both introduction andelimination of @ is unmarked in the syntax, so the reduction behav-ior ofan expression is unaffected by whether the type system deemsit to b e provably terminating or not.

For example, a recursive function f can require an argumentto be a p roof by marking it @L, e.g., A@L → B, forcing thattaorgu bema enp t rtooo fb eb cyhme ckarekdi ning fi rta@ gmL,ene t. gL.,. SA i@miLlar→ ly, aB l,ogf iocracli nlgem tmhaatg can be applied to a programmatic value b y marking it @P:

Γ ‘Pf :A @ΓL ‘ →PfB a :Γ BΓ‘ P‘ aLa: : A A @LTTABPOPXP

Γ ‘Lg: A @ΓP‘ → LgB v : ΓB Γ‘ L‘ vP: vA : A @PTTABPOPXLVOf course, g can only be defined in the logical fragment if it iscareful to not use its argument in unsafe ways. For example, usingTCONV we can prove a lemma of type

( n : Nat ) → ( f : (Nat → Nat )@P ) → ( f ( plus n 0 ) = f n )

because reasoning about f does not require calling f at runtime.

Page 27: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

There is no way to apply a logical lemma to a p rogrammaticnon-value expression. If an expression a may diverge then so may

Mobile(A) Mobile(A@θ)MAT

Mobile(a= b )MEQ MobMileob(iAle)(ΣxM :Aob.iBle)(B)MSIGMA

Mobile(Nat)MNAT MobiMleo(bAil)e(AM+ oB bil)e(B)MSUM

Γ‘ θa: AΓ ‘Pv :A Γ ‘LLAv : :A ? Mobile(A)TMVAL

Γ ‘θ a : (A1 + A2)@θ0 Γ ‘θ B : ?

Γ, x :θ0 A1, z :L inl x = a ‘Γθ b1 : B

Γ ‘θΓs,cxas: θe0zaA2 o,fz i:Lnlinx r⇒ x= b 1a ;in‘ rθx b2 ⇒:B b 2: B TSCASE’

Γ ‘θ a : (Σx: A1.A2)@θ0 Γ ‘θ B : ?

Γ,x :Γθ0‘ Aθ1p,cya: sθe0zAa2o ,fz : L(xh,x,y )yi⇒ = b a ‘ : B θb: B TPCASE’

Figure 5. Typing: mobile types and cross-fragment case expres-sions

Page 28: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

f a, so we must not assign it a type in the logical fragment.3 How-ever, we can work around this r estriction by either first e valuatinga to a value in the programmatic fragment or b y thunking.

The @-types are eliminated b y the rule TUNBOXVAL. To p re-serve termination, the rule is restricted to apply only to values. Webelieve it is possible to extend the system with three “unbox” rules,the symmetric twins of our three “box” r ules, and are exploring thisdirection in our current work.

Recall the function solve r of type

prog solve r : ( n : Nat ) → ( f : Fo rmula n )→ Vecto r (Maybe Bool ) n → (Ans n f )@L

In the introduction, we asserted that the following code type checks.

let prog isSat = ( solver n f empty : Ans n f @L) inlet log p rf = case isSat of

SAT a pf → - - . . . he re pf is logical . . .UNSAT → - - . . .

In this example, the logical program p rf cannot directly treatsolve r n f empty as a proof because it may diverge. However,once it has been evaluated to a value, it can be safely u sed b ythe logical fragment. Above, the let binding f orces evaluation ofthe e xpression solve r n f empty, introducing a new program-matic variable isSat : Ans n f @ L into the context. Becausevariables are values, any logical context can freely use the vari-able through T UNBOXVAL even though it was computed by theprogrammatic language.

3.3 Mobile types

The consistency classifier tracks which expressions are k nown to

Page 29: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

come from a normalizing language. For some types of values, how-ever, the r ules described so far can be unnecessarily conservative.For example, while a p rogrammatic expression of type Nat maydiverge, a programmatic value of that type is j ust a number, so we

3 This is one drawback of working in a strict r ather than a l azy l anguage. Ifwe know that f is nonstrict, then this application is indeed safe.

Page 30: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

can treat it as if it were logical. On the other hand, we can not treata programmatic function value as logical, since it might cause non-termination when applied.

The rule T MVAL (Figure 5) allows values to be moved fromthe p rogrammatic to the logical fragment. I t r elies on an auxiliaryjudgment Mobile (A).. Intuitively, a type is mobile if the same setof values inhabit the type when θ = L and when θ = P. Inparticular, these types do not include functions (though any typemay b e made mobile by tagging its fragment with @).

Concretely, the natural number type Nat is mobile, as is theprimitive equality type (which is inhabited by the single constructorrefl, as discussed in Section 2.2). Any @-type is mobile, since itfixes a p articular θ independent of the one on the typing j udgment.Sum and p air t ypes are mobile if their component types are.

Even if a sum type is not mobile, it is always safe to do one levelof pattern matching on one of its values, since such a value muststart with a constructor. W e reflect that in the r ule TSCASE’ ,whichgeneralizes TSCASE from the previous section. This rule allows ascrutinee that type checks in one fragment θ0 to be eliminated inanother fragment θ. This lets the logical language reason by caseanalysis on programmatic values. Similarly, TPCASE’ is a moregeneral version of the rule TPCASE. The two rules shown here arethe ones actually included in our formalization.

The mobile rule lets the p rogrammer write simpler types, be-cause mobile types never need to be tagged with logical classifiers.For example, without loss of generality we can give a function thetype (a = b) → B instead of ((a = b)@L) → B, since whentnyepedee( da, =t he bb)od →y o Bf thi nes tfuenadctio ofn( (caan =treba t) @thLe) )a→r gumB e,n sti nasc elow gihceanlthrough TMVAL. Similarly, multiple @’s have no effect beyond theinnermost @ in a type. Values of type A@P@L@P@L@P can beused as if they had type A@P.

In fact, the arguments to functions must always have mobile

Page 31: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

types. This restriction, enforced b y rule TARR, means that higher-order functions must use @-types to specify which fragment theirarguments b elong to. For example, the type (Nat → Nat) → A isnaorgtu uwmeelln-tfso rbmeleodn,g s too .thF eo programmer emt uyspt ec( hoNoaste → →eitN heart ()(→ NatA → isNnoattw )@elLl-)f →orm Aed o,rs o(( tNhaetp →ro Nraamt)m@ePr) m →us tAc .h

tI)n@ @eiLt)he→ r caA se o, programmers bte)@nePfi)t f→romA .implicit unboxing. Forexample, checking well-formedness of a type like

( f : ( Nat → Nat )@P) → f ( plus n 0 ) = f n

implicitly uses TUNBOXVAL. But the equation still talks aboutthe expression f n. If we instead had to use explicit unboxing toeliminate the @-type, as in ( unbox f ) n, there would b e no wayto write a logical lemma proving the original equation. By contrast,mobile arguments do not need nor benefit from tagging.

The reason that function arguments must b e mobile is to ac-count for contravariance. Through subsumption, we can introducea function in the logical fragment and use it in the p rogrammatic:

Γ, x :L A ‘L b : B

ΓΓ ‘‘LP((λλxx..bb)A): : ‘ ( ( xx: : AA)) →→ BB TTLSAUMBHere, the definition of b assumed x was logical, yet when thefunction is called it can be given a programmatic argument. Forthis derivation to be sound, we need to know that A means thesame thing in the two fragments, which is exactly what Mobile (A)checks.

4. Metatheory

We now describe the metatheory of λθ. We are interested in twoproperties. First, that the entire language is type safe, including

Page 32: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

both the L and P f ragments. Second, that any closed term in theL fragment normalizes, which implies logical consistency.

Type safety is p roven using standard progress and p reservationtheorems. Since the rules T CONV and TCONTRA allow stuck termsto type check given a contradiction, the progress theorem dependson logical consistency. For this reason, we first prove preservation,then normalization and consistency, and finally p rogress.

The theorems in this p aper have been checked in Coq. To provecertain f acts about our logical relation we needed a standard axiomof functional extensionality. This axiom is known to b e consistentwith Coq’s logic [41].

4.1 Preservation

As usual, the p reservation p roof relies on weakening, substitutionand inversion lemmas. The weakening lemma is standard. Due tothe value restrictions in the type system, the substitution lemma isrestricted to values:

LEMMA 1 (Substitution). IfΓ 1, x :θ0 B, Γ2 ‘θ a : A and Γ1 ‘θ0v : B, then Γ1 , [v/x]Γ2 ‘θ [v/x] a : [v/x]A.‘

bHeocwaeuvseer o,no euro if n tvheers dioesnigl enmg moaalssa o freλ m θoisret hc aotm typpliicnagter dult ehsan wiu thsuoault,runtime effects should not require annotation. In particular, u ses ofTCONV and TBOXP/L/LV are not marked.

For example, consider inversion for λ-expressions. Usually, it isthe case that if Γ ‘ (λx.b) : A, then A is β-convertible with somearrow type (txi : BΓ1‘ ) ( →λ xB.b2) a :n dA Γ,t ,h x : BA1i s‘β b- : Bnv2e. rItinb lλeθ wthitish s iso mnoettrue: if t here were a h ypothesis (x :L (Na‘t b→: BNat) = Nat) ∈ Γ,the expression could also have b een gi(vNena tty→ pe NNaatt ) u= singN Ta tC)O∈ NV Γ.,(Restricting preservation to empty contexts would not help, sinceat this point in the p roof—before proving consistency—we cannot

Page 33: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

rule out that this equality is provable). Alternatively, if the BOXrules were used, A may be an @-type. T aking this into account, ourinversion lemma r eads:

LEMMA 2 (Inversion for λ-expressions). I f Γ ‘θ (λx. b) : B,then there2 2is( Isnovmeers p nanf do r(λx -: eBxp1 )r →ssi Bon2s )s.u cIfh Γtha‘ t either

1. Γ ‘L p : B = ((x : B1) → B2) andΓ , x :θ B1 ‘θ b : B2,2. or there are some θ0 . . . →θ00B such that Γ ‘L p : B = (((x :

B1) → B2)@θ0 ...@θ00) a ndΓ , x h:aθ0t B1 ‘‘θ0 b : B2.

With this and other similar inversion lemmas, we can p rove preser-vation.

THEθOaR0E:MA 3. (Preservation).I fΓ ‘θ a :A a nda ;a0, then

The proof of the preservation theorem requires the additionof type constructor discrimination and injectivity rules (Figure 6)to the type system. The discrimination rule TCONTRA eliminatescontradictory equalities. If we can prove a contradiction we must bein unreachable code, so we allow giving any typeable expression aany wellformed type B at any θ0.

An equation B1 = B2 counts as contradictory if the headf ormsof both sides are defined and unequal. The head form of a type is itsoutermost constructor. For example, the head form of (x :A) → Boisu t→er,m manosdt tchoen shetraudc tfoorr.mF o oorf e Nxaamt pisl eN, tahte. T hehea dcof omrpmle otfe (dxef :iAni)ti o→n oBfihsd → →(A,) a appears e ina dAf popremnd oifxN NAa.

The injectivity r ules invert equality p roofs between type forms.For example, from a proof Γ ‘L p : ((x : A1) → A2) = ((x :BFo1r) e→xa mB2pl)e we can aalp soro odfer iΓve‘ Γ ‘L p : A1 = )B→1 . SA imilar typingrule)s→ →areB av)ai wlaeblc ea nfoa rl s@o, dsuermiv aenΓ d ‘pair types. These are elided h erefor space, but appear in the appendix.

Page 34: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

These rules are necessitated b y the weak inversion lemmas.Consider, e.g., the case when a function application b eta reduces,

t(hλaxt. Γb) ‘ vθ; (λ[ xv./bx)]: b. (F xro: m At 1h)e→ p reA m2isaensdo fΓ t h‘ eθr uvle :T A A1PP,wa nedk f nroowm

Page 35: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

Γ‘ θa: A hΓd‘ (BLa1)16 =:B hd1(=B2B )2ΓΓ ‘‘θθaA1: = ((x B: Γ1A: ‘1 ?)θ →a: A A2)1== ( B (x1: B1)→ B 2)TARRINV1ΓΓ‘ ‘ θθAaΓ: : ‘ A ? θ0aΓ: ‘ B θ0B: ? TCONTRA

Γ ‘θ a : ((x : A1) → A2) = ((x : B1) → B2)

Γ ‘θ0vΓ : A‘ θ1a :Γ[ v ‘/θx][Av/2x=]A[ 2v/=x][ vB/2x]B2:? TARRINV2

Figure 6. Typing: discrimination and injectivity of type constructors (injectivity rules for @-, µ-, pair- and sum-types omitted).

inversion we know either Γ ‘L p : ((x : A1) → A2) = ((x :iBnv1)e →sio nBw 2)e a knndo wΓ, x h:θe B Γ1 ‘‘θ b : B1, or el)se→ →(x : A1) → A2is p)r→ ovabB ly equal to an @-ty‘pe. In the first case we ap)p→ ly Athesubstitution lemma, using TARRINV 1 to p rove A1 = B1, whilein the second case we use TCONTRA.

4.2 Normalization and Progress

Our p roof of normalization b uilds upon the standard Girard-Taitreducibility method [17, 39] in a CBV-style formulation. The cruxof this method is to define a “type interpretation”. For each typeA we define a set of values Vρ [A]]kθ that check in fragment θ (theAaddw ietiod neafli nienp auts es ρ fanv da uke asrVe discussed below). The definition ofthe type interpretation (Figure 7) is a logical relation and followsthe structure of A.

Our main theorem is that the interpretation is “sound”: anyclosed logical expression a of type A reduces to a value in Vρ [[A]]kL.cTlohes erdu lleosg TicaUlN exBpOrXesVsiAoLn aa n dof Tt yMpeVA ALr cdaunc emso tovea vvaalluuees i nfro Vm P toL, so for the proof to go through we must generalize the soundnesstheorem to also characterize expressions in P. For these values weprove a partial correctness property: if a closed programmatic ex-pression a oftype A reduces to a value, then the value is in Vρ [[A]]kP.

Page 36: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

Titasht ideoesnfei Cni nρedv[[Aa mri]u]akθtnu,t swala hlriyceh ws ui idthmemn Vtaiρfr[i[ieAzse]]ds kθe.tb syo a f( c noomn-pvuatlautieo)ne axlpt ryepsesii onntesr,pa rned-Tehfien etydp me uitnutealrlpyrew taitthioV n for p rogrammatic expressions must ac-

count for recursive functions and recursive types, which meansthat it cannot b e defined by recursion on A. Instead, we use step-indexing [1, 5]. The interpretation is indexed by a number k. Anyvalue v i n Vρ [[A]]kP will b e “well-behaved” for at least k steps ofevxaleuceutv ioni n. TVhe interpretation is defined by well-founded r ecursionon the lexicographically ordered triple (k, A,I),where Iis one ofoCn not rh Ve ewxiithco oVg a<p Chic.

rH Voww evitehrV, Vth< e u Cs.ual formulation of a step-indexed type interpre-tation only lends itself to proving safety p roperties—it tells us thatan expression will not do anything bad for the next k steps. By con-trast, normalization is a liveness p roperty: every expression willeventually do something good (namely reduce to a value). In ourdefinition, we take a hybrid approach by only counting steps thathappen in the P fragment. The difference can b e seen b y compar-ing the definitions of Vρ [[(x : A) → B]]kL and Vρ [[(x : A) → B]]kP,winghict hhe say “inji i≤o ks”o afnV d “[[(j x<: Ak”) r→esp Bec]]tivaenlyd. VIf [a[(llx xθ: sA Ain) a→ →deB riv]]a-wtiohnic ahres aLy, t“hje n≤ n ko” ”ia nnedqu“ ajlit< iesk a”rer esstpriecct,t vsoe tyh.e I fs atellpθ -csoiu nna t kd nereivvae-r

needs to decrease.The input ρ is a substitution mapping free variables of A to

values. We use ρ when interpreting equality types. The type a1 =a2 is interpreted as the singleton set refl if ρ a1 and ρ a2 parallel-reduisc ien tteor par ectoemda msot hn eex sinpgrelsestoionns, eatn dr eafls ti hfeρ ρeampty set otherwise.We inductively define the judgment Γ |=k ρ, which asserts that ρ

maps dtou vctailvueelys i dne tfhinee ecto hrreej cutd digntmerepnrte tΓati| =on, by

·| =k∅ENIL Γ |=kρΓ,xv :θ ∈A Vρ| =[[Akρ]][kθx→7 Γv ‘ ]θA: ? ECONS

Page 37: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

Intuitively, Γ |=k ρ asserts that ρ maps term variables to well-bInehtuaivtieved yv,al uΓes| .= Because of the premise Γ ‘θ A : ? it also assertstbheahta vΓe ddov easl uneost. c Boenctaaiuns any tthyeppe rveamriiasebl eΓs.‘ This is vacuously truefor the empty context, and preserved b y each case of the typeinterpretation.

In a normalization p roof for System F or for CC [16], the typeinterpretation would t ake an input ρ which specifies the interpreta-tion of type variables in A, but not one which specifies the valuesof term variables. Since we do not h ave p olymorphism in our lan-guage, we do not need to account for type variables. But unlikeCC, because of the p rimitive equality t ype we can not j ust ignoreterm variables in t ypes. Our ρ is similar t o normalization proofs forsystems that have large elimination of datatypes, such as CIC [43].

The soundness theorem relies on a few key lemmas about theinterpretation. The first is a standard “downward closure” propertyfor step-indexed relations: it says that requiring values to staywell-behaved for a larger number of steps creates a more preciseinterpretation.

LEMMA 4. For any A, θ and ρ, if j ≤ k then Vρ [[A]]kθ ⊆ Vρ [[A]]jθ.

The next two lemmas are specific to λθ because they relate the Land P interpretations of a type. They are used to handle the TSUBand TMVAL rules, respectively. The first says that the set of logicalvalues is a subset of the corresponding programmatic sets.

CLρE[M[AM]]LkA⊆5.C F ρo[[rA]a ]kPn.yA , k, θ andρ , Vρ[[A]]kL ⊆ Vρ[[A]]kP andThe second says that for mobile types, the reverse containment

also holds. For these types, the interpretations contain the samevalues in both fragments.

Page 38: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

LEMMA 6. For any k and ρ, if Mobile (A) then Vρ [[A]]kP ⊆

Vρ[[A]]kL.Finally, for the TCONV rule, we need equal types to h ave the sameinterpretation.

LEMMA 7 . Suppose ρ B1 V∗ A and ρ B2 V∗ A and Γ ‘θ B1 :?andΓ ‘θ B2 : ? andΓ |=k ρ. Then a ∈ Iρ[[B1]]Akθ ai fnfa d Γ∈ ‘I ρ[[B2]]kθ.

We can now prove soundness by induction on Γ ‘θ a : A. Normal-Wizaet icoann i ns awn pimromveeds ioautne dconerossllb aryy.i nW duec atlioson ognet Γa ‘characterization ofwhich terms can b e p roven equal in the empty context. W e needsuch a characterization to prove progress.

THEOREM 8 (Soundness). I f Γ ‘θ a : A and Γ |=k ρ, thenρ a ∈ C ρ[[A8]]θk.(

COROLLARY 9 (Normalization).If · ‘L a : A, then there exists a value v such that a ; ∗ v.

COROLaL: ARA Y, 1h 0e ( Sthoeruend enxiesstss oaf v v parloupeov sits iuocnhalt heaqtuaa l;i ty).If · ‘L a : A1 = A2, then there exists some A such that A1 V∗ A

aInf d· A‘2 V∗ A.

Page 39: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

Vρ[[?]]kθ = v | · ‘θ v : ?

Vρ[[Nat]]kθ = v | v is of the form Sn Z

Vρ[[A@θ0]]kθ = v | ·‘ θ0 ρA : ? and v ∈ Vρ[[A]]kθ0

Vρ[[(x :A) → B]]kL = λx.b | · ‘L λx.b : ρ ((x :A) → B)xa.nbd ∀j ≤ k, ibf v ∈ Vρ :[[AA)]]jL→ →thB en) [v/x] b ∈ Cρ[x→7v] [B]]jL

∪ indand f x ∀.jb ≤| ·k ‘ ,L iifn vd ∈f x V.ρb[[A: ]ρ]jL(t(hxe: nA[ v)→ /x]B [λ)y.λz.(indf x .b)y /f] b∈ C ρ[x→7v][[B]]jLVρ[[(x :A)→ B ]]kP = λxan.bd |∀ · j‘ <Pλk x,.i bfv : ρ ∈ ( V(xρ[: [AA])]jP→ theB n)[ v/x]b∈ C ρ[x→7v][[B]]jP

∪ reacnf d x∀ .jb< |· k ‘ ,P irfe vc ∈f x V.ρb[[: A ]ρ]jP((thxe: nA[ )v→ /x]B [r)ecf x .b/f] b∈ C ρ[x→7v][[B]]jP∪ inadndf x ∀.jb< |· k ‘ ,P iifn vd ∈f x V.ρb[[A: ]ρ]jP(t(hxe: nA[ v)→ /x]B [in)df x .b/f] b∈ C ρ[x→7v][[B]]jP

Vρ[[A+ B ]]kθ =∪ iinnrlvv || · ·‘ ‘θθρρ((AA+ + B B )): :? ? a a nnddv v ∈ ∈ V V ρρ[[[[AB]]]k]θkθVρ[[Σx :A.B]]θk = hv1, v2i | · ‘θ ρ (Σx :A.B) : ? and v1 ∈ Vρ[[A]]kθ and v2 ∈ Vρ[x→7v1] [[B]]kθ

Vρ[[µx.A]]kθ0 = roll v | · ‘θ0 roll v : ρ (µx.A) and ∀j < k,v ∈ Vρ[[[µx.A/x]A]]jθ

Vρ [[a1 = a2]]kθ = refl | · ‘θ ρ (a1 = a2) : ? and ρ a1 V∗ a and ρ a2 V∗ a for some a

Vρ [[A]]kθ = ∅ otherwise

Cρ[[A]]kP = a | · ‘P a : ρA and ∀j ≤ k, if a ; j v then v ∈ Vρ[[A]](Pk−j)

Cρ [[A]]kL = a | · ‘L aa :: ρ AA aanndd a∀ j; ≤ ∗ kv, ∈ if Vaρ ; ;[[A]]Lk

Figure 7. Type interpretation

Normalization h olds only for closed terms. This is a result of thefact that uses of the TCONV rule are unmarked in the syntax. It ispossible to assume a contradictory equality and use it to typechecka non-terminating term in the logical fragment. For example, thefollowing statement is derivable:

y :L Nat = (Nat → Nat) ‘L (λx.x x) (λx.x x) : Nat

This distinguishes λθ from intensional type theories like Coq andAgda. In those systems, our rule TCONV arises as the pattern-matching elimination form for a defined equality datatype. U ses ofthis eliminator would appear in the term above, and their r eductionwould get “stuck” on the variable y, since it does not reduce to the

Page 40: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

appropriate constructor.The benefit of giving up normalization of open terms is a more

generous equality. Since uses of conversion appear in terms in Coqand Agda, they often get i n the way of judging two terms whichuse such conversions equal. In our system, this can not happen. Thedrawback is that the typechecker can not automatically normalizeexpressions (since they may diverge), so u ses of refl must be ex-plicit and annotated with a maximum step count. However, in a lan-guage with general recursion some explicit p roofs are unavoidable,since checking a logical term can involve reducing a programmaticterm that appears in its type. Since our language must accommodatesuch proofs in any case, making conversion unmarked is appealing.

The progress theorem r elies on a canonical forms lemma(elided). In the TCONV and TCONTRA cases we n eed to k nowthat there are no proofs of inconsistent equalities such as (Nat →Nthaatt)t e=r Na aret. Tohp erroeofforseo , fti hnics olensmimstean tree lqieusa loitnie sCos ruoclhla arys 1N0.a tT→h eprogress theorem is t hen an easy induction on · ‘θ a : A.

Surface language (Zombie)

⇓ (elaboration)

Annotated language (ZT derivations)

⇓ (erasure)

Core language (ZT)

Figure 8. Implementation

THEOREM 11 (Progress). I f · ‘θ a : A, then either a is a value,

Page 41: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

or there exis1ts1 a( P0 rsuogchre tshs)at. Iaf ;· ‘ a0.

5. Implementation

We have implemented a p rototype dependently-typed language,called Zombie, based on λθ. We h ave used this implementation togain experience with the features described in this paper. Indeed,all of the example code in this paper can be t ype-checked b your implementation. These, and other examples are available fordownload.

Our language includes several features which were left out ofλθ to k eep the normalization proof simple. Instead of a single sort?, Zombie includes a f ull predicative hierarchy [22], which al-lows b oth polymorphism and type-level functions. We also includea general form for parameterized r ecursive datatypes, which sub-sumes Nat, A + B, Σx :A.B and µx.A. Datatypes are alwaysmobile, and Zombie provides structural induction for all strictly

Page 42: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

positive datatypes (not j ust Nat) following [20]. Finally, Zombiedistinguishes between computationally relevant and irrelevant ar-guments [24], and includes a multiplace conversion operator, calledmulticonversion [34].

Adding these features to λθ would complicate the type interpre-tation, increasing the complexity of our machine-checked p roof farbeyond its current state. In p articular, to add predicative polymor-phism and type-level computation we would have to redefine ourtype interpretation as an induction over typing derivations, whichis very painful to do in Coq. However, b ased on work in p rogress,we are optimistic that the metatheoretic requirements of these ad-ditional features will have little interaction with the fundamentalconsistency mechanism proposed here.

The general structure of our implementation appears in Fig-

bulrees8 λ.θ Tihse thp eari tnteo rfno alurl an imgpulaegmeeZ nTta.tT iohnist lhaantgm uaogsetd c elofisneelsyt r heeseo mp--erational behavior of Zombie expressions. However, like λθ, typechecking is not decidable for Z T expressions. T herefore, the imple-mentation also includes an annotated version of ZT that supportssyntax-directed type checking, an approach we have explored inprevious work [34]. Annotated Z T is a direct r epresentation of Z Ttyping derivations, marking all uses of conversion, subsumption,cumulativity, and coercion to and from A@θ types. Furthermore,because r eduction may not terminate, annotations on refl controland limit the search for a common reduct when proving that twoterms are equal.

Directly working with ZT derivations incurs a considerable an-notation burden for p rogrammers. Therefore, the Zombie surfacelanguage makes these annotations optional. We are currently exper-imenting with a number of elaboration strategies to infer these an-notations. These include using bidirectional type checking [3 1] topropagate type information through terms, unification to automati-

Page 43: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

cally infer some dependent arguments, and congruence closure [27]to automatically infer equality proofs u sed in conversions.

For example, consider the p rojection functions (fst and snd)for dependent p airs shown below. T hese functions pattern matchtheir argument and r eturn its first and second components respec-tively.

data Sigma (A : Type ) ( B :A → Type) : Type w herePai r of ( x :A) ( y : B x )

log fst : [A :Type] ⇒ [ B :A → Type] ⇒ Sigma A B → Afst [A] [ B] p = case p of

Pai r x y → x

log snd : [A :Type] ⇒ [ B :A → Type] ⇒ ( p : Sigma A B)→ B ( f⇒st p )

snd [A] [ B] p = case p ofPai r x y → unfold ( fst p) in y

In the implementation of snd, unification can infer the arguments Aand B to fst (which were marked inferable b y the fat arrow⇒in thedeclaration of fst). Because not all expressions terminate, ⇒the p ro-grammer must explicitly ask the type checker to u nfold ( fst p )by β-reduction, which introduces the equation ( fst p ) = x intothe context. That equation is then automatically used to convert thetype of y from B x to B ( fst p) .

The examples we h ave implemented fall into two categories.The first includes the division and SAT-solving programs describedin Section 1. These examples illustrate how one can write proofsabout general r ecursive programs, and how general r ecursive pro-grams can r eturn proofs. Second, we h ave implemented functionsfor length-indexed lists (Vectors), finite sets represented as binary

Page 44: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

search trees, and data compression using run-length encoding, to-gether with proofs of their correctness. Since these functions usesimple structural recursion, they can b e done entirely in the logi-cal fragment. T hey show that although our core language requiresannotations on refl and conv, the overhead of t hese annotations ismanageable.

6. Related Work

In previous work, we introduced the p roof technique of h ybridstep-indexed/traditional logical relations, but for a simply-typedlanguage [12]. This p aper extends the normalization proof to amore expressive type system with dependent function types, anequality type, and conversion. It also improves the treatment of @-types by making them implicit. This change complicates the meta-theory (see Lemma 2) but makes the language more expressive andsimplifies the application rule.

Terminating S ublanguage. There are other dependently-typedlanguages which allow general recursion but identify a sublanguageof terminating expressions. Aura [18] and F∗ [38] do this using thekind system: expressions whose type has kind Prop are checked fornormalization. Types can contain values but not non-value expres-sions, so there is no way to write separate p roofs about p rograms.There also is no facility to treat programmatic values as proofs, e.g.a logical case expression cannot destruct a value from the nonter-minating fragment. 3

ATS [13], GURU [36], and Sep3 [20] are dependently-typedlanguages where the logical and p rogrammatic fragments are syn-tactically separate—in effect rejecting the r ule TSUB. One of thegains of this separation is that the logical language can be madeCBN even though the programmatic one is CBV, avoiding the need

Page 45: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

for thunking (as discussed in Section 3.3). To do inductive reason-ing, the Sep3 language adds an explicit “terminates” predicate.

Idris [10] is a full-spectrum dependently typed p rogramminglanguage that permits non-total definitions. Internally, it applies asyntactic test to check if function definitions are structurally de-creasing, and p rogrammers may ask whether p articular definitionshave been j udged total. The type checker will only reduce expres-sions that have b een proved terminating, again precluding separateequational reasoning about partial p rograms. Idris’ metatheory hasnot b een studied formally.

Partiality M onad. Capretta’s partiality monad [11] u ses coin-ductive types to embed general recursion into Type Theory. Thisapproach treats pure functions as the default and nonterminationless conveniently. Nonterminating programs must be written usingmonadic combinators (and are therefore n ever syntactically equalto p ure programs). The partiality monad provides r ecursive func-tion definitions but not general r ecursive types.

Furthermore, the coinductive approach requires a separate no-tion of equivalence to reason about partial programs. In, e.g., Coq,one would compare p ure expressions according to the standard op-erational semantics, but define a coarser equivalence relation forpartial terms t hat ignores the number of steps they t ake to nor-malize. Equations like ((rec f x.b) v) = [v/x] [rec f x.b/f] bdo not hold with the u sual Coq equality because the step countsdiffer. Conveniently p rogramming with equivalence relations likethis, which are not directly j ustified by the reduction behavior ofexpressions, is an active area of research involving topics such assetoids [8], quotient t ypes, and the univalence axiom [42].

Non-constructive fixpoint s emantics. The work of Bertot andKomendantsky [9] describes a way to embed general recursivefunctions into Coq that does not use coinduction. They define a

Page 46: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

datatype partial A that is isomorphic to the usual Maybe A butis understood as r epresenting a lifted CPO A⊥, and use classicallogic axioms to provide a fixpoint combinator fixp. When defininga recursive function the user must prove continuity side-conditions.

Page 47: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

Since recursive functions are defined nonconstructively they cannot be reduced directly, so instead one must r eason about themusing the fix-point equation.

Partial Types. Nuprl has at its core an untyped lambda calculus,capable ofdefining a general fixed point combinator for defining re-cursive computations. In the core type theory, all expressions mustbe proven terminating when used. Constable and Smith [14] inte-grated potentially nonterminating computations through the addi-

ttoiornt ho efna h t ayspt eyp Ae( o Afp → artiA al) te→ rmA s.o H fot ywpeeveA r,.t T oh peref sixerpvoeint theo pc eoran--tsoirstet nhceyn ohafs stht ey leog( Aic, →the Aty)p e→ →A Am.u Hsot wbee v reers,trt oictep dre tseor vadem thiess icbolne.-types. Crary [15] provides an expressive axiomatization of admissi-ble types, but these conditions lead to significant proof obligations,especially when using Σ-types.

Smith [35] provides an example which shows that Nuprl n eedsthis restriction. Writing a ↓ for “a terminates”, define a Σ-type Tothfi fsu rnescttrioicntiso wnh. iWchr tainreg n ao t↓ tfo otarl,“ aant de mreicnuarsteisve”l,yd defeifnineea aΣ p ywpheicT hinhabits T.

Total (f : N → N ) =def (n :N) → (f n)↓

T =def Σ(f : N → N).Total f → False

(p : T) =def fix (λp.hg, λh.—i)

g =def λx.if x = 0 then 0 else π1(p)(x − 1)

Here the dash is an (elided) proof which sneakily derives a con-tradiction using π2 (p) and the hypothesis h that g is total. On theother hand, a separate induction shows that π1 (p) is total; it returns0 for all arguments. This is a contradiction.

λθ has almost all the ingredients for this paradox. Instead of arecursively defined pair we can use a r ecursive function Unit → T,arnecdu rwsiev cealny edenfciondede apa↓i raws Σec (ya n: uAse) .aa e=c y. Wivehfa ut snactvieosn u Us nisi tth→ at t The,aprndoow f ienc athne e snceocodneda ↓coa mspΣ o(nyen: tA Ao)f. p u=sey s. Wtheh aftols laovweisnu gs riseat hsoantti hneg

Page 48: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

principle: if π1 (p) terminates, then p t erminates. In Nuprl a ↓ isa p rimitive pre(dipc)att ee amnidn athteiss, ti hnveenrsp iot ne mpriinncaitpesle. Iins bN uuipltr lina . B↓i utsusing our encoding, a function (π1 (p) ↓) → (p ↓) would have tomagically guess the second compon(epn)t ↓o)f a→ →pa( irp k↓ n)ow woinugld oh nalyve etht eofirst component. If we assume this function as an axiom we canencode the paradox and derive inconsistency , so our consistencyproof shows that there is no way to write such a function.

Hoare Type Theory. HTT [26, 37] is another embedding of gen-eral programs into a type theory like Coq, which goes beyond non-termination to also handle memory effects. Instead of a unary typeconstructor A , it adds the indexed type Px : AQ r epresentingcano nesftfreuccttfourl Aco,mi tpa udtadtsiot hne er e intdurenxiendg tyAp ean dP Pwixth: pre- anr de pprosetscenotnindgi-tions P and Q. The assertions P and Q can use all of Coq, so thetype of a computation can specify its behavior precisely. However,computations can not b e evaluated during type checking (the fix-point combinator and memory access primitives are implementedas Coq axioms with types but no r eduction rules).

Fixpoint i nduction Domain-theory based formalisms providetwo b asic reasoning p rinciples for proving properties about re-cursive functions: unfolding a function definition, and fixpoint in-duction. The latter p rinciple (see e.g. [44]) states that to prove aproperty about a function, one may assume it as an induction hy-pothesis for the recursive calls of the function. For t his to be valid,the property must b e “admissible”, and it most h old for infiniteloops. An equivalent variant [9] is to allow induction on the num-ber of r ecursive steps an expression takes to normalize.

λθ currently provides no such principle. If a theorem can not beproved j ust from unfolding, there are two ways to proceed. In orderto prove div_le in Section 1 we used (strong) natural-numberinduction. For this strategy to work the p rogrammer has to find atermination metric for the function in question, so it only works

Page 49: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

for functions that are in fact terminating. However, it can still beconvenient to give a direct r ecursive definition of the function. Forfunctions that genuinely do not terminate, one can instead changethem to return a Σ-type asserting the property, so t hat the propertyis automatically available for recursive calls. This is what we didfor solve r in Section 1, and it is the only option i n Hoare TypeTheory.

Modal t ypes for d istributed c omputation. Modal logic reasonsabout statements whose truth varies in different “possible worlds”.Our type system is formally similar, with the possible worlds b eingL and P. Modal logic has previously been u sed to design typesystems for distributed computation [19, 25]. In particular, λθ wasinspired b y ML5 [25], in which the typing judgment is indexedby what “world” (computer in a distributed system) a programis running on, and which includes a type A@θ internalizing thatjudgment. Our rule T MVAL is similar to the GET rule in M L5, andour Mobile (A) is similar t o the judgment A mobile i n ML5. Onthe other hand, unlike λθ, ML5 does not require that the domain ofan arrow type be mobile. As we explained in Section 3.1 we makethat restriction to accommodate our rule TSUB, a r ule which doesnot make sense in the context of distributed computation.

7. Future work

In future work, we hope to extend the metatheory of λθ to includemore of ZT. We plan to allow polymorphic types and type-levelfunctions in b oth the L and P f ragments, extending our proof us-ing ideas from normalization proofs for the Calculus of Construc-tions [16]. F ollowing the ideas of Ahn and Sheard [2] and their

Page 50: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

language Nax [3], we also hope to add combinators to define re-cursive functions over recursive data to the logical language. Naxplaces no restriction on what sorts of datatypes can b e defined orhow they can b e constructed. Instead, it limits the analysis of datastructures to ensure the soundness of the logic. M ore generally, wewould like to extend our p roofs to a general theory of datatype def-initions, maybe encoded via recursion, sums, and products as inΠΣ [4]. One p otential worry is that we assume injectivity for alltype constructors, which can b e used to encode Cantor-like p ara-doxes. We h ope to avoid inconsistency b y forbidding i mpredicativepolymorphism and datatypes with “large” indices.

Adding these features will require substantial additional workin the normalization p roof, but we do not anticipate any changes tothe novel typing r ules that connect the L and P fragments.

Reasoning a bout general recursivef unctions Currently λθ em-phasizes lightweight verification. In order to turn it into a tool forfull verification of potentially nonterminating programs, we wouldadd stronger r easoning principles.

First, the value restrictions in;can get in the way ofequationalreasFoirnistn,gt.h eIfv aal uise arens terxicptrioensssiionn ;in cPa nthgeertei nist hneow wayayo ftoe q puraovtieo naanl

equation like (let x = a in f x) = (f a), even though the two sidesare in fact contextually equivalent. T o make it provable we couldadd termination-case—a case analysis on whether a p rogrammaticexpression evaluates to a value or diverges [20]. Unfortunately, t hisoperator is unimplementable, so we would not want to allow p roofsthat use this reasoning to b e used as programs. One solution is tointroduce a new consistency c lassifier O, for oracular, in additionto L and P. By not allowing O expressions to b e used as p rograms,we could control and track the use of termination case.

Second, we would like to i nvestigate whether some (perhaps

Page 51: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

weakened) form of fixpoint induction can be consistently added.The experience with partial types in Nuprl suggests that t his mayrequire a notion of admissible predicates.

Page 52: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

8. Conclusion

This p aper presents a framework for interacting logics and pro-gramming languages. The consistency classifiers, θ, describe theset of typing r ules that determine the properties of each well-typedexpression. At the same time, many standard typing r ules are p oly-morphic in this classifier, leading to uniformity between the sys-tems. I nternalizing thisj udgment as a type and observing that somevalues can move freely allows the fragments to interact in nontriv-ial ways, leading to an expressive foundation for dependently-typedprogramming.

Acknowledgments

This material is based upon work supported by the National ScienceFoundation u nder Grant Nos. 0910500 and 1116620. The Zombieimplementation was developed with the assistance of the Trellysteam, and the ideas in this p aper b enefitted greatly from that col-laboration. This p aper was written with the help of the excellentOtt tool [32]. The authors would also like to t hank the anonymousreviewers for their considered and helpful comments.

References

[1] Ahmed, A.: Step-indexed syntactic logical r elations for recursive andquantified types. In: E SOP ’06: European Symposium on Program-ming. L NCS, vol. 3924. Springer (2006)

[2] Ahn, K.Y., Sheard, T.: A h ierarchy of mendler style r ecursion com-binators: taming inductive datatypes with negative occurrences. In:ICFP ’ 11: International Conference on F unctional p rogramming. pp.234–246. ACM (201 1)

Page 53: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

[3] Ahn, K.Y., Sheard, T., Fiore, M., Pitts, A.M.: The Nax p rogramminglanguage (work in progress) (2012), talk p resented at IFL 2012: the24th Symposium on Implementation and Application o f F unctionalLanguages

[4] Altenkirch, T., Danielsson, N .A., L öh, A., Oury, N.: ΠΣ: D ependenttypes without the sugar. Functional and Logic Programming pp. 4 0–55(2010)

[5] Appel, A.W., McAllester, D.: An indexed model of recursive types forfoundational proof-carrying code. ACM Trans. Program. L ang. Syst.23(5), 657–683 (2001)

[6] Augustsson, L.: Cayenne – a language with dependent types. In: ICFP’98: International Conference on Functional P rogramming. pp. 239–250. ACM (1998)

[7] Barendregt, H.P.: Lambda calculi with types. In: Abramsky, S., Gab-bay, D.M., Maibaum, T .S.E. (eds.) Handbook of L ogic in ComputerScience. pp. 117–309. Oxford U niversity Press (1992)

[8] Barthe, G., Capretta, V., Pons, O.: Setoids in type theory. Journal ofFunctional Programming 13(2), 261–293 (2003)

[9] Bertot, Y., Komendantsky, V.: F ixed point semantics and partial re-cursion in coq. In: PPDP ’08: Principles and practice of declarativeprogramming. pp. 89–96. ACM (2008)

[10] Brady, E.C.: Idris—systems p rogramming meets full dependent types.In: PLPV’ 11: Programming languages meets program verification. pp.43–54. ACM (201 1)

[11] Capretta, V.: General recursion via coinductive types. Logical Meth-ods in Computer Science 1(2), 1–18 (2005)

[12] Casinghino, C., Sjöberg, V., Weirich, S.: Step-indexed normalizationfor a language with general recursion. In: M SFP ’ 12: Mathemati-cally Structured Functional Programming. EPTCS, vol. 76, pp. 25–39(2012)

[13] Chen, C., Xi, H.: Combining p rogramming with theorem proving.

Page 54: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

In: Proceedings of the tenth ACM SIGPLAN international con-ference on F unctional programming. pp. 66–77. ICFP ’05, ACM,New York, NY, USA (2005), http ://doi .acm . o rg/10 . 1145/1086365 . 1086375

[14] Constable, R.L., Smith, S.F.: Partial objects in constructive type the-ory. In: Logic in Computer Science (LICS’87). pp. 183–193. I EEE(1987)

[15] Crary, K.: Type T heoretic Methodology for Practical P rogrammingLanguages. Ph.D. thesis, Cornell University (1998)

[16] Geuvers, H.: A short and flexible proof of Strong Normalization forthe Calculus of Constructions. In: TYPES ’94. L NCS, vol. 996, pp.14–38 (1995)

[17] Girard, J .Y.: Interprétation fonctionelle et é limination des coupures del’arithmétique d’ordre supérieur. P h.D. thesis, Université P aris VII(1972)

[18] Jia, L., Vaughan, J.A., Mazurak, K., Zhao, J., Zarko, L., Schorr, J.,Zdancewic, S.: AURA: A programming language for authorizationand audit. In: ICFP ’08: International Conference on FunctionalProgramming). pp. 27–38. ACM (2008)

[19] Jia, L., Walker, D.: Modal p roofs as distributed programs (extendedabstract). In: ESOP’04: European Symposium on P rogramming.LNCS, vol. 2986, pp. 219–233. Springer (2004)

[20] Kimmell, G., Stump, A., Eades III, H.D., Fu, P., Sheard, T., Weirich,S., Casinghino, C., Sjöberg, V., Collins, N., Ahn, K.Y.: E quationalreasoning about programs with general recursion and call-by-valuesemantics. In: PLPV ’ 12: Programming languages meets programverification. ACM (2012)

[21] Licata, D.R., Harper, R.: Positively dependent types. In: PLPV ’09:Programming languages meets program verification. pp. 3–14. ACM(2008)

[22] Luo, Z.: Computation and R easoning: A Type Theory for ComputerScience. Oxford University P ress, USA (1994)

Page 55: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

[23] McBride, C., McKinna, J.: The view from the left. J . Funct. Program.14(1), 69–1 11(2004)

[24] Miquel, A.: The implicit calculus of constructions - extending p uretype systems with an intersection type binder and subtyping. In: TLCA’01 : Proceeding of 5th international conference on Typed L ambdaCalculi and Applications. LNCS, vol. 2044, pp. 344–359. Springer(2001)

[25] Murphy, VII, T., Crary, K., Harper, R.: Type-safe distributed program-ming with ML5. In: Trustworthy Global Computing 2007 (2007)

[26] Nanevski, A., Morrisett, G., Shinnar, A., Govereau, P., B irkedal, L.:Ynot: dependent types for imperative p rograms. In: ICFP ’08: Inter-national Conference on F unctional Programming. pp. 229–240. ACM(2008)

[27] Nieuwenhuis, R., Oliveras, A.: Fast congruence closure and exten-sions. Inf. Comput. 205(4), 557–580 (2007)

[28] Norell, U.: Towards a p ractical programming language b ased on de-pendent type theory. Ph.D. thesis, Chalmers University of Technology(2007)

[29] Peyton-Jones, S., Vytiniotis, D., Weirich, S., W ashburn, G.: Simpleunification-based type inference for GADTs. In: ICFP ’06: Inter-national Conference on F unctional Programming. pp. 50–61. ACM(2006)

[30] Pierce, B.C.: T ypes and Programming Languages. MIT Press (2002)

[31] Pierce, B.C., Turner, D .N.: Local type inference. In: ACM SIGPLAN–SIGACT Symposium on P rinciples of Programming L anguages(POPL), San Diego, California (1998)

[32] Sewell, P., Nardelli, F., Owens, S., Peskine, G., Ridge, T., Sarkar, S.,Strnisa, R.: Ott: Effective tool support for the working semanticist. J .Funct. Program. 20(1), 71–122 (2010)

[33] Sheard, T., Linger, N.: Programming in ωmega. In: Horváth, Z.,Plasmeijer, R., Soós, A., Z sók, V. (eds.) 2nd Central European Func-tional Programming School (CEFP). LNCS, vol. 5161, pp. 158–227.

Page 56: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

Springer (2007)

[34] Sjöberg, V., Casinghino, C., Ahn, K.Y., Collins, N., E ades III, H.D.,Fu, P., Kimmell, G., Sheard, T., Stump, A., Weirich, S.: Irrelevance,heterogeneous equality, and call-by-value dependent t ype systems.In: MSFP ’ 12: Mathematically Structured Functional Programming.EPTCS, vol. 76, pp. 112–162 (2012)

[35] Smith, S.F.: Partial Objects in Type Theory. Ph.D. thesis, CornellUniversity (1988)

[36] Stump, A., Deters, M., Petcher, A., Schiller, T., Simpson, T.W.: Ver-ified p rogramming in guru. In: Altenkirch, T., Millstein, T.D. (eds.)PLPV. pp. 49–58. ACM (2009)

[37] Svendsen, K., Birkedal, L., Nanevski, A.: Partiality, state and depen-dent types. In: T yped lambda calculi and applications (TLCA’ 11).LNCS, vol. 6690, pp. 198–212. Springer (2011)

[38] Swamy, N., Chen, J., Fournet, C., Strub, P.Y., Bhargavan, K., Yang,J.: Secure Distributed Programming with Value-dependent T ypes. In:ICFP ’ 11: International Conference on Functional Programming. pp.285–296. ACM (2011)

[39] Tait, W.W.: Intensional interpretations of functionals of finite type i.The Journal of Symbolic Logic 32(2), pp. 198–212 (1967)

[40] The Coq Development T eam: The Coq Proof Assistant ReferenceManual, Version 8.3. INRIA (2010), http : //coq . in ria .f r/V8 .3/ refman/

[41] The Coq Development Team: The Coq Proof Assistant, FrequentlyAsked Questions. INRIA (2011), http : //coq . in ria .f r/faq/

[42] The Univalent Foundations Program: Homotopy Type Theory: Univa-lent Foundations of Mathematics (2013), http : //a rxiv . o rg/abs/1308 .0729

[43] Werner, B.: Une Théorie des Constructions Inductives. Ph.D. thesis,Université Paris 7 (1994)

[44] Winskel, G.: The formal semantics of p rogramming languages: anintroduction. MIT Press, Cambridge, MA, USA (1993)

Page 57: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

A. The λθ Type System

θ ::= L | P

a, b,A ,B ::= ||hx ?a |, | λb (xix |.:a Apc| )a r→s ecezf B ax o .| af a | = ( ixn,bd y|f N) x ⇒ .aatb | | aA |+ bZ | B r |eS | fla Σ | ix | nnl : Aaca.Bs| e inz| rµ abx o| .Afs c a| ZsA e⇒ @zθaa 1o ;fS x inl⇒ x ⇒ a 2a 1|;r oinllray | ⇒ u na ro2llav ::= ? | (x : A) → B |a = b | Nat | A + B | Σx :A.B | µx.A | A@θ

| x? ?| |λ (xx. :aA A| )r→e c f B Bx|. aa a| =inbd | f Nx.a at || rAef+ l +| Binl| vΣ Σ|x i :nAr .vB B| h|µ v1x , .vA2i || AZ@ @| S v | roll v

Γ ::= ·| Γ, x :θ A

headform ::= ? | → | @θ | Nat | + | Σ | =

Call-by-value r eduction

a1;a 2

ncasezZ of Z⇒ a 1;Sx ⇒ a 2; [refl/z]a1SCZ ncasezS vo f Z⇒ a 1;Sx ⇒ a 2 ;[ refl/z][v/x]a2SCS

scasezinlvo f inlx ⇒ a 1;inrx ⇒ a 2; [ refl/z][v/x]a1SCL scasezinrvo f inlx ⇒ a 1;inrx ⇒ a 2; [ refl/z][v/x]a2SCR

pcasezhv1,v2io f (x,y )⇒ a ; [ refl/z][v1/x][v2/y]aSCP (recf x.a)v ; [ v/x][recf x .a/f] aSFUN

(λx.a) v; [ v/x]aSLAM (ind f x.a)v ; [ v/x][λy.λz.(indf x .a)y /f] aSIND unroll(rollv); v SUNROLLa;b a;a0

S aa; ; S b b SSUCC1 ncaseza of Z⇒ a1;Sx ⇒ a2a;; an caseza0of Z⇒ a 1;Sx ⇒ a 2SNCASE1a;b a;b a;a0

inlaa;; i b nlbSINL1 inraa;; i b nrbSINR1 scasezao f inlx ⇒ a 1;inr x⇒ a 2a;; s a caseza0of inlx ⇒ a 1;inrx ⇒ a 2SSCASE1a;a0 a;a0 a;a0

ha,bai; ; h a a0,biSPAIR1 hv,aai; ; h a v,a0iSPAIR2 pcasezao f (x, y)⇒ a 1a; ; a p caseza0of (x,y )⇒ a 1SPCASE1a;b a;b a;a0 b;b0

rollaa;; r b ollbSROLL1 unrollaa;; b unrollbSUNROLL1 aab ;; a a 0bSAPP1 v bb; ; v b b 0SAPP2

Mau1l;ti-skteap2c all-by-valuer eductiona; 0aMSREFL ab ;; 1+kb kbb00MSSTEP

PaarV alleb lc all-by-valuer eductionaV a PREFL

ncasezZ of Z⇒ aa 11;VSx a ⇒ 10a 2V [ refl/z]a10PCZ ncasezSv of Z⇒v V a1v ;0S xa⇒ 2V a2a 20V [ refl/z][v0/x]a20PCS

scasezinlvo f inl xv⇒ V a v1 0;inrax 1⇒ Va a 210V [ refl/z][v0/x]a10PCL scasezinrvo f inl xv⇒ V a v1 0;inrax 2⇒ Va a 220V [ refl/z][v0/x]a20PCR

Page 58: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

pcasezhv1,v2iv1o Vf (v x10,y )v⇒ 2V bv 20V [brefV l/zb ][0v02/y][v10/x]b0PCP (recf x .a)vv V Vv 0[v0/ax]V[ reca 0f x .a0/f] a0PFUN

(λvx.V a)v v 0V a[ vV 0/xa ]a00PLAM (ind fx .a)v Vv [vV 0/xv 0][λya.λzV .(ai n0df x .a0)y /f] a0PIND unrollv(rVo llvv 0)V v 0PUNROLL

a V a0 a V a0 a V a0rec fx .aV r ecf x .a0PFUN1 λx.aV λx.a0PLAM1 ind fx .aV i ndf x .a0PIND1

S aaV V S b b PSUCC1 ncasezao f Z ⇒a 1a;V Sx a ⇒ 0a 2a1V Vn a 1c0aseaz2aV0ofa 20Z⇒ a 10;Sx ⇒ a 20PNCASE1

inlaaVV i b nlbPINL1 inraaVV i b nrbPINR1 scasezao f inlx ⇒ a1a;in Vrx a ⇒ 0a 2a1V Vs a c10aseza2aV0ofa 2 0inlx ⇒ a 10;inrx ⇒ a 20PSCASE1

aha V,bia V0 hba0V ,b0b i0PPAIR1 pcaseza of (x,y )a ⇒V ba 0V p bcaV sebz 0a0of (x,y )⇒ b 0PPCASE1

rollaaVV r b ollbPROLL1 unrollaaVV b unrollbPUNROLL1 a Vab a 0V a b0V b0b 0PAPP1

A V A0 B V B0 A V A0(x :A) →B V ( x: A0)→ B 0PARR1 A@θV A 0@θPAT1

a V a0 b V b0a =b V a 0=b 0PEQ1

Ma1ultVi-s∗teap2p arallelc all-by-valuer eduction

aV ∗aMPREFL

MMoobbiliele t(yApe)s

Page 59: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

A V A0 B V B0 A V A0 B V B0A+ B V A 0+B 0PSUM1 Σx: A.BV Σ x: A0.B0PSIGMA1

µx.AAV Vµ A x0.A0PMU1

a V bb V∗ b0

aV ∗b0MPSTEP

Mobile(Nat)MNAT Mobile(a= b )MEQ Mobile(A@θ)MAT

MobiMleo(bAil)e(AM+ oB bil)e(B)MSUM MobMileob(iAle)(ΣxM :Aob.iBle)(B)MSIGMA

Hhefa (dAf o)r= mhshf (?) =? HSTAR hf ((x :A)→ B )= →HARR hf( A@θ)= @ θHAT hf (Nat)= N atHNAT

hf( A+ B )= + HSUM hf (Σx :A.B)= ΣHSIGMA hf( µx.A)= µ HMU hf( A= B )= =HEQ

W‘eΓ ll-formedc ontexts

Page 60: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

‘· CNIL

TΓyp‘ inθga: A(x :θA)θ∈ xΓ : A ‘Γ TVAR

Γ, x :L A ‘L b :

‘ Γ ‘ Γ Γ ‘θ A : ?

‘ Γ,‘xΓ : θ?CSTAR ‘ Γ‘ Γ,Γx‘ : θACTYPE

ΓΓ,Γ‘ xθ ‘: AθθA(: x? ‘ :θAB)M→ : ob? B ile: (? A)TARR ΓΓ ‘‘θθabΓ: :‘ (A θxb :A aΓ): →‘ [θa/B [xa]/Bx]B: ? TAPPB Γ,f :P (x : A) → B, x :P A ‘P b : B

ΓΓ‘ L‘ λLx(.xb : A:( )x→ :AB )→ :? B TLAM Γ ‘ΓP(‘ xP :rAe)c→ fx B .b :: ? ( x: A)→ B TREC

Page 61: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

Γ, x :L Nat,f :L (y :Nat) → (z : S y = x) → B ‘L b : B

Γ ‘L(x :NatΓ)→ ‘ L Bind: ? f x .b: ( x: Nat)→ B TIND

‘ Γ ‘ Γ Γ ‘θ a : NatΓ ‘L‘NΓ at: ? TNAT Γ‘ L‘ZΓ : N atTZERO ΓΓ‘ ‘ θSa : N atTSUCC

Γ ‘θ A : ? Γ ‘θ a : A Γ ‘θ b : BΓΓ ‘‘θ B : ? ΓΓ ‘‘θ A + B : ? ΓΓ ‘‘θ A + B :?

Γ Γ‘θ‘ A+ B : ?TSUM ΓΓ‘ ‘θ inla: A + B TINL ΓΓ‘ ‘θ inrb: A + B TINR

Γ ‘θ a :NatΓ, z :L Z = a ‘θ b1 : B Γ ‘θ a : A1 + A2 Γ ‘θ B : ?

Γ, x :θ ZN=a t, z :‘L (S x) = a ‘θ b2 : B Γ, x :θ A1, z :L inl x = a ‘θ b1 : B

Γ‘ Γθ‘ ncθaBse: z? ao f Z⇒ b 1;Sx ⇒ b 2: B TNCASE Γ ‘θΓsc,axse: zθAa 2of,z :i nLlinx r ⇒x= b 1;a in‘ rθ xb⇒ 2:B b 2: B TSCASE

Γ ‘θ Σx :A.B : ?

Γ ‘θ A : ? ΓΓ ‘‘θ a : AΓM‘o bile (A) ΓΓ ‘‘θ b : [a/x]B Γ ‘θ a :Σx :A1.A2 Γ ‘θ B : ?

Γ,xθ :θΣAx: ‘ Aθ.BB: : ? ? TSIGMA ΓΓ‘ θ ‘hθa[,ab/ix: ]Σ Bx: : A? .BTPAIR Γ,xΓ: θ ‘Aθ1p,yca: sθezAa2, ozf : L(xhx,,y y)i ⇒= b a ‘ : θB b: B TPCASE

Γ,Γx ‘: LL?µx‘ .ALA: : ? ? TMU ΓΓΓ‘ ‘ ‘θθθaµrx: o.lA[l µax: .: ? Aµ /xx.A]ATROLL Γ ‘PaΓ: ‘ µPxu.AnrollΓa: ‘ [µPx[µ.Ax/.Ax/]Ax]A: ? TUNROLL

Γ‘ Pa: LA a =Γb ‘ : P? b :B TEQ ΓaV ‘θ∗1caL: A rbef Vl: Γ∗a ‘ c= θ2b b: B TREFL ΓΓ ‘‘ θLb[b: 2/b 1xΓ]=A ‘θb: 2a? : [Γb2/‘ xθ]Aa: [ b1/x]ATCONVΓ ‘L a1 : B1 = B2hΓd‘ (B1) = hd(B2)Γ ‘θ a : =AhΓ ‘‘θ A : ? Γ ‘θ0 B : ?

Γ ‘Γ ‘θ0aΓ: ‘ BTCONTRA

Γ‘ PLaa: : A A TSUB Γ ‘Pv :A Γ ‘LLAv : :A ? Mobile(A)TMVAL Γ‘ θAθ0@Aθ0 :? :? TAT

Γ ‘θ a : A Γ ‘L a : A Γ ‘P v : A Γ ‘θ v : A@θ0ΓΓ ‘‘θ A : ? ΓΓ ‘‘θ A : ? ΓΓ ‘‘P A : ? Γ ‘‘θ0 A : ?

ΓΓ ‘P‘ a: A @θTBOXP ΓΓ ‘L‘ a: A @θTBOXL ΓΓ ‘L‘ v: A @PTBOXLV ΓΓ‘ ‘ θ0v: A TUNBOXVAL

ΓΓ ‘ ‘θθaA: = (θA Ba@: : θA ? 0) = =B ( B@θ0)TATINV ΓΓΓ‘ ‘ ‘ θθθaa([µ : :x( ( µ[.µAxx/.A.xA)]A/ x=)]=A ( µ)( x[= µ.Bx( ).[Bµx/.xB]B/x)]: B? )TMUINVΓ ‘θ a : ((x :A1) → A2) = ((x :B1) → B2)

Page 62: Combining Proofs and Programs in a Dependently Typed ... · Keywords Dependent types; Termination; General r ecursion 1. Introduction Dependently typed languages have developed along

Γ ‘θA1=B Γ1 :‘? θa: A 1=B 1TARRINV1

Γ ‘θ a : (Σx :A1.A2) = (Σx :B1.B2)

Γ‘ θA1=Γ ‘B1θ:a? : A 1=B 1TSIGMAINV1

Γ ‘θ a : (A1 + A2) = (B1 + B2)

Γ ‘θA1Γ= ‘Bθ 1a:: ? A 1=B 1TSUMINV1

Γ ‘θ a : ((x :A1) → A2) = ((x : B1) → B2)

Γ ‘θ0vΓ : A‘ θ1a :Γ[ v ‘/θx][Av/2x=]A[ 2v/=x][ vB/2x]B2:? TARRINV2

Γ ‘θ a : (Σx :A1.A2) = (Σx :B1.B2)

Γ‘ θ0vΓ: A‘ θ1a :Γ[ v ‘/θx][Av/2x=]A[ 2v/=x][ vB/2x]B2:? TSIGMAINV2

ΓΓ ‘‘θθAa2:Γ ( = A‘θ1B a2+: :A A ? 22)== B( B21+B 2)TSUMINV2