HAL Id: hal-00644156
https://hal.inria.fr/hal-00644156
Submitted on 23 Nov 2011
HAL is a multi-disciplinary open access
archive for the deposit and dissemination of
sci-entific research documents, whether they are
pub-lished or not. The documents may come from
teaching and research institutions in France or
abroad, or from public or private research centers.
L’archive ouverte pluridisciplinaire HAL, est
destinée au dépôt et à la diffusion de documents
scientifiques de niveau recherche, publiés ou non,
émanant des établissements d’enseignement et de
recherche français ou étrangers, des laboratoires
publics ou privés.
Na Xu
To cite this version:
Na Xu. Hybrid Contract Checking via Symbolic Simplification. [Research Report] RR-7794, INRIA.
2011. �hal-00644156�
a p p o r t
d e r e c h e r c h e
N
0
2
4
9
-6
3
9
9
IS
R
N
IN
R
IA
/R
R
--7
7
9
4
--F
R
+
E
N
G
Programs, Verification and Proofs
Hybrid Contract Checking via Symbolic
Simplification
Dana N. Xu
N° 7794
Centre de recherche INRIA Paris – Rocquencourt
Dana N. Xu
Theme: Programs,Veri ationandProofs Algorithmi s,Programming,SoftwareandAr hite ture
Équipes-ProjetsGallium
Rapport dere her he n°7794Novembre201169pages
Abstra t: Program errorsare hardto dete tandto proveabsent. Contra t he kingallowsusto(a)stati allyverifythatafun tionsatisesits ontra t;(b) pre isely blame fun tions at fault bothstati allyand dynami ally when there is a ontra tviolation. Stati ontra t he king at hes allbugs but anonly he krestri ted properties while dynami he king an he k moreexpressive properties,butisnot omplete. Inthispaper,weintegratestati and dynami ontra t he kingforasubsetofOCaml. Weexploitastati he kerasmu has possibleandleavetheresidual ontra t satisfa tion he ksto run-time. Thus, no(potential) bugs anes apeandyetexpressiveproperties anbeexpressed.
Key-words: ontra tsemanti s,stati , dynami , hybrid, ontra t he king, fun tionallanguage,veri ation,debugging
Résumé : Ilest di ile dedéte terdeserreursdans desprogrammes,oude démontrerleurabsen e. Permettreauxprogrammeursd'é riredesspé i ations formellesetpré ises, enparti uliersouslaformede ontrats,est uneappro he ommunepourvérierdesprogrammesettrouverdeserreurs. Nousformalisons etproposonsuneimplémentationd'unvéri ateurhybridede ontratspourun sous-ensembled'OCaml. Late hniqueprin ipalequenousmettonsen÷uvreest lasimpli ationsymbolique,quipermetde ombinerfa ilementlesvéri ations statiquesetdynamiquesde ontrats. Late hniquequenousproposons onsiste àvérierqu'unefon tionsatisfaitson ontratou indiquequelle estlafon tion àl'originede saviolation. Quand lasatisfa tiond'un ontratn'estpas dé id-ablestatiquement,du odedetestestajoutéauprogrammeand'ee tuerles véri ationsàl'exé ution.
Mots- lés : lasémantiquedu ontrat,statique,dynamique,hybride,langage fon tionnel,véri ation,débogage
Contents
1 Introdu tion 4
2 Overview 5
3 The language 9
3.1 Syntax . . . 9
3.2 Type he kingrulesforexpression . . . 10
3.3 Operationalsemanti s . . . 11
3.4 Crashing. . . 12
3.5 Behaves-the-same. . . 14
3.6 Crashes-more-often . . . 14
4 Contra ts 16 4.1 Type he kingfor ontra ts . . . 16
4.2 Asemanti sfor ontra tsatisfa tion . . . 17
4.3 Thewrappers . . . 18
4.4 Openexpressionsand ontra ts . . . 19
4.5 Terminating ontra ts . . . 19
4.6 Contra tAny . . . 20
4.7 Contra tordering. . . 21
4.7.1 Predi ateContra tOrdering . . . 22
4.7.2 DependentFun tionContra tOrdering . . . 23
4.7.3 Dependenttuple ontra tordering . . . 23
4.8 Contra tequivalen e . . . 24
5 Stati ontra t he king and residualization 26 5.1 TheSLma hine . . . 29
5.2 Logi ization . . . 32
5.3 Dis ussionandpreliminaryexperiments . . . 38
6 Hybrid ontra t he king 40 7 Relatedwork 41 8 Con lusion 42 A Prooffor the maintheorem 46 A.1 Teles opingProperty . . . 50
A.2 KeyLemma . . . 53
A.3 ExaminationofCy li Dependen ies . . . 54
A.4 Congruen eofCrashes-More-Often . . . 55
A.5 Proje tionPairandClosurePair . . . 55
A.6 Contra tsareProje tions . . . 56
A.7 BehaviourofProje tions. . . 58
B Corre tness ofSL ma hine 60 B.1 Corre tnessofLogi ization . . . 60
1 Introdu tion
Constru ting reliablesoftware isdi ultevenwith fun tionallanguages. F or-mulating and he king(stati ally ordynami ally)logi alassertions [18,15, 2, 5, 35℄, espe ially in the form of ontra ts [28, 13, 7, 14, 39℄, is one popular approa h to error dis overy. Stati ontra t he king an at h all ontra t violations but may give false alarm and anonly he k restri ted properties; dynami he king an he kmoreexpressivepropertiesbut onsumesrun-time y lesand only he ksthea tualexe utedpaths, thus is not omplete. Stati and dynami he king an be omplementary. In this paper,weformalize hy-brid(i.e. stati followedbydynami ) ontra t he kingforasubsetofOCaml. Thus,no(potential) ontra tviolations anes apeandyetexpressiveproperties anbeexpressed.
ConsideranOCamlprogramaugmentedwitha ontra tde laration:
(* val f1 : int -> int -> int *)
ontra t f1 = ({x | x >= 0} -> {y | y >= 0}) -> {z | z >= 0}
let f1 g = (g 1) - 1
let f2 = f1 (fun x -> x - 1)
The ontra toff1saysthat iff1takesafun tion thatreturnsanon-negative number when given a non-negative number, the fun tion f1 itself returns a non-negative number. Both a stati he ker and a dynami he ker are able to report that f1 fails its post ondition: the stati he ker relies on the in-validity of
∀g :
int→
int, (g 1) ≥ 0 ⇒ (g 1) − 1 ≥ 0
while the dynami he kerevaluates(((fun x -> x - 1) 1) - 1)to-1,whi hviolatesthe on-tra t{z | z >= 0}. However,adynami he ker annottellthattheargument (fun x -> x - 1) fails f1'spre ondition be ause there is no witnessat run-time,whileastati he ker anreportthis ontra tviolationbe ausex − 1 ≥ 0
does not hold for allx
of int to satisfy the post ondition{y | y ≥ 0}
. On theotherhand,astati he kerusuallygivesthreeout omes: (a)denitelyno bug; (b) denitely abug; ( ) possiblya bug. Here,abug refersto a ontra t violation. Ifwegetmanyalarms( ),itmaytakeusalotoftimeto he kwhi h one is areal bug and whi h one is a false alarm. We may want to invokea dynami he kerwhentheout omeis( ).Followingtheformalization in[39℄, but this timeforastri t language. We rst givea denotational semanti s to ontra tsatisfa tion. That is to dene whatitmeansbyanexpression
e
satisesits ontra tt
(writtene ∈ t
)without knowingitsimplementation. Next,wedeneawrapper⊲
thattakesan expres-sione
and its ontra tt
and produ esa terme ⊲ t
su h that ontra t he ks areinsertedatappropriatepla esine
. Ifa ontra t he kisviolated,aspe ial onstru tor BADl
signalstheviolation. As theterm
e ⊲ t
isatermin thesame languagease
, allwehaveto do is to he k therea habilityof BADl
. If aBAD is rea hable,weknow a ontra tis violatedand the label
l
pre isely aptures thefun tion atfault. Wesymboli allysimplifytheterme ⊲ t
aimingtosimplify BADsaway. In asethere is anyBADleft, weeither reportit asa ompile-time error orleavethe residual odefor dynami he king. We makethe following ontributions: We larifytherelationshipbetweenstati ontra t he kinganddynami ontra t he king (2). A newobservationis that, after stati he king,
weshouldpruneawaysomemoreunrea hable odebeforegoondynami he king. Su h unrea hable odehoweverisessentialduringstati he k-ing. We provethe orre tness of this pruning (6) with the teles oping propertystudied(butnotusedforsu h purpose)in [7, 39℄.
Wedene
e ∈ t
ande⊲t
andproveatheoreme⊲t
is rash-free⇐⇒ e ∈ t
(4). The rash-free means BAD is not rea hable under all ontexts. Su h aformalizationistri kyandits orre tnessproofisnon-trivial. We re-dothekindofproofsin [40℄forastri tlanguage. WedesignanovelSLma hinethataugmentssymboli simpli ationwith ontextualinformationsynthesisfor he kingtherea habilityofBAD stat-i ally(5). Thedi ultyliesinthereasoningaboutnon-totalterms. The he kingisautomati andmodularandweproveissoundness. Moreover, theSLma hineprodu esresidual odefordynami he king. We ompare ourframeworkwithotherapproa hesin7.
Wedesignalogi izationte hniquethat transformsexpressionsto logi al formulae,inspiredby[20,19℄and axiomatizationoffun tions that inter-a tivetheoremproversperformbefore allingSMTsovlers. However,we haveto dealwithnon-totaltermsandthat isthekey ontributionofthe logi ization(5).
2 Overview
Assertions[18℄statelogi alpropertiesofanexe utionstateatarbitrarypointsin aprogram; ontra tsspe ifyagreements on erningthevaluesthatowa rossa boundarybetweendistin tpartsofaprogram(modules,pro edures,fun tions, lasses). Ifanagreementisviolated, ontra t he kingissupposedto pre isely blame the fun tion at fault. Contra ts were rst introdu ed to be he kedat run-time [28, 13℄. To perform dynami ontra t he king (DCC), a fun tion mustbe alledtobe he ked. Forexample:
ontra t in = {x | x > 0} -> {y | y > 0} let in = fun v -> v + 1
let t1 = in 0
Adynami he kerwrapsthein in t1with its ontra t
t
in : let t1 =(
in BADl
⊲⊳
BADl′
t
in)
0where
l
is(2, 5, “
in”)
indi ating the sour e lo ation where in is dened (row:2, ol:5) andl
′
is
(3, 10, “
t1”)
indi ating thelo ation of the allsite with aller'sname. Thiswrappedt1expandsto:(λx
1
.
lety =
in(
letx = x
1
inif
x > 0
thenx
elseBAD(3,10,“
t1”)
)
in if
y > 0
theny
elseBAD(2,5,“
in”)
) 0
Intheupperbox,theargumentofin isguardedbythe he k
x > 0
;inthelower box, theresultof in is guardedby the he ky > 0
. Ifa he ksu eeds, theoriginaltermisreturned;otherwise,thespe ial onstru torBADisrea hedanda blameisraised. Inthis ase,t1 allsin with0,whi hfailsin 'spre ondition. Runningtheabovewrapped ode,wegetBAD
(3,10,“
t1”)
,whi hpre iselyblames t1.
The DCC algorithm is like this. Given a fun tion
f
and a ontra tt
, to he k that the alleef
and its aller agree on the ontra tt
dynami ally, a he kerwrapsea h all tof
withits ontra t:f
BADf
⊲⊳
BAD
?
t
whi hbehavesthesameas
f
ex eptthat(a)iff
disobeyst
,itblamesf
,signaled by BADf
; (b) if the ontext uses
f
in a way notpermitted byt
, itblames the alleroff
,signaledbyBAD?
where
?
is lled witha allernameandthe all sitelo ation.Later,[7,39℄giveformalde larativesemanti sfor ontra tsatisfa tionthat not only allow us to prove the orre tnessof DCC w.r.t. this semanti s, but alsoto he k ontra tsstati ally.
Theessen eofstati ontra t he king(SCC) is:
splitting BAD
f
⊲⊳
BAD?
intohalf:e ⊲ t = e
BADf
⊲⊳
UNR?
t
ande ⊳ t = e
UNRf
⊲⊳
BAD?
t.
The
⊲
(ensures) and the⊳
(requires) are dual to ea h other. The spe ial onstru torUNR(pronoun edunrea hable),doesnotraise ablame, butstops an exe ution. (One, who is familiar with assert and assume, an think of (ifp
thene
else BAD) as (assertp; e
) and (ifp
thene
else UNR) as (assumep; e
).)SCCis modular and performed at denition site of ea h fun tion. For ex-ample,
(λv.v + 1) ⊲ t
in
expandsto:
λx
1
.
lety = (λv.v + 1)
(
letx = x
1
inifx > 0
thenx
elseUNR?
)
in
if
y > 0
theny
elseBAD(2,5,“
in”)
Atthedenition siteofafun tion,
f = e
,weassumef
'spre onditionholds and assertitspost ondition. IfallBADsine ⊲ t
arenotrea hable,weknowf
satisesits ontra tt
. Onewayto he krea habilityof BADis tosymboli ally simplify thefragment. Intheabove ase,inliningx
,weget:λx
1
.
lety = (λv.v + 1) (
ifx
1
> 0
thenx
1
elseUNR?
)
in
if
y > 0
theny
elseBAD(2,5,“
in”)
Unlike [37℄ in a lazy setting, we annot apply beta-redu tion in a stri t lan-guageif an argument isnot avalue asit maynot preservethe semanti s. In thispaper,besidessymboli simpli ation,we olle t ontextualinformationin logi alformulaformand onsultanSMTsolverto he ktherea habilityofBAD. An SMTsolverusually dealswithformulaeinrstorder logi (FOL),5gives the details of the generation of formulae in FOL. As an overview, we present formulaein higherorder logi (HOL).Forthetwosubexpressions of theRHS of
y
,wehave:λv.v + 1
∃x
2
, (∀v, x
2
(v) = v + 1)
if
x
1
> 0
thenx
1
elseUNR?
∃x
3
, (x
1
> 0 ⇒ x
3
= x
1
)∨
(not(x
1
> 0) ⇒ false)
One anthinkoftheexistentiallyquantied
x
2
(andx
3
)denotingtheexpression itself. FortheRHSofy
,wehavelogi alformula:∀y, ∃x
2
, (∀v, x
2
(v) = v + 1) ∧ (∃x
3
, (x
1
> 0 ⇒ x
3
= x
1
)
∧(not(x
1
> 0) ⇒ false) ∧ y = x
2
(x
3
))
[Q1℄We he k the validity of
∀x
1
,
Q1⇒ y > 0
by onsulting an SMT solver. As∀x
1
,
Q1⇒ y > 0
isvalid,weknowtheBAD(2,5,“
in”)
isnotrea hable,thusin satisesits ontra t.
Considerthefun tionf1andits ontra t
t
f1in1. Sof1
⊲ t
f1is
(λg.(g 1) −
1) ⊲ ({x | x ≥ 0} → {y | y ≥ 0}) → {z | z ≥ 0}
,whi hexpandsto:λx
1
.
letz = (λg.(g 1) − 1)
(λx
2
.
lety = x
1
(
letx = x
2
in ifx ≥ 0
thenx
elseBAD(4,5,“f
1
”)
)
in ify ≥ 0
theny
elseUNR?
)
in
if
z ≥ 0
thenz
elseBAD(4,5,“f
1
”)
Afterapplyingsome onventionalsimpli ationrules,wehave:
R1
: λx
1
.
letz =
lety = x
1
1
inif
y ≥ 0
theny − 1
elseUNR?
if
z ≥ 0
thenz
elseBAD(4,5,“f
1
”)
WeseethattheinnerBAD
(4,5,“f
1
”)
hasbeensimpliedaway,be ause
x = x
2
= 1
and(if1 ≥ 0
then1
elseBAD(4,5,“f
1
”)
)issimplied to1. Aswe annotprove
∀x
1
, ∀z, (∃y, y = x
1
1 ∧ (y ≥ 0 ⇒ z = y − 1)) ⇒ z ≥ 0
to be valid, the other BAD(4,5,“f
1
”)
remains. We aneither report this potential ontra tviolationat ompile-timeorleavethisresidual odeR1forDCCtoa hievehybrid he king. Hybrid ontra t he king (HCC) performs SCC rst and runs the residual odeasin DCC.InSCC,f1
⊲ t
f1
he kswhether f1satisesitspost ondition byassumingitspre onditionholds. Atea h allsiteoff1,wewrapthefun tion with
⊳
. Forexample:ontra t f3 = {v | v >= 0} let f3 = f1 zut
where zut is adi ult fun tion for anSMT solverand zut's ontra tis
{x |
true}
. Sayzut⊳ {x |
true} =
zut, wethenhavethetermf3⊲ t
f3 tobe:
((
f1⊳ t
f1)
zut
) ⊲ {v | v > 0}
whi hrequiresf3tosatisfyf1'spre onditionandassumesf1satisesits post- onditionbe ausef1
⊲ t
f1
hasbeen he ked. DuringSCC,atop-levelfun tion isneverinlined. Wedonothavetoknowitsdetailedimplementationatits all
siteas ithasbeenguardedbyits ontra twith
f ⊳ t
. Thef3⊲ t
f3expandsto:
let
v =
letz =
f1(λx
2
.
lety =
zut(
letx = x
2
in ifx ≥ 0
thenx
elseUNR(7,10,“f
1
”)
)
in if
y ≥ 0
theny
elseBAD(7,10,“f
3
”)
)
in
if
z ≥ 0
thenz
elseUNR(7,10,“f
1
”)
if
v ≥ 0
thenv
elseBAD(7,10,“f
3
”)
As
⊳
is dual to⊲
, the RHS ofv
is a tually a opy of the earlierf1⊲ t
f1but swapping the BAD and UNR and substituting
x
1
with zut. We now know the sour e lo ation of the all site of f1 and its aller's name, the UNR?
be omes BAD
(7,10,“f
3
”)
andtheBAD
(4,5,“f
1
”)
be omesUNR
(7,10,“f
1
”)
. Atdenitionsitewhere the allerisunknown,weusethelo ationoff1,i.e.
(4, 5, “f
1
”)
. On eits aller is known, we use(7, 10, “f
1
”)
. It is easy to get sour e lo ation, whi h is for thesakeoferrormessagereporting. Sowedonotelaboratethesour elo ation further.AsanSMTsolversaysvalid for
∀v.(∃z.z ≥ 0 ∧ v = z) ⇒ v ≥ 0
,thef3⊲ t
f3 anbesimpliedto (sayR2):let
z =
f1(λx
2
.
lety =
zut(
letx = x
2
in ifx > 0
thenx
elseUNR(7,10,“f
1
”)
)
in ify ≥ 0
theny
elseBAD(7,10,“f
3
”)
)
in
if
z ≥ 0
thenz
elseUNR(7,10,“f
1
”)
One BAD remains. We an either report this potential ontra t violation at ompile-time or ontinue aDCC. ForSCC, wehave he ked f1
⊲ t
f1
, but for DCC, toinvokef1
⊲ t
f1
, wemust usetheresidual odeR1. However,theUNR lausesare usefulforSCC,but redundantforDCC. We anremoveUNRswith asimpli ationrule:
(
ife
0
thene
1
elseUNR) =⇒ e
1
[rmUNR]
(Weshallexplainwhyitisvalidtoapplythisruleevenif
e
0
maydivergeor rash in6. Intuitively,UNRisindeedunrea hableande
0
hasbeen he kedbeforethis program point.) Applying therule [rmUNR℄to R1 andR2and simplify abit, weget:f1
♯ = λx
1
.
letz = (
lety = (x
1
1)
iny − 1)
in ifz ≥ 0
thenz
elseBAD(4,5,“f
1
”)
f2
♯ =
f1♯ (λx
2
.
lety =
zutx
2
in ify ≥ 0
theny
elseBAD(7,10,“f
3
”)
)
respe tively, whi h is the residual ode beingrun. We show in 6 that HCC blamesafun tion
f
i
iDCCblamesf
i
.Summary Given a denition
f = e
and a ontra tt
, to he ke
satisest
(writtene ∈ t
), weperformthese steps. (1) Constru te ⊲ t
. (2) Simplifye ⊲ t
asmu haspossibletoe
′
BAD is in
e
′
, then there isno ontra t violation; ifthere is aBADin
e
′
but no fun tion all in
e
′
, then itis denitely a bugand report it at ompile-time; if thereisaBADandfun tion all(s)in
e
′
,thenitisapotentialbug. (4)Forea h fun tion
f
, reateitsresidual odef ♯
bysimplifyinge
′
withtherule[rmUNR℄, andruntheprogramwithea h
f
beingrepla edbyf ♯
.3 The language
Thelanguagepresentedin thispaper,namedM,ispureandstri t,asubsetof OCaml,in ludingparametri polymorphism.
3.1 Syntax
x, f ∈ Variables
T ∈ Type constructors
K ∈ Data constructors
pgm
::=
def
1
, . . . , def
n
Program
τ
::=
−
→
τ T | τ
1
→ τ
2
Types
t
∈
Contracts
t
::=
{x | p}
predi ate ontra t|
x : t
1
→ t
2
dependentfun tion ontra t|
(x : t
1
, t
2
)
dependenttuple ontra t|
Any polymorphi Any ontra tdef
∈
Definitions
def
::=
type−
→
′
α T =
−−−−−→
K
of−
→
τ
|
ontra tf = t
|
letf −
→
x = e
top-levelfun tion|
let ref −
→
x = e
top-levelre ursivefun tion
a, e, p
∈
Exp
Expressions
a, e, p ::= n
integers|
r
blame|
x | λ(x
τ
).e | e
1
e
2
|
mat he
0
with−
→
alt
pattern-mat hing|
K −
→
e
onstru torr
::=
BADl
|
UNRl
Blames
l
::=
(n
1
, n
2
,
String)
Label
alt
::=
K (x
τ
1
1
, . . . , x
τ
n
n
) → e
Alternatives
val
::=
n | x | r | K −
→
v | λ(x
τ
).e
Values
Figure1givesthesyntaxof languageM.A program ontainsasetof data type de larations, ontra tde larations and fun tion denitions. Expressions in lude variables, lambda abstra tions, appli ations, onstru tors and mat h-expressions. Basetypessu hasintandboolaredatatypeswithnoparameter. Pairsareaspe ial aseof onstru tedterms,i.e.
(e
1
, e
2
)
is Pair(e
1
, e
2
)
with type ('a,'b) produ t = Pair of 'a * 'b. Wehavetop-levellet re ,but for the ease of presentation, we omit lo al let re . (It is possible to allow lo al let re by either assuming that a lo al re ursive fun tion is given a ontra t or using ontra t inferen e [21℄ to infer its ontra t. Even if [21℄ is not modular, it is good enough to infer a ontra t for a lo al fun tion.) A lo al let-expression letx = e
1
ine
2
is asynta ti sugar for(λx.e
2
) e
1
. An if-expressionife
0
thene
1
elsee
2
issynta ti sugarformat he
0
with{
true→ e
1
;
false→ e
2
}
.Weassumealltop-levelfun tionsaregivena ontra t. Contra t he kingis doneafter thetype he kingphaseina ompilersoweassumeallexpressions, ontexts and ontra tsare well-typed and useits typeinformation (presented assupers ript, e.g.
e
τ
or
t
τ
)wheneverne essary. Thetwo ontra tex eptions(also alledblames)BAD
l
andUNR
l
areadapted from [39℄. Theyare forinternal usage, notvisible to programmers. The label
l
ontainsinformation su h as fun tion name andsour e ode lo ation, whi h is useful for error reporting as well as for examination of the orre tness of blaming. Butwemayomitthelabell
whenitisnotthefo usofthedis ussion.Itispossibleforprogrammerstowrite:
let head xs = mat h xs with
| [℄ -> raise Emptylist | x::l -> x
where raise
: ∀α.
Ex eption→ α
. The Ex eptionisabuilt-indata typefor ex eptionsandEmptylisthastypeEx eption. Aswedonothavetry-within languageM(leavingitasfuturework),aprepro essing onvertsraise EmptylisttoBAD head
.
Wehavefourformsof ontra ts.The
p
inapredi ate ontra t{x | p}
refers toabooleanexpressioninthesamelanguageM.Dependentfun tion ontra ts allowus to des ribe dependen y betweeninput andoutput of afun tion. For example,x : {y | y > 0} → {z | z > x}
saysthat,theinputisgreaterthan0and theoutputisgreaterthantheinput. We anuseashorthand{x | x > 0} → {z |
z > x}
byassumingx
s opesovertheRHS of→
. The→
is rightasso iative. Similarly, dependenttuple ontra tsallow us to des ribedependen ybetween two omponents ofa tuple. Forexample,(x : {y | y > 0}, {z | z > x})
whose short hand is({x | x > 0}, {z | z > x})
. Contra tAnyis auniversal ontra t that anyexpressionsatises. Wesupporthigher order ontra ts, e.g.k : ({x |
x > 0} → {y | y > x}) → {z | k 5 > −1}
forafun tionlet f g = g 2.3.2 Type he king rules for expression
ThelanguageMisstati allytypedinthe onventionalway. Figure2givestype he kingrules. Atypejudgementhastheform
whi hstatesthat given
Γ
(whi his amappingfrom variabletoitstype),e
has typeτ
assumingthat anyfreevariable in ithastypegivenbyΓ
. IfΓ = ∅
, we omittheΓ
,andwrite⊢ e
τ
.
Γ ⊢
BAD:: τ
[
T-BAD]
Γ ⊢
UNR:: τ
[
T-UNR]
v :: τ ∈ Γ
Γ ⊢ v :: τ
[
T-Var]
Γ, x :: τ
1
⊢ e :: τ
2
Γ ⊢ (λ(x
τ
1
).e) :: τ
1
→ τ
2
[
T-Lam]
Γ ⊢ e
1
:: τ
1
→ τ
2
Γ ⊢ e
2
:: τ
1
Γ ⊢ (e
1
e
2
) :: τ
2
[
T-App]
K :: −
→
τ → T ∈ Γ
Γ ⊢ −
→
e :: −
→
τ
Γ ⊢ K −
→
e :: T −
→
α
[
T-Con]
Γ ⊢ e
0
:: T −
→
τ
Γ, {v :: T −
→
τ }, {
−−−−−−−−−→
K
i
−
→
x
i
:: T −
→
τ } ⊢ e
i
:: τ
Γ ⊢ (
asee
0
of(v
T −
→
τ
) {K
i
−
→
x
i
→ e
i
}) :: τ
[
T-Mat h]
Figure 2: TypeChe kingRules
Aswedotype he kingbefore ontra t he king,weassumeallexpressions arewell-typed(i.e. notypeerror)in therestof thispaper. Notethat nothing substantial in the paper depends deli ately on the type system. The reason we ask that programs are well-typed is to avoid the te hni al in onvenien e in designing the semanti s of ontra ts if, say, evaluation nds an ill-typed expression(3 True).
3.3 Operational semanti s
Thesemanti sofourlanguageisgivenbyredu tionrulesinFigure3. Fora top-levelfun tion, wefet h itsdenition from theevaluation envrionment
∆
. We adaptsomebasi denitionsfrom[39℄. Denition1denestheusual ontextual equivalen e. Twoexpressionsaresaidtobesemanti allyequivalent,ifunderall ( losing) ontexts,ifoneevaluatesto ablamer
,theotheralsoevaluatestothe samer
.Denition1(Semanti allyEquivalent). Twoexpressions
e
1
ande
2
are seman-ti ally equivalent, namelye
1
≡
s
e
2
, i for all losingC
, for allr
,C[[e
1
]] →
∗
r
⇐⇒
C[[e
2
]] →
∗
r
Our framework only guarantees partial orre tness. A diverging program doesnot rash.
Denition2 (Diverges). A losed expression
e
diverges, writtene ↑
,ieithere →
∗
UNR,orthereisno value
val
su hthate →
∗
val
let
(
re) f = e ∈ ∆
f → e
[E-top℄(λx.e) val → e[val/x]
[E-beta℄mat h
K
−→
val
with−−−−−−→
K −
→
x → e → e[
−−−→
val/x]
[E-mat h℄e
1
→ e
2
C[[e
1
]] → C[[e
2
]]
[E- tx℄C[[r]] → r
[E-exn℄ ContextsC
::=
[[•]] | C e | val C | K
−→
val C −
→
e
|
mat hC
with−
→
alt
Figure 3: Semanti softhelanguageM
3.4 Crashing
WeuseBADtosignalthatsomethinghasgonewrongintheprogram,whi h an beaprogramfailureora ontra tviolation.
Denition3 (Crash). A losedterm
e
rashesie →
∗
BAD.
At ompile-time, onede idableway to he k thesafety of aprogram isto seewhether theprogramissynta ti allysafe.
Denition4(Synta ti safety). A(possibly-open)expression
e
is synta ti ally safeiBAD∈
/
s
e
. Similarly,a ontextC
issynta ti allysafe iBAD∈
/
s
C
.Thenotation BAD
∈
/
s
e
meansBADdoesnotsynta ti ally appearanywhere ine
, similarly for BAD∈
/
s
C
. For example,λx.x
is synta ti ally safe whileλx. (
BAD, x)
isnot.Denition5 (Crash-freeexpression). A(possibly-open) expression
e
is rash-free i: for allC
su hthat BAD∈
/
s
C
and⊢ C[[e]] ::
bool, C[[e]] 6→
∗
BAD
.
The notation
⊢ C[[e]] ::
bool meansC[[e]]
is losed and well-typed. The quantied ontextC
servestheusualroleofaprobethattriestoprovokee
into rashing. Note thata rash-freeexpression maynot be synta ti ally safe,e.g.λx.
ifx ∗ x ≥ 0
thenx + 1
elseBAD.Lemma1(Synta ti allysafeexpressionis rash-free).
e
issynta ti ally safe⇒
e
is rash-freeProof. Sin e there is no BAD synta ti ally in
e
, for all ontextC
, su h that thereisnoBADsyntati allyinC
,thenC[[e]] 6→
∗
BAD.Bydenition5(Crash-free expression),
e
is rash-free.Foreaseofpresentation,whenwedonotgivelabel
l
toBADorUNR,wemean BADorUNRforanyl
. Moreover,expressionsBADl
andUNR
l
are losedexpressions evenif
l
isnotexpli itlybound.Proof. Sin e
e
is rash-free,allBADsine
arenotrea hablesoby onvertingall BADsine
toUNRby⌊.⌋
doesnot hangethesemanti sofe
. Formally,weprove thisbyindu tiononredu tionrules.Lemma3(Crash-freePreservation). Given
e
1
→ e
2
,e
1
is rash-free⇐⇒ e
2
is rash-free Proof. Weprovetwodire tions by ontradi tion.(
⇒
)Suppose
e
2
is not rash-free. ByDenition 5 p12(Crash-free Expression),there exists a
C
su hthat BAD∈
/
s
C
andC[[e
2
]] →
∗
BAD. By[E- tx℄and
e
1
→ e
2
andC[[e
2
]] →
∗
BAD, we have:C[[e
1
]] →
∗
C[[e
2
]] →
∗
BAD. Asweknowe
1
is rash-free, werea h ontradi tion. Thus,wearedone.(
⇐
)Suppose
e
1
is not rash-free. ByDenition 5 p12(Crash-free Expression),there exists a
C
su hthat BAD∈
/
s
C
andC[[e
1
]] →
∗
BAD. By[E- tx℄and
e
1
→ e
2
and onuen e of thelanguage,wehaveC[[e
2
]] →
∗
BAD. With theassumptionthat
e
2
is rash-free,werea h ontradi tion. Thus,wearedone.Lemma4(Crash-freefun tion). For all(possibly-open) terms
λx.e
,λx.e
is rash-free⇐⇒
for all(possibly-open) rash-free
e
′
,
e[e
′
/x]
is rash-free.
Proof. Weprovetwodire tions separately. (
⇒
)λx.e
is rash-free⇒ (
ByLemma 2 p12 ,e
′
is rash-free⇒ ⌊e
′
⌋ ≡
s
e
′
andbythedenitionof rash-freeexpression
)
forall rash-freee
′
, e[e
′
/x]
is rash-free
(
⇐
)Wehavethefollowingproof. forallcf
e
′
, e[e
′
/x]
is rash-free⇐⇒
(
ByLemma 3 p13)
forallcf
e
′
, (λx.e) e
′
is rash-free⇐⇒
(
ByDenition 5 p12 (Crash-freeExpression))
forallcf
e
′
, ∀C,
BAD∈
/
s
C, C[[(λx.e) e
′
]] 6→
∗
BAD⇒
(
ByLemma 2 p12 ,e
′
is rash-free⇒ ⌊e
′
⌋ ≡
s
e
′
)
∀C,
BAD∈
/
s
C, C[[(λx.e) ⌊e
′
⌋]] 6→
∗
BAD⇒
(
ByBAD∈
/
s
⌊e
′
⌋)
∀C,
BAD∈
/
s
C, C[[(λx.e)]] 6→
∗
BAD⇐⇒
(
ByDenition 5 p12 (Crash-freeExpression))
λx.e
is rash-free3.5 Behaves-the-same
We dene an ordering, named Behaves-the-same, whi h is useful in later se -tions.
Denition6(Behavesthesame). Expression
e
1
behaves thesamease
2
w.r.t. a set of ex eptionsR
, writtene
1
≪
R
e
2
, ifor all ontextsC
, su h that∀i ∈
{1, 2}. ⊢ C[[e
i
]] ::
boolC[[e
2
]] →
∗
r ∈ R
⇒
C[[e
1
]] →
∗
r
Denition 6 p14
saysthat
e
1
either behavesthesamease
2
orthrowsan ex- eption fromR
. (The denition doesnotlook asstrong asthat, but asevery theorist knows, it is. Forexample, oulde
1
produ e true whilee
2
produ es false? No,be ausewe ouldnda ontextC
thatwouldmakeC[[e
2
]]
throwan ex eption whileC[[e
1
]]
does not.) In ourframework, thereare only two ex ep-tionalvaluesinR
: BADandUNR.Certainly,ife
2
itselfthrowsanex eption,thene
1
mustthrowthesameex eption.As we only have twoex eptional values BAD, UNR(whi h are dual to ea h
other)in
R
,thisyieldsLemma5 p14. Weomit
{}
ifthereisonlyoneelementinR
.Lemma5(PropertiesofBehaves-the-same). Forall losed
e
1
ande
2
,e
1
≪
UNRe
2
⇐⇒ e
2
≪
BADe
1
Proof. Weprovetwodire tions separately.(
⇒
)Wehavethefollowingproof:e
1
≪
UNRe
2
⇐⇒
(
Bydefnof≪
UNR)
∀C. C[[e
2
]] →
∗
UNR⇒ C[[e
1
]] →
∗
UNR
⇐⇒
(
Bylogi)
∀C. C[[e
1
]] 6→
∗
UNR⇒ C[[e
2
]] 6→
∗
UNR
Wewantto showthat
∀D. D[[e
1
]] →
∗
BAD⇒ D[[e
2
]] →
∗
BAD. AssumeD[[e
1
]] →
∗
BAD.Let
C =
mat h(D[[•]])
with{
DEFAULT→
UNR}
NowwehaveC[[e
1
]] →
∗
BAD
⇒ C[[e
2
]] 6→
∗
UNR.
Sin e
C[[e
2
]] =
aseD[[e
2
]]
with{
DEFAULT→
UNR}
,wehaveD[[e
2
]] →
∗
BAD. Sowehave
∀D. D[[e
1
]] →
∗
BAD⇒ D[[e
2
]] →
∗
BAD
(
⇐
) Byrepla ing BAD by UNR and UNR by BADin the above proof for the dire tion(⇒
),wegettheproofforthedire tion(⇐
).3.6 Crashes-more-often
Westudy aspe ializedordering rashes-more-often, whi h playsa ru ial role in provingourmain theorems.
Denition7 (Crashes-more-often). An expression
e
1
rashes moreoften thane
2
,writtene
1
e
2
,ie
1
≪
BADe
2
Informally,
e
1
rashesmoreoftenthane
2
iftheybehaveinexa tlythesame wayex eptthate
1
may rashwhene
2
doesnot. ByDenition7p14
,Lemma5 p14
alsosaysthat:
e
1
≪
UNRe
2
⇐⇒ e
2
e
1
Theorem1(Crashes-more-oftenisAntiSymmetri ). Forallexpressions
e
1
ande
2
,e
1
e
2
ande
2
e
1
ie
1
≡
s
e
2
.Proof. Itfollowsimmediatelyfromthedenitionof
≡
s
(Denition1 p11)andthe denition of
.The rashes-more-oftenoperatorhasmanyproperties. Lemma6 p15
saysthat BAD rashes-more-often then all expressions; all expressions rash more often thenadivergingexpression. Lemma 7
p15
givesmoreintuitiveproperties.
Lemma6(PropertiesofCrashes-more-often-I).
(a)
BADe
2
(b)
e
1
e
2
ife
2
↑
Proof. Weproveea hpropertyseparately(allby ontradi tion)andweassume typesoundness.
(a) Assumethere exists a ontext
C
su hthatC[[e
2
]] →
∗
BADand
C[[
BAD]] 6→
∗
BAD. Therearetwopossibilitiesfor
C[[e
2
]] →
∗
BAD: (1)theBADisfromthe ontext
C
; (2) the BAD is from the holee
2
. For ase (1), we must haveC[[
BAD]] →
∗
BADsin eweusethesame ontext
C
. For ase(2),ifthehole isevaluated, werea hBADimmediately. Sowerea ha ontradi tionand wearedone.(b) Given
e
2
↑
, assumethere exists a ontextC
su hthatC[[e
2
]] →
∗
BADand
C[[e
1
]] 6→
∗
BAD. Sin ee
2
↑
andC[[e
2
]] →
∗
BAD, we know the BAD is from the ontext
C
. Sonomatterwhate
1
is,wehaveC[[e
1
]] →
∗
BAD. Thus, we againrea ha ontradi tionandwearedone.
Lemma7(PropertiesofCrashes-more-often-II). If
e
1
e
2
(a)
e
1
→
∗
K f
1
⇒ e
2
→
∗
K f
2
ore
2
↑
(b)
e
1
↑ ⇒ e
2
↑
(c) e
1
is rash-free⇒ e
2
is rash-free(d)
e
1
→
∗
λx.e
′
1
⇒ e
2
→
∗
λx.e
′
2
ore
2
↑
Proof. Weproveea hpropertyseparately(allby ontradi tion):(a) Given
e
1
→
∗
K f
1
, assume neithere
2
→
∗
K f
2
nore
2
↑
. Thenwemust havee
2
→
∗
BAD. By the denition of
and the fa t thate
1
e
2
, ife
2
→
∗
BAD,thene
1
→
∗
BAD. Sin e
e
1
→
∗
K f
1
,werea ha ontradi tionandwearedone.
(b) Given
e
1
↑
,assumee
2
6 ↑
. Thene
2
→
∗
val
andthereexistsasynta ti ally safe ontext
C
su hthatC[[e
2
]] →
∗
BAD. But
C[[e
1
]]
alwaysdivergesase
1
divergesifBAD∈
/
s
C
. Bythefa t thate
1
e
2
andbythedenition of, werea ha ontradi tionandwearedone.( ) Given
e
1
is rash-free, assumee
2
is not rash-free. By Denition 5 p12(Crash-freeExpression), there exists a synta ti ally safe ontext
C
su h thatC[[e
2
]] →
∗
BAD. Bythefa t that
e
1
e
2
andby thedenition of, wehaveC[[e
1
]] →
∗
BAD. This ontradi tswithanotherassumptionthat
e
1
is rash-free. Sin ewerea ha ontradi tion,wearedone.(d) Theproofissimilarto thatin(a).
4 Contra ts
Findler and Felleisen (FF) rst introdu ed an algorithm for dynami higher order ontra t he king[13℄. BlumeandM Allester[7℄thendeneasemanti s for ontra tsatisfa tion and show its sound-and- ompletenesswith respe tto the FF-algorithm. As the algorithm and the ontra t semanti s are dened by two groupsofpeople, there are somemismat hesaddressedin [12℄. Later, [39℄ denes both a ontra t semanti s and a (stati ) he king algorithm for a lazy language. In this paper, we follow the style in [39℄, design ontra t satisfa tionand he kingalgorithmforastri tlanguage.Asdiverging ontra ts makedynami ontra t he kingunsound(explainedinSe tion4.5)andwedo hybrid he king,wefo usontotal ontra ts.
Denition8 (Total ontra t). A ontra t
t
istotal it
is{x | p}
andλx.p
istotal(i.e. rash-free, terminating) ort
isx : t
1
→ t
2
andt
1
istotalandfor all
val
1
∈ t
1
, t
2
[val
1
/x]
istotal ort
is(x : t
1
, t
2
)
andt
1
istotalandfor all
val
1
∈ t
1
, t
2
[val
1
/x]
istotal ort
isAnyOurdenition oftotal ontra tisdierentfrom thatin[7℄,but losetothe rash-free ontra tin[39℄withanadditional onditionthat
λx.p
isaterminating fun tion. Forexample, ontra t{x | x 6=
[℄} → {y |
headx > y}
is totalin ourframeworkbe auseheadx
doesnot rashforallx
satisfying{x | x 6=
[℄}
. Su ha ontra tisnottotalin [7℄be ausea rashing fun tionheadis alledin apredi ate ontra t.4.1 Type he king for ontra ts
A ontra ttypejudgementhastheform
Γ ⊢
c
t ∈ τ
whi h statesthat given
Γ
(a mapping from program variable to its type, and fromtypevariableα
toitskindk
),e
hastypeτ
assumingthatanyfreevariable in ithastypegivenbyΓ
. Contra ttype he kingrulesareshownin Figure4.Γ, α :: k ⊢
c
t :: τ
Γ ⊢
c
(∀α :: k. t) :: τ
[
C-Forall]
Γ ⊢
c
Any:: τ
[
C-Any]
Γ, x :: τ ⊢
c
e ::
BoolΓ ⊢
c
{x | e} :: τ
[
C-One]
Γ ⊢
c
t
1
:: τ
1
Γ, x :: τ
1
⊢
c
t
2
:: τ
2
Γ ⊢
c
x : t
1
→ t
2
:: τ
1
→ τ
2
[
C-Fun]
Γ ⊢
c
t
1
:: τ
i
Γ, x :: τ
1
⊢
c
t
2
:: τ
2
Γ ⊢
c
(x : t
1
, t
2
) :: (τ
1
, τ
2
)
[
C-Tuple]
Figure 4: TypeChe kingRulesforContra t
Forawell-typedexpression
e
,denee ∈ t
thus:e ∈ {x | p}
⇐⇒
e ↑
or(e
is rash-freeand [A1℄p[e/x] →
∗
true
)
e ∈ x : t
1
→ t
2
⇐⇒
e ↑
or(e →
∗
λx.e
2
and [A2℄∀val
1
∈ t
1
. (e val
1
) ∈ t
2
[val
1
/x])
e ∈ (x : t
1
, t
2
)
⇐⇒
e ↑
or(e →
∗
(val
1
, val
2
)
and [A3℄val
1
∈ t
1
andval
2
[val
1
/x] ∈ t
2
[val
1
/x])
e ∈
Any⇐⇒
true [A4℄Figure 5: Contra tSatisfa tion
4.2 A semanti s for ontra t satisfa tion
We givethe semanti s of ontra ts by dening
e
satisest
" (writtene ∈ t
) in Figure 5 inspired by [7, 39℄. Here are some onsequen es: (1) a divergent expression satises any ontra t, hen e all ontra ts are inhabited; (2) only rash-free expressionsatises apredi ate ontra t;(3) anyexpression satises ontra tAny;(4) BADonlysatises ontra tAny.Onedieren e from [39℄ is that, wedo notallow
p[e/x]
in [A1℄ to diverge while [39℄allowsbe ausetheyonly dostati he king. Wesupport dependent tuple ontra ts, that are not in [7, 39℄. One dieren e from [7℄ is that, they say that a rashing expression does not satisifay any ontra t; wesay that a rashing expression satisfy the universal ontra tAny. Having atop ordering ontra tisdebated in [12℄whereasub ontra tordering isdened below. It is obviousthatAnyisusefulinalazylanguage[39℄aswemaywanttoignoresome sub omponentsof a onstru tor. WeexplainwhyAnyisalsousefulforastri t languagein Se tion4.6.Denition9 (Sub ontra t). Forall losed ontra ts
t
1
andt
2
,t
1
isa sub on-tra toft
2
,writtent
1
≦ t
2
,i∀e. e ∈ t
1
⇒ e ∈ t
2
4.3 The wrappers
e ⊲ t = e
BADl1
⊲⊳
UNRl2
t
e ⊳ t = e
UNRl2
⊲⊳
BADl1
t
e
⊲⊳
r
r
1
2
{x | p} =
letx = e
inifp
thenx
elser
1
[P1]
e
r
1
⊲⊳
r
2
x : t
1
→ t
2
=
lety = e
inλx
1
.((y (x
1
r
2
⊲⊳
r
1
t
1
))
r
1
⊲⊳
r
2
t
2
[(x
1
r
2
⊲⊳
r
1
t
1
)/x])
[P2]
e
⊲⊳
r
r
1
2
(x : t
1
, t
2
) =
mat he
with(x
1
, x
2
) → (x
1
r
1
⊲⊳
r
2
t
1
, x
2
r
1
⊲⊳
r
2
t
2
[(x
1
r
2
⊲⊳
r
1
t
1
)/x])
[P3]
e
⊲⊳
r
r
1
2
Any= r
2
[P4]
Figure6: Contra t he kingwiththewrappers
AsmentionedinSe tion2,theessen eof ontra t he kingisthetwo wrap-pers
⊲
and⊳
, whi h aredual toea hother (denedin Figure 6). Weomitthe labelsfor⊲
and⊳
whosefullversionsare⊲
l
1
l
2
and⊳
l
1
l
2
respe tively. Thewrappedexpression
e
r
1
⊲⊳
r
2
t
expandstoaparti ularexpression,whi hbehavesthesamease
ex eptthatitraisesblamer
1
ife
doesnotobeyt
andraiser
2
ifthewrapped termisusedinawaydisobeyingt
.From[P1℄to[P3℄, if
e
rashes,thewrappedterm rashes;ife
diverges,the wrapped term diverges. Wheneveranr
i
is rea hed, weknow the propertyp
does not evaluate to true (as in [P1℄). The wrappers are dened su h that Theorem2holds.Theorem2(Sound-and- ompletenessof ontra t he king). Forall losed ex-pression
e
τ
, losedandtotal ontra t
t
τ
,
(e ⊲ t)
is rash-free⇐⇒
e ∈ t
Thesupers ript
τ
saysbothe
andt
arewell-typedandhavethesametypeτ
. ThefullproofofTheorem2isinAppendixA,whi hissimilartothatin[40℄. Inpra ti e,weonlyneedThereom3,i.e. onedire tionofThereom2.Theorem 3 (Soundness of ontra t he king). For all losed expression
e
τ
, losedandterminating ontra t
t
τ
,
(e ⊲ t)
is rash-free⇒
e ∈ t
Notethat,if
t
isterminatingande⊲t
is rash-free,thent
istotal. Unlike[13℄, whi hassumesthereisnoex eptionfroma ontra titself,our ontra t he king algorithm helpsprogrammersto ensureitbydete tingex eptions in ontra tsthemselves. Theterm
t
2
[(v
r
2
⊲⊳
r
1
t
1
/x]
in [P2℄ and [P3℄ saysthat, we wrapea h (fun tion) all in a ontra t with its ontra t so that if there is any ontra t violationina ontra t,wereportthiserror. Forexample:ontra t f = k:({x | x > 0 } -> {y | y > 0 }) -> {z | k 0 > -1}
let f g = g 2
let t2 = f (fun x -> x)
a ontra t violation o urs in {z | k 0 > -1} be ause the all k 0 fails k's pre ondition{x | x > 0}. Asaddressedin[10℄,weshouldblamethe ontra t. Weomitpassingaroundthenameofthe ontra tinthis paperasourfo usis to he ktherea habilityofBAD.Instead,weuse
r
1
toindi atethatthelabelofr
1
isrepla edbythenameofthe ontra t.4.4 Open expressions and ontra ts
Foropenexpressions,weusethesameideain [39℄. Suppose thede lared on-tra tsforfandgare
t
f
, t
g
respe tively,andthedenitionofgisg= e
g
where fis alledine
g
. Then,insteadof he kingthate
g
∈ t
g
,we he kthat(λf. e
g
) ∈ t
f
→ t
g
Thatmeanswesimplylambda-abstra toveranyvariablesfreein
e
g
. Thesame ideaappliesforthere ursivefun tions. Iftheprogrammerspe iesthe ontra tt
f
foradenitionf= e
,thenitsu esto he kthatλf.e ∈ t
f
→ t
f
whi h iseasier be ause
λf.e
doesnot allfre ursively. There is nothingnew hereitisjustthestandardte hniqueofloopinvariantsinanotherguisebut itispa kagedvery onveniently.Inotherwords,imaginewehavea ontra tjudgement:
∆ ⊢ e ∈ t
whi hstatesthatgiven
∆
,whi hisamappingfromvariabletoitstype, ontra t anddenition.Denition 10 (Contra t judgement). We write
∆ ⊢ e ∈ t
to mean thate
has ontra tt
assuming that any free variable ine
has ontra t given by∆
and any free variable int
has denition given by∆
. Suppose∆ = {f
1
7→
(τ
1
, t
1
, e
1
), . . . , f
n
7→ (τ
n
, t
n
, e
n
)}
,wedene:∆ ⊢ e ∈ t ⇐⇒ λf
1
. . . . .f
n
.e ∈ t
1
→ · · · → t
n
→ t
Thismeans,intheory(i.e. in theformalizationoftheveri ation),weonly need to dealwith losed expressions; in pra ti e(i.e. in theimplementation), wemayrefertotheenvironment
∆
whenne essary. We ansimply he k rash-freenessofe[(g ⊳ t
g
)/g] ⊲ t
f
[(g ⊳ t
g
)/g]
wherea alltog
isrepla edbyg ⊳ t
g
. This ideaholds forre ursive alls off
ine
aswell,we he ke[f ⊳ t
f
/f ] ⊲ t
f
. (Note thatf
is notallowedto beusedint
f
.)4.5 Terminating ontra ts
We want
p
in{x | p}
to be terminating be ause a divergent ontra t hides rashes. Forexample:let re loop x = loop x
ontra t fb = {x | loop x} -> {y | true} let fb x = head [℄
fb
⊲ t
fbis
λx
1
.((λx.
head[ ]) (
ifloopx
1
thenx
1
elseBAD))
, whi hdiverges wheneverapplied be auseofthe loop. However,the fun tion fbisnot rash-free.Consider the higher order fun tion f in Se tion 4.3, one might wonder whether we have to he k the argument of the higherorder fun tion f to be terminatingbe ausek is alledin the ontra t. Theanswerisno. By inspe t-ing[P1℄and[P2℄,we anseethatanargumentisalwaysevaluatedearlierthan the
x
int
2
. So we will not en ounter the situation that a divergent ontra t hides a rash.Weonlyhavetoproveterminationoffun tionsusedin ontra ts,notallthe fun tions in aprogram. We anadapt ideasin [26, 34, 4℄to buildan e ient automati termination he ker.
4.6 Contra t Any
Thereisadebatein[12℄onwhetheritisusefultohaveatopordering ontra t Any. We want Any be ause we want to give a fun tion, that always fails, a ontra ttosatisfy,sothatwedonotblameitat itsdenitionsite duringSCC be ause
∀e, e⊲
Any=
UNR,whi his rash-free. ConsiderapopularOCamllibrary fun tion:ontra t failwith = {x | true} -> Any let failwith str = raise (Failure str)
where Failurehas typeEx eption. A alleroffailwith alwaysviolatesthe ontra tAnybe ause
∀e, e ⊳
Any=
BAD. Forexample:let get a i = if i >= 0 and i < Array.length a - 1 then a.(i) else failwith "Out of bound"
Whenevertheelse-bran hisrea hed(eitherin SCCorDCC),the allergetis blamed be auseasafeprogramismeantnotto invokeafun tionthat fails. It isnotusefultoblamethefailwithitself. Certainly,programmers'intentionis nottohaveanindexoutofboundsotheymaygivegeta ontra t:
{a |
true} → {i | i ≥ 0 ∧ i <
Array.lengtha − 1} → {z |
true}
sothata allerofgetwillbeblamed ifitfailsget'spre ondition.Theexampleunderdebatein [12℄issomethinglike:
ontra t id = ({x | x /= 0} -> {y | true}) -> Any let id x = x
let t3 = let invert y = 1/y in (id invert) 0
If programmers' intention is not to dene a fun tion that always fails, they shouldrepla eAnyby{z | true},whi hneverassignsblamebe ause
∀e, e⊲{z |
true} = e ⊳ {z |
true} = e
. With this new ontra t, id is blamed in either SCCorDCCforviolatingits ontra tbe auseid annotguaranteea rash-freeresult (required by {z | true}) when taking anon- rash-free fun tion as its argument.
Withthede larativesemanti sfor ontra tsatisfa tion, ontra ts anbe ex-portedforseparate ompilation. Animplementationofafun tion may hange overtime(e.g. havingamoree ientimplementation),but its exported on-tra tmaynot hange. Inourframework,werespe tafun tion's ontra tmore than its implementation. This is dierent from the original purpose in [13℄, whi honlyuses ontra tsfordynami blaming.
Wehaveasimplelemmafor ontra tAny.
Lemma8(Contra tAny). (a) If BAD
∈ t
,thent =
Any. (b) IfBAD⊲ t
is rash-free, thent =
Any.Proof. (a) Byinspe tingthedenitionof
∈
,theonly ontra tthatBAD satis-esisAny.(b) Byinspe tingthedenitionof
⊲
,forallt
su hthatt 6=
Any,BAD⊲t →
∗
BAD whi hisnot rash-free. AndwehaveBAD
⊲
Any=
UNRwhi his rash-free, sowearedone.4.7 Contra t ordering
thesub ontra trelation anbeillustratedinrule-formshowninFigure7. Ea h rule in Figure 7is atheorem. Therelation
p ⇒
e
q
in rule [C-Pred℄ isdened in Denition 11. Rule [C-Any℄ follows dire tly from the denition of≦
. We now study the rules [C-Pred℄, [C-DepFun℄ and [C-DepTup℄. We assume the statementabovethelineistrue,andprovethestatementbelowthelineistrue. Weleavetheproofofotherdire tionasaopenproblem.p ⇒
e
q
{x | p} ≦ {x | q}
[
C-Pred]
t ≦
Any[
C-Any]
t
1
≦ t
3
∀e ∈ t
1
, t
2
[e/x] ≦ t
4
[e/x]
(x : t
1
, t
2
) ≦ (x : t
3
, t
4
)
[
C-DepTup
]
t
3
≦ t
1
∀e ∈ t
3
, t
2
[e/x] ≦ t
4
[e/x]
x : t
1
→ t
2
≦ x : t
3
→ t
4
[
C-DepFun
]
Figure 7: Sub ontra tRelation
Denition11(BooleanExpressionImpli ation). Forallbooleanexpressions
p
andq
,wesayp
impliesq
(writtenp ⇒
e
q
)i ifq
then()
elseBAD ifp
then()
elseBAD FromDenition11 p21,forexample,weknow
{x | x < 10} ⇒
e
{x | x < 12}
. Thesubstitution for ontra tsisdened inFigure8. Here,weassumeea h boundvariablehasauniquename.{x | p}[e/y]
=
{x | p[e/y]}
(x : t
1
→ t
2
)[e/y] =
x : t
1
[e/y] → t
2
[e/y]
(t
1
, t
2
)[e/y]
=
(t
1
[e/y], e
2
[e/y])
Any
[e/y]
=
AnyFigure8: Substitution forContra ts
4.7.1 Predi ate Contra t Ordering
Weprovethat therule[C-Pred℄issound; thatisweproveTheorem4 p22
.
Theorem4(Predi ateContra tOrdering). Forallexpressions
p
,q
, ifp ⇒ q
then{x | p} ≦ {x | q}
.Proof. Wehavethefollowingproofforall
t
1
, t
2
, t
3
, t
4
:p ⇒
e
q
⇐⇒
(
ByDenition11 p21(BooleanExpressionImpli ation), let
e
1
=
asep
of True→ ()
False→
BAD
ande
2
=
aseq
of True→ ()
False→
BAD
)
e
2
e
1
⇐⇒
(
ByDenition7 p14 (Crashes-more-often))
∀C. C[[e
2
]] →
∗
BAD⇒ C[[e
1
]] →
∗
BAD
⇒
(
By(*)below)
∀e. e
is rash-freeand(e
1
[e/x] 6→
∗
{
BAD
,
False} ⇒ e
2
[e/x] 6→
∗
{
BAD
,
False})
⇐⇒
(
Bylogi anddenition of∈
in Figure5)
∀e. e ∈ {x | e
1
} ⇒ e ∈ {x | e
2
}
⇐⇒
(
ByDenition9 p17(Sub ontra t)
)
{x | e
1
} ≦ {x | e
2
}
(*) Weknow
∀e, a, x. e[a/x] ≡
s
letx = a
ine.
Assumingforall rash-freee
:(1) ∀C. C[[e
2
]] →
∗
BAD⇒ C[[e
1
]] →
∗
BAD
(2) (
letx = e
ine
1
) 6→
∗
{
BAD
,
False})
wewanttoshow(
letx = e
ine
2
) 6→
∗
{
BAD
,
False}
Suppose(
letx = e
ine
2
) →
∗
BAD
By(1), let
C
beletx = e
in•
,wehaveC[[e
1
]] →
∗
BAD
.
That means(
letx = e
ine
1
) →
∗
BAD
.
This ontradi tswith(2)soourassumptioniswrongandwearedone.
Suppose
(
letx = e
ine
2
) →
∗
False
By(1), let
C
be ase(
letx = e
in•)
of{
False→
BAD}
,wehaveC[[e
1
]] →
∗
BAD
.
That means(
ase(
letx = e
ine
1
)
of{
False→
BAD}) →
∗
BAD
.
That means(
letx = e
ine
1
) →
∗
{
BAD
,
False}.
This ontradi tswith(2)soourassumptioniswrongandwearedone.
4.7.2 DependentFun tion Contra t Ordering
Weprovethat therule[C-DepFun℄issound;that isweproveTheorem5 p23
.
Theorem5(DependentFun tionContra tOrdering). Forall
t
1
, t
2
, t
3
, t
4
. ift
3
≦ t
1
and∀e ∈ t
3
. t
2
[e/x] ≦ t
4
[e/x],
thenx : t
1
→ t
2
≦ x : t
3
→ t
4
Proof. Wehavethefollowingproofforallt
1
, t
2
, t
3
, t
4
:t
3
≦ t
1
and∀e
3
∈ t
3
. t
2
[e
3
/x] ≦ t
4
[e
3
/x]
⇐⇒
(
ByDenition9 p17(Sub ontra t)
)
(†
1
)
∀e
1
. e
1
∈ t
3
⇒ e
1
∈ t
1
and∀e
3
∈ t
3
.∀e
2
. e
2
∈ t
2
[e
3
/x] ⇒ e
2
∈ t
4
[e
3
/x]
⇒
(
Bythe(*) below)
(†
2
)
∀e. ∀e
1
∈ t
1
. (e e
1
) ∈ t
2
[e
1
/x] ⇒ ∀e
3
∈ t
3
. (e e
3
) ∈ t
4
[e
3
/x]
⇐⇒
(
Bydenitionof∈
in Figure5)
∀e. e ∈ x : t
1
→ t
2
⇒ e ∈ x : t
3
→ t
4
⇐⇒
(
ByDenition9 p17 (Sub ontra t))
x : t
1
→ t
2
≦ x : t
3
→ t
4
(∗)
Foralle
,assuming:(1) ∀e
1
. e
1
∈ t
3
⇒ e
1
∈ t
1
(
rst lauseoftheline†
1
)
(2) ∀e
3
∈ t
3
, ∀e
2
. e
2
∈ t
2
[e
3
/x] ⇒ e
2
∈ t
4
[e
3
/x] (
se ond lauseoftheline†
1
)
(3) ∀e
1
∈ t
1
.(e e
1
) ∈ t
2
[e
1
/x]
(
LHSoftheline†
2
)
weshow∀e
3
. e
3
∈ t
3
⇒ (e e
3
) ∈ t
4
[e
3
/x]
asfollows.e
3
∈ t
3
⇐⇒
(
By(1))
e
3
∈ t
1
⇐⇒
(
By(3))
(e e
3
) ∈ t
2
[e
3
/x]
⇐⇒
(
By(2))
(e e
3
) ∈ t
4
[e
3
/x]
Wearedone.4.7.3 Dependenttuple ontra t ordering
Weprovetherule[C-DepTup℄is soundbyshowing:
Forall
t
1
, t
2
, t
3
, t
4
.
ift
1
≦ t
3
andt
2
≦ t
4
,
then(t
1
, t
2
) ≦ (t
3
, t
4
)
Proof. Forall