• Aucun résultat trouvé

Hybrid Contract Checking via Symbolic Simplification

N/A
N/A
Protected

Academic year: 2021

Partager "Hybrid Contract Checking via Symbolic Simplification"

Copied!
73
0
0

Texte intégral

(1)

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�

(2)

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

(3)
(4)

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

(5)

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

(6)

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

(7)

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 ause

x − 1 ≥ 0

does not hold for all

x

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 t

t

(written

e ∈ t

)without knowingitsimplementation. Next,wedeneawrapper

thattakesan expres-sion

e

and its ontra t

t

and produ esa term

e ⊲ t

su h that ontra t he ks areinsertedatappropriatepla esin

e

. Ifa ontra t he kisviolated,aspe ial onstru tor BAD

l

signalstheviolation. As theterm

e ⊲ t

isatermin thesame languageas

e

, allwehaveto do is to he k therea habilityof BAD

l

. If aBAD is rea hable,weknow a ontra tis violatedand the label

l

pre isely aptures thefun tion atfault. Wesymboli allysimplifytheterm

e ⊲ 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,

(8)

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

and

e⊲t

andproveatheorem

e⊲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 hesinŸ7.

ˆ 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 BAD

l

⊲⊳

BAD

l′

t

in

)

0

where

l

is

(2, 5, “

in

”)

indi ating the sour e lo ation where in is dened (row:2, ol:5) and

l

is

(3, 10, “

t1

”)

indi ating thelo ation of the allsite with aller'sname. Thiswrappedt1expandsto:

(λx

1

.

let

y =

in

(

let

x = x

1

in

if

x > 0

then

x

elseBAD

(3,10,“

t1

”)

)

in if

y > 0

then

y

elseBAD

(2,5,“

in

”)

) 0

Intheupperbox,theargumentofin isguardedbythe he k

x > 0

;inthelower box, theresultof in is guardedby the he k

y > 0

. Ifa he ksu eeds, the

(9)

originaltermisreturned;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 t

t

, to he k that the allee

f

and its aller agree on the ontra t

t

dynami ally, a he kerwrapsea h all to

f

withits ontra t:

f

BAD

f

⊲⊳

BAD

?

t

whi hbehavesthesameas

f

ex eptthat(a)if

f

disobeys

t

,itblames

f

,signaled by BAD

f

; (b) if the ontext uses

f

in a way notpermitted by

t

, itblames the allerof

f

,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

BAD

f

⊲⊳

UNR

?

t

and

e ⊳ t = e

UNR

f

⊲⊳

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 (if

p

then

e

else BAD) as (assert

p; e

) and (if

p

then

e

else UNR) as (assume

p; e

).)

SCCis modular and performed at denition site of ea h fun tion. For ex-ample,

(λv.v + 1) ⊲ t

in

expandsto:

λx

1

.

let

y = (λv.v + 1)

(

let

x = x

1

inif

x > 0

then

x

elseUNR

?

)

in

if

y > 0

then

y

elseBAD

(2,5,“

in

”)

Atthedenition siteofafun tion,

f = e

,weassume

f

'spre onditionholds and assertitspost ondition. IfallBADsin

e ⊲ t

arenotrea hable,weknow

f

satisesits ontra t

t

. Onewayto he krea habilityof BADis tosymboli ally simplify thefragment. Intheabove ase,inlining

x

,weget:

λx

1

.

let

y = (λv.v + 1) (

if

x

1

> 0

then

x

1

elseUNR

?

)

in

if

y > 0

then

y

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:

(10)

λv.v + 1

∃x

2

, (∀v, x

2

(v) = v + 1)

if

x

1

> 0

then

x

1

elseUNR

?

∃x

3

, (x

1

> 0 ⇒ x

3

= x

1

)∨

(not(x

1

> 0) ⇒ false)

One anthinkoftheexistentiallyquantied

x

2

(and

x

3

)denotingtheexpression itself. FortheRHSof

y

,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

f1

inŸ1. Sof1

⊲ t

f1

is

(λg.(g 1) −

1) ⊲ ({x | x ≥ 0} → {y | y ≥ 0}) → {z | z ≥ 0}

,whi hexpandsto:

λx

1

.

let

z = (λg.(g 1) − 1)

(λx

2

.

let

y = x

1

(

let

x = x

2

in if

x ≥ 0

then

x

elseBAD

(4,5,“f

1

”)

)

in if

y ≥ 0

then

y

elseUNR

?

)

in

if

z ≥ 0

then

z

elseBAD

(4,5,“f

1

”)

Afterapplyingsome onventionalsimpli ationrules,wehave:

R1

: λx

1

.

let

z =

let

y = x

1

1

in

if

y ≥ 0

then

y − 1

elseUNR

?

if

z ≥ 0

then

z

elseBAD

(4,5,“f

1

”)

WeseethattheinnerBAD

(4,5,“f

1

”)

hasbeensimpliedaway,be ause

x = x

2

= 1

and(if

1 ≥ 0

then

1

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

(11)

siteas ithasbeenguardedbyits ontra twith

f ⊳ t

. Thef3

⊲ t

f3

expandsto:

let

v =

let

z =

f1

(λx

2

.

let

y =

zut

(

let

x = x

2

in if

x ≥ 0

then

x

elseUNR

(7,10,“f

1

”)

)

in if

y ≥ 0

then

y

elseBAD

(7,10,“f

3

”)

)

in

if

z ≥ 0

then

z

elseUNR

(7,10,“f

1

”)

if

v ≥ 0

then

v

elseBAD

(7,10,“f

3

”)

As

is dual to

, the RHS of

v

is a tually a opy of the earlierf1

⊲ t

f1

but 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

.

let

y =

zut

(

let

x = x

2

in if

x > 0

then

x

elseUNR

(7,10,“f

1

”)

)

in if

y ≥ 0

then

y

elseBAD

(7,10,“f

3

”)

)

in

if

z ≥ 0

then

z

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:

(

if

e

0

then

e

1

elseUNR

) =⇒ e

1

[rmUNR]

(Weshallexplainwhyitisvalidtoapplythisruleevenif

e

0

maydivergeor rash inŸ6. Intuitively,UNRisindeedunrea hableand

e

0

hasbeen he kedbeforethis program point.) Applying therule [rmUNR℄to R1 andR2and simplify abit, weget:

f1

♯ = λx

1

.

let

z = (

let

y = (x

1

1)

in

y − 1)

in if

z ≥ 0

then

z

elseBAD

(4,5,“f

1

”)

f2

♯ =

f1

♯ (λx

2

.

let

y =

zut

x

2

in if

y ≥ 0

then

y

elseBAD

(7,10,“f

3

”)

)

respe tively, whi h is the residual ode beingrun. We show in Ÿ6 that HCC blamesafun tion

f

i

iDCCblames

f

i

.

Summary Given a denition

f = e

and a ontra t

t

, to he k

e

satises

t

(written

e ∈ t

), weperformthese steps. (1) Constru t

e ⊲ t

. (2) Simplify

e ⊲ t

asmu haspossibleto

e

(12)

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 ode

f ♯

bysimplifying

e

withtherule[rmUNR℄, andruntheprogramwithea h

f

beingrepla edby

f ♯

.

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 t

def

Definitions

def

::=

type

α T =

−−−−−→

K

of

τ

|

ontra t

f = t

|

let

f −

x = e

top-levelfun tion

|

let re

f −

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 h

e

0

with

alt

pattern-mat hing

|

K −

e

onstru tor

r

::=

BAD

l

|

UNR

l

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

(13)

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 let

x = e

1

in

e

2

is asynta ti sugar for

(λx.e

2

) e

1

. An if-expressionif

e

0

then

e

1

else

e

2

issynta ti sugarformat h

e

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. Butwemayomitthelabel

l

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 Emptylist

toBAD 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}

byassuming

x

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

(14)

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

:: τ

Γ ⊢ (

ase

e

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 ablame

r

,theotheralsoevaluatestothe same

r

.

Denition1(Semanti allyEquivalent). Twoexpressions

e

1

and

e

2

are seman-ti ally equivalent, namely

e

1

s

e

2

, i for all losing

C

, for all

r

,

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, written

e ↑

,ieither

e →

UNR,orthereisno value

val

su hthat

e →

val

(15)

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℄ Contexts

C

::=

[[•]] | C e | val C | K

−→

val C −

e

|

mat h

C

with

alt

Figure 3: Semanti softhelanguageM

3.4 Crashing

WeuseBADtosignalthatsomethinghasgonewrongintheprogram,whi h an beaprogramfailureora ontra tviolation.

Denition3 (Crash). A losedterm

e

rashesi

e →

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 ontext

C

issynta ti allysafe iBAD

/

s

C

.

Thenotation BAD

/

s

e

meansBADdoesnotsynta ti ally appearanywhere in

e

, 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 all

C

su hthat BAD

/

s

C

and

⊢ C[[e]] ::

bool

, C[[e]] 6→

BAD

.

The notation

⊢ C[[e]] ::

bool means

C[[e]]

is losed and well-typed. The quantied ontext

C

servestheusualroleofaprobethattriestoprovoke

e

into rashing. Note thata rash-freeexpression maynot be synta ti ally safe,e.g.

λx.

if

x ∗ x ≥ 0

then

x + 1

elseBAD.

Lemma1(Synta ti allysafeexpressionis rash-free).

e

issynta ti ally safe

e

is rash-free

Proof. Sin e there is no BAD synta ti ally in

e

, for all ontext

C

, su h that thereisnoBADsyntati allyin

C

,then

C[[e]] 6→

BAD.Bydenition5(Crash-free expression),

e

is rash-free.

Foreaseofpresentation,whenwedonotgivelabel

l

toBADorUNR,wemean BADorUNRforany

l

. Moreover,expressionsBAD

l

andUNR

l

are losedexpressions evenif

l

isnotexpli itlybound.

(16)

Proof. Sin e

e

is rash-free,allBADsin

e

arenotrea hablesoby onvertingall BADsin

e

toUNRby

⌊.⌋

doesnot hangethesemanti sof

e

. 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

and

C[[e

2

]] →

BAD. By[E- tx℄and

e

1

→ e

2

and

C[[e

2

]] →

BAD, we have:

C[[e

1

]] →

C[[e

2

]] →

BAD. Asweknow

e

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

and

C[[e

1

]] →

BAD. By[E- tx℄and

e

1

→ e

2

and onuen e of thelanguage,wehave

C[[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-free

e

, e[e

/x]

is rash-free

(

)Wehavethefollowingproof. forall

cf

e

, e[e

/x]

is rash-free

⇐⇒

(

ByLemma 3 p13

)

forall

cf

e

, (λx.e) e

is rash-free

⇐⇒

(

ByDenition 5 p12 (Crash-freeExpression)

)

forall

cf

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-free

(17)

3.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 thesameas

e

2

w.r.t. a set of ex eptions

R

, written

e

1

R

e

2

, ifor all ontexts

C

, su h that

∀i ∈

{1, 2}. ⊢ C[[e

i

]] ::

bool

C[[e

2

]] →

r ∈ R

C[[e

1

]] →

r

Denition 6 p14

saysthat

e

1

either behavesthesameas

e

2

orthrowsan ex- eption from

R

. (The denition doesnotlook asstrong asthat, but asevery theorist knows, it is. Forexample, ould

e

1

produ e true while

e

2

produ es false? No,be ausewe ouldnda ontext

C

thatwouldmake

C[[e

2

]]

throwan ex eption while

C[[e

1

]]

does not.) In ourframework, thereare only two ex ep-tionalvaluesin

R

: BADandUNR.Certainly,if

e

2

itselfthrowsanex eption,then

e

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

{}

ifthereisonlyoneelementin

R

.

Lemma5(PropertiesofBehaves-the-same). Forall losed

e

1

and

e

2

,

e

1

UNR

e

2

⇐⇒ e

2

BAD

e

1

Proof. Weprovetwodire tions separately.

(

)Wehavethefollowingproof:

e

1

UNR

e

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. Assume

D[[e

1

]] →

BAD.

Let

C =

mat h

(D[[•]])

with

{

DEFAULT

UNR

}

Nowwehave

C[[e

1

]] →

BAD

⇒ C[[e

2

]] 6→

UNR.

Sin e

C[[e

2

]] =

ase

D[[e

2

]]

with

{

DEFAULT

UNR

}

,wehave

D[[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 than

e

2

,written

e

1

 e

2

,i

e

1

BAD

e

2

(18)

Informally,

e

1

rashesmoreoftenthan

e

2

iftheybehaveinexa tlythesame wayex eptthat

e

1

may rashwhen

e

2

doesnot. ByDenition7

p14

,Lemma5 p14

alsosaysthat:

e

1

UNR

e

2

⇐⇒ e

2

 e

1

Theorem1(Crashes-more-oftenisAntiSymmetri ). Forallexpressions

e

1

and

e

2

,

e

1

 e

2

and

e

2

 e

1

i

e

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)

BAD

 e

2

(b)

e

1

 e

2

if

e

2

Proof. Weproveea hpropertyseparately(allby ontradi tion)andweassume typesoundness.

(a) Assumethere exists a ontext

C

su hthat

C[[e

2

]] →

BADand

C[[

BAD

]] 6→

BAD. Therearetwopossibilitiesfor

C[[e

2

]] →

BAD: (1)theBADisfromthe ontext

C

; (2) the BAD is from the hole

e

2

. For ase (1), we must have

C[[

BAD

]] →

BADsin eweusethesame ontext

C

. For ase(2),ifthehole isevaluated, werea hBADimmediately. Sowerea ha ontradi tionand wearedone.

(b) Given

e

2

, assumethere exists a ontext

C

su hthat

C[[e

2

]] →

BADand

C[[e

1

]] 6→

BAD. Sin e

e

2

and

C[[e

2

]] →

BAD, we know the BAD is from the ontext

C

. Sonomatterwhat

e

1

is,wehave

C[[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

or

e

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

or

e

2

Proof. Weproveea hpropertyseparately(allby ontradi tion):

(a) Given

e

1

K f

1

, assume neither

e

2

K f

2

nor

e

2

. Thenwemust have

e

2

BAD. By the denition of



and the fa t that

e

1

 e

2

, if

e

2

BAD,then

e

1

BAD. Sin e

e

1

K f

1

,werea ha ontradi tion

andwearedone.

(b) Given

e

1

,assume

e

2

6 ↑

. Then

e

2

val

andthereexistsasynta ti ally safe ontext

C

su hthat

C[[e

2

]] →

BAD. But

C[[e

1

]]

alwaysdivergesas

e

1

divergesifBAD

/

s

C

. Bythefa t that

e

1

 e

2

andbythedenition of



, werea ha ontradi tionandwearedone.

(19)

( ) Given

e

1

is rash-free, assume

e

2

is not rash-free. By Denition 5 p12

(Crash-freeExpression), there exists a synta ti ally safe ontext

C

su h that

C[[e

2

]] →

BAD. Bythefa t that

e

1

 e

2

andby thedenition of



, wehave

C[[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 i

t

is

{x | p}

and

λx.p

istotal(i.e. rash-free, terminating) or

t

is

x : t

1

→ t

2

and

t

1

istotaland

for all

val

1

∈ t

1

, t

2

[val

1

/x]

istotal or

t

is

(x : t

1

, t

2

)

and

t

1

istotaland

for all

val

1

∈ t

1

, t

2

[val

1

/x]

istotal or

t

isAny

Ourdenition 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 |

head

x > y}

is totalin ourframeworkbe ausehead

x

doesnot rashforall

x

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

α

toitskind

k

),

e

hastype

τ

assumingthatanyfreevariable in ithastypegivenby

Γ

. Contra ttype he kingrulesareshownin Figure4.

(20)

Γ, α :: 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

,dene

e ∈ 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

and

val

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

satises

t

" (written

e ∈ 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

and

t

2

,

t

1

isa sub on-tra tof

t

2

,written

t

1

≦ t

2

,i

∀e. e ∈ t

1

⇒ e ∈ t

2

(21)

4.3 The wrappers

e ⊲ t = e

BAD

l1

⊲⊳

UNR

l2

t

e ⊳ t = e

UNR

l2

⊲⊳

BAD

l1

t

e

⊲⊳

r

r

1

2

{x | p} =

let

x = e

inif

p

then

x

else

r

1

[P1]

e

r

1

⊲⊳

r

2

x : t

1

→ t

2

=

let

y = 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 h

e

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. Thewrapped

expression

e

r

1

⊲⊳

r

2

t

expandstoaparti ularexpression,whi hbehavesthesameas

e

ex eptthatitraisesblame

r

1

if

e

doesnotobey

t

andraise

r

2

ifthewrapped termisusedinawaydisobeying

t

.

From[P1℄to[P3℄, if

e

rashes,thewrappedterm rashes;if

e

diverges,the wrapped term diverges. Wheneveran

r

i

is rea hed, weknow the property

p

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

τ

saysboth

e

and

t

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

isterminatingand

e⊲t

is rash-free,then

t

istotal. Unlike[13℄, whi hassumesthereisnoex eptionfroma ontra titself,our ontra t he king algorithm helpsprogrammersto ensureitbydete tingex eptions in ontra ts

themselves. 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:

(22)

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 atethatthelabelof

r

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 alledin

e

g

. Then,insteadof he kingthat

e

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 t

t

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 that

e

has ontra t

t

assuming that any free variable in

e

has ontra t given by

and any free variable in

t

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-freenessof

e[(g ⊳ t

g

)/g] ⊲ t

f

[(g ⊳ t

g

)/g]

wherea allto

g

isrepla edby

g ⊳ t

g

. This ideaholds forre ursive alls of

f

in

e

aswell,we he k

e[f ⊳ t

f

/f ] ⊲ t

f

. (Note that

f

is notallowedto beusedin

t

f

.)

4.5 Terminating ontra ts

We want

p

in

{x | p}

to be terminating be ause a divergent ontra t hides rashes. Forexample:

(23)

let re loop x = loop x

ontra t fb = {x | loop x} -> {y | true} let fb x = head [℄

fb

⊲ t

fb

is

λx

1

.((λx.

head

[ ]) (

ifloop

x

1

then

x

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

in

t

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.length

a − 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-free

(24)

result (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

,then

t =

Any. (b) IfBAD

⊲ t

is rash-free, then

t =

Any.

Proof. (a) Byinspe tingthedenitionof

,theonly ontra tthatBAD satis-esisAny.

(b) Byinspe tingthedenitionof

,forall

t

su hthat

t 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

and

q

,wesay

p

implies

q

(written

p ⇒

e

q

)i



if

q

then

()

elseBAD







if

p

then

()

elseBAD



FromDenition11 p21

,forexample,weknow

{x | x < 10} ⇒

e

{x | x < 12}

. Thesubstitution for ontra tsisdened inFigure8. Here,weassumeea h boundvariablehasauniquename.

(25)

{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]

=

Any

Figure8: 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

, if

p ⇒ 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

=

ase

p

of True

→ ()

False

BAD

and

e

2

=

ase

q

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

let

x = a

in

e.

Assumingforall rash-free

e

:

(1) ∀C. C[[e

2

]] →

BAD

⇒ C[[e

1

]] →

BAD

(2) (

let

x = e

in

e

1

) 6→

{

BAD

,

False

})

wewanttoshow

(

let

x = e

in

e

2

) 6→

{

BAD

,

False

}

Suppose

(

let

x = e

in

e

2

) →

BAD

By(1), let

C

belet

x = e

in

,wehave

C[[e

1

]] →

BAD

.

That means

(

let

x = e

in

e

1

) →

BAD

.

This ontradi tswith(2)soourassumptioniswrongandwearedone.

Suppose

(

let

x = e

in

e

2

) →

False

By(1), let

C

be ase

(

let

x = e

in

•)

of

{

False

BAD

}

,wehave

C[[e

1

]] →

BAD

.

That means

(

ase

(

let

x = e

in

e

1

)

of

{

False

BAD

}) →

BAD

.

That means

(

let

x = e

in

e

1

) →

{

BAD

,

False

}.

This ontradi tswith(2)soourassumptioniswrongandwearedone.

(26)

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

. if

t

3

≦ t

1

and

∀e ∈ t

3

. t

2

[e/x] ≦ t

4

[e/x],

then

x : t

1

→ t

2

≦ x : t

3

→ t

4

Proof. Wehavethefollowingproofforall

t

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

(∗)

Forall

e

,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

.

if

t

1

≦ t

3

and

t

2

≦ t

4

,

then

(t

1

, t

2

) ≦ (t

3

, t

4

)

Proof. Forall

e

,if

e

diverges,thenforall

t

1

, t

2

, t

3

, t

4

,

e ∈ (t

1

, t

2

)

and

e ∈ (t

3

, t

4

)

be ause adivergent expression satises all ontra ts. By the denition of

, we have the desired result

(t

1

, t

2

) ≦ (t

3

, t

4

)

. Now, we prove the ase when

Figure

Figure 1: Syntax of the language M
Figure 2: Type Cheking Rules
Figure 3: Semantis of the language M
Figure 4: Type Cheking Rules for Contrat
+7

Références

Documents relatifs

This report is the result of several discussions between WHO and Strategic Mediaworks, which has consulted with media experts, sociologists, film and television professionals

Each of the 87 health fairs was organized by local steering committees made up of representatives of all the statutory and voluntary bodies work- ing in the

A review by the EPPI-Centre at the Institute of Education, University of London, found that and collaborative professional development was linked with a positive

Quando arriva una interruzione alla CPU si ha l’automatica sospensione del processo in esecuzione sulla CPU (con il salvataggio del suo PCB) e l’attivazione di una routine di

If the format of the CHAR argument is the DATE default (MM/DD/YY), you are not required to specify the date picture. The result has the data type DATE. TO_DATE converts a

This manual describes ALLY release 2.0. This manual contains information fo developers on how to use ALL Y utilities. ALLY utilities allo you to manage and

Do not com pare keys in the key-definition file for assignment conflicts. The output produced by the Terminal Definer is an encoded file that contains all of the

Pourtant, quand mon père a envisagé de déménager, elle a été la première à faire des recherches et c’est grâce à elle que nous avons trouvé cette magnifique maison