(** So far, we have seen many examples of what we might call %``%#"#classical program verification.#"#%''% We write programs, write their specifications, and then prove that the programs satisfy their specifications. The programs that we have written in Coq have been normal functional programs that we could just as well have written in Haskell or ML. In this chapter, we start investigating uses of %\textit{%#<i>#dependent types#</i>#%}% to integrate programming, specification, and proving into a single phase. *)
(**Sofar,wehaveseenmanyexamplesofwhatwemightcall%``%#"#classical program verification.#"#%''%Wewriteprograms,writetheirspecifications,andthenprovethattheprogramssatisfytheirspecifications.TheprogramsthatwehavewritteninCoqhavebeennormalfunctionalprogramsthatwecouldjustaswellhavewritteninHaskellorML.Inthischapter,westartinvestigatingusesof%\index{dependenttypes}\textit{%#<i>#dependenttypes#</i>#%}%tointegrateprogramming,specification,andprovingintoasinglephase.Thetechniqueswewilllearnmakeitpossibletoreducethecostofprogramverificationdramatically.*)
(***IntroducingSubsetTypes*)
...
...
@@ -37,7 +37,7 @@ pred = fun n : nat => match n with
]]
We can use a new command, [Extraction], to produce an OCaml version of this function. *)
We are lucky that Coq's heuristics infer the [return] clause (specifically, [return n > 0 -> nat]) for us in this case. In general, however, the inference problem is undecidable. The known undecidable problem of %\textit{%#<i>#higher-order unification#</i>#%}% reduces to the [match] type inference problem. Over time, Coq is enhanced with more and more heuristics to get around this problem, but there must always exist [match]es whose types Coq cannot infer without annotations.
We can reimplement our dependently-typed [pred] based on %\textit{%#<i>#subset types#</i>#%}%, defined in the standard library with the type family [sig]. *)
[sig] is a Curry-Howard twin of [ex], except that [sig] is in [Type], while [ex] is in [Prop]. That means that [sig] values can survive extraction, while [ex] proofs will always be erased. The actual details of extraction of [sig]s are more subtle, as we will see shortly.
@@ -159,13 +164,12 @@ Definition pred_strong2 (s : {n : nat | n > 0}) : nat :=
|exist(Sn')_=>n'
end.
(** To build a value of a subset type, we use the [exist] constructor, and the details of how to do that follow from the output of our earlier [Print sig] command. *)
(** The function [proj1_sig] extracts the base value from a subset type. It turns out that we need to include an explicit [return] clause here, since Coq's heuristics are not smart enough to propagate the result type that we wrote earlier.
We have managed to reach a type that is, in a formal sense, the most expressive possible for [pred]. Any other implementation of the same type must have the same input-output behavior. However, there is still room for improvement in making this kind of code easier to write. Here is a version that takes advantage of tactic-based theorem proving. We switch back to passing a separate proof argument instead of using a subset type for the function's input, because this leads to cleaner code. *)
@@ -237,19 +240,21 @@ Definition pred_strong4 : forall n : nat, n > 0 -> {m : nat | n = S m}.
end).
(*beginthide*)
(** We build [pred_strong4] using tactic-based proving, beginning with a [Definition] command that ends in a period before a definition is given. Such a command enters the interactive proving mode, with the type given for the new identifier as our proof goal. We do most of the work with the [refine] tactic, to which we pass a partial %``%#"#proof#"#%''% of the type we are trying to prove. There may be some pieces left to fill in, indicated by underscores. Any underscore that Coq cannot reconstruct with type inference is added as a proof subgoal. In this case, we have two subgoals:
@@ -263,7 +268,7 @@ We can see that the first subgoal comes from the second underscore passed to [Fa
(*endthide*)
Defined.
(** We end the %``%#"#proof#"#%''% with [Defined] instead of [Qed], so that the definition we constructed remains visible. This contrasts to the case of ending a proof with [Qed], where the details of the proof are hidden afterward. Let us see what our proof script constructed. *)
@@ -291,10 +296,37 @@ Eval compute in pred_strong4 two_gt0.
(**%\vspace{-.15in}%[[
=exist(funm:nat=>2=Sm)1(refl_equal2)
:{m:nat|2=Sm}
]]
We are almost done with the ideal implementation of dependent predecessor. We can use Coq's syntax extension facility to arrive at code with almost no complexity beyond a Haskell or ML program with a complete specification in a comment. *)
@@ -313,10 +345,9 @@ Eval compute in pred_strong5 two_gt0.
(**%\vspace{-.15in}%[[
=[1]
:{m:nat|2=Sm}
]]
One other alternative is worth demonstrating. Recent Coq versions include a facility called [Program] that streamlines this style of definition. Here is a complete implementation using [Program]. *)
@@ -326,28 +357,25 @@ Program Definition pred_strong6 (n : nat) (_ : n > 0) : {m : nat | n = S m} :=
|Sn'=>n'
end.
(** Printing the resulting definition of [pred_strong6] yields a term very similar to what we built with [refine]. [Program] can save time in writing programs that use subset types. Nonetheless, [refine] is often just as effective, and [refine] gives you more control over the form the final term takes, which can be useful when you want to prove additional theorems about your definition. [Program] will sometimes insert type casts that can complicate theorem-proving. *)
(** Curious readers can verify that the [decide equality] version extracts to the same OCaml code as our more manual version does. That OCaml code had one undesirable property, which is that it uses %\texttt{%#<tt>#Left#</tt>#%}% and %\texttt{%#<tt>#Right#</tt>#%}% constructors instead of the boolean values built into OCaml. We can fix this, by using Coq's facility for mapping Coq inductive types to OCaml variant types. *)
@@ -522,7 +548,7 @@ let rec in_dec a_eq_dec x = function
(***PartialSubsetTypes*)
(** Our final implementation of dependent predecessor used a very specific argument type to ensure that execution could always complete normally. Sometimes we want to allow execution to fail, and we want a more principled way of signaling that than returning a default value, as [pred] does for [0]. One approach is to define this type family [maybe], which is a version of [sig] that allows obligation-free failure. *)
@@ -532,7 +558,7 @@ Inductive maybe (A : Set) (P : A -> Prop) : Set :=
Notation"{{ x | P }}":=(maybe(funx=>P)).
Notation"??":=(Unknown_).
Notation "[[ x ]]" := (Found _ x _).
Notation"[| x |]":=(Found_x_).
(**Nowournextversionof[pred]istrivialtowrite.*)
...
...
@@ -540,56 +566,51 @@ Definition pred_strong7 : forall n : nat, {{m | n = S m}}.
refine(funn=>
matchnwith
|O=>??
| S n' => [[n']]
|Sn'=>[|n'|]
end);trivial.
Defined.
Evalcomputeinpred_strong72.
(**%\vspace{-.15in}%[[
= [[1]]
=[|1|]
:{{m|2=Sm}}
]]
]]
*)
Evalcomputeinpred_strong70.
(**%\vspace{-.15in}%[[
=??
:{{m|0=Sm}}
]]
Because we used [maybe], one valid implementation of the type we gave [pred_strong7] would return [??] in every case. We can strengthen the type to rule out such vacuous implementations, and the type family [sumor] from the standard library provides the easiest starting point. For type [A] and proposition [B], [A + {B}] desugars to [sumor A B], whose values are either values of [A] or proofs of [B]. *)
(** Now we are ready to give the final version of possibly-failing predecessor. The [sumor]-based type that we use is maximally expressive; any implementation of the type has the same input-output behavior. *)
(** We can treat [maybe] like a monad, in the same way that the Haskell [Maybe] type is interpreted as a failure monad. Our [maybe] has the wrong type to be a literal monad, but a %``%#"#bind#"#%''%-like notation will still be helpful. *)
This notation is very helpful for composing richly-typed procedures. For instance, here is a very simple implementation of a function to take the predecessors of two naturals at once. *)
(** With that notation defined, we can implement a [typeCheck] function, whose code is only more complex than what we would write in ML because it needs to include some extra type annotations. Every [[[e]]] expression adds a [hasType] proof obligation, and [crush] makes short work of them when we add [hasType]'s constructors as hints. *)
@@ -834,29 +857,29 @@ Definition typeCheck' : forall e : exp, {t : type | hasType e t} + {forall t, ~
(**Weregisterallofthetypingrulesashints.*)
HintResolvehasType_det.
(** [hasType_det] will also be useful for proving proof obligations with contradictory contexts. Since its statement includes [forall]-bound variables that do not appear in its conclusion, only [eauto] will apply this hint. *)
(** We clear [F], the local name for the recursive function, to avoid strange proofs that refer to recursive calls that we never make. The [crush] variant [crush'] helps us by performing automatic inversion on instances of the predicates specified in its second argument. Once we throw in [eauto] to apply [hasType_det] for us, we have discharged all the subgoals. *)
The results of simplifying calls to [typeCheck'] look deceptively similar to the results for [typeCheck], but now the types of the results provide more information. *)
Ournewfunctionremainseasytotest:*)
EvalsimplintypeCheck'(Nat0).
(**%\vspace{-.15in}%[[
= [[[TNat]]]
=[||TNat||]
:{t:type|hasType(Nat0)t}+
{(forallt:type,~hasType(Nat0)t)}
]]
...
...
@@ -876,7 +899,7 @@ Eval simpl in typeCheck' (Nat 0).
%\item%#<li># Define a function [decide] that determines whether a particular [prop] is true under a particular truth assignment. That is, the function should have type [forall (truth : var -> bool) (p : prop), {propDenote truth p} + {~ propDenote truth p}]. This function is probably easiest to write in the usual tactical style, instead of programming with [refine]. [bool_true_dec] may come in handy as a hint.#</li>#
%\item%#<li># Define a function [negate] that returns a simplified version of the negation of a [prop]. That is, the function should have type [forall p : prop, {p' : prop | forall truth, propDenote truth p <-> ~ propDenote truth p'}]. To simplify a variable, just negate it. Simplify a negation by returning its argument. Simplify conjunctions and disjunctions using De Morgan's laws, negating the arguments recursively and switching the kind of connective. [decide] may be useful in some of the proof obligations, even if you do not use it in the computational part of [negate]'s definition. Lemmas like [decide] allow us to compensate for the lack of a general Law of the Excluded Middle in CIC.#</li>#