Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has...

Post on 04-May-2020

19 views 0 download

Transcript of Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has...

RecaponReferences

SyntaxWeaddedto𝜆→(withUnit)syntacticformsforcreating,dereferencing,andassigningreferencecells,plusanewtypeconstructorRef.

EvaluationEvaluationbecomesafour-placerelation:t|µ ⟶ t′|µ′

TypingTypingbecomesathree-placerelation:Γ|Σ ⊢ t ∶ T

PreservationTheorem:if

Γ|Σ ⊢ t: TΓ|Σ ⊢ 𝜇t|𝜇 ⟶ t6|µ

then,forsome Σ6 ⊇ Σ,Γ|Σ′ ⊢ t′: TΓ|Σ′ ⊢ 𝜇′.

ProgressTheorem:Supposet isaclosed,well-typedterm(thatis,∅|Σ ⊢ t: T forsomeT andΣ).Theneither t isavalueorelse,foranystore𝜇 suchthat∅|Σ ⊢ 𝜇,thereissometermt′andstore𝜇′ witht|𝜇 ⟶ t′|𝜇′.

Chapter14:Exceptions

WhyexceptionsRaisingexceptions(abortingwholeprogram)

HandlingexceptionsExceptionscarryingvalues

Exceptions

Whyexceptions?Real world programming is full of situations where afunction needs to signal to it caller that it is unable toperform its task for :– Divisionbyzero– Arithmeticoverflow– Arrayindexoutofbound– Lookupkeymissing– Filecouldnotbeopened– ……

Whyexceptions?Most programming languages provide some mechanism forinterrupting the normal flow of control in a program to signalsome exceptional condition ( & the transfer of control flow) .

Note that it is always possible to program withoutexceptions :– instead of raising an exception, return None– instead of returning result 𝑥 normally, return Some(x)

But if we want to wrap every function application in a case tofind outwhether it returned a result or an exception?

It is much more convenient to build this mechanism into thelanguage.

Whyexceptions?#type ′𝛼 list=None|Someof′𝛼

#letheadl=matchlwith[] ->None

|x::_ ->Some(x);;

Whyexceptions?#type′𝛼 list=None|Someof′𝛼#letheadl =matchlwith

[] ->None| x::_ ->Some(x);;

Typeinference?

Whyexceptions?#type ′𝛼 list=None|Someof′𝛼#letheadl =matchlwith

[] ->None| x::_ ->Some(x);;

Whatistheresultoftypeinference?val head:′α list->′α Option=<fun>#letheadl =matchlwith

[] ->raiseNot_found| x::_ ->x;;

val head:′α list->′α =<fun>

Varietiesofnon-localcontrolThere are many ways of adding “non-local control flow”– exit(1)– goto– setjmp/longjmp– raise/try (or catch/throw) inmany variations– callcc / continuations– more esoteric variants (cf. many Scheme papers)

which allow programs to effect non-local “jumps” in theflow of control.

Let’s begin with the simplest of these.

Raisingexceptions(abortingwhole program)

An“abort”primitivein𝜆→Raising exceptions (but not catching them), which causethe abort of the whole program.

Evaluation

Syntactic forms

TypingTyping

TypingerrorsNotethatthetypingrule forerror allowsustogiveitanytypeT.

Whatifwehadbooleans andnumbersinthelanguage?

TypingerrorsNotethatthetypingruleforerror allowsustogiveitanytypeT.

Thismeansthatboth𝑖𝑓𝑥 > 0𝑡ℎ𝑒𝑛5𝑒𝑙𝑠𝑒𝑒𝑟𝑟𝑜𝑟

and𝑖𝑓𝑥 > 0𝑡ℎ𝑒𝑛𝑡𝑟𝑢𝑒𝑒𝑙𝑠𝑒𝑒𝑟𝑟𝑜𝑟

willtypecheck.

Whatifwehadbooleans andnumbersinthelanguage?

Aside:Syntax-directednessNote:thisrule

hasaproblem fromthepointofviewofimplementation:itis not syntaxdirected.ThiswillcausetheUniquenessofTypestheoremtofail.

Forpurposesofdefiningthelanguageandprovingitstypesafety,thisisnotaproblem— UniquenessofTypesisnotcritical.

Let’sthinkalittleabouthowtherulemightbefixed...

Aside:Syntax-directedrulesWhen we say a set of rules is syntax-directed we meantwo things:1. There is exactly one rule in the set that applies to each syntactic

form (in the sense that we can tell by the syntax of a termwhich rule to use.)– e.g., to derive a type for t1 t2, we must use T-App.

2. We don't have to “guess" an input (or output) for any rule.– e.g., to derive a type for t1 t2, we need to derive a type for

t1 and a type for t2.

Analternative: AscriptionCan’t we just decorate the error keywordwith its intendedtype, as we have done to fix related problems with otherconstructs?

Analternative:Ascription

Can’t we just decorate the error keyword with itsintended type, as we have done to fix related problemswith other constructs?

No, this doesn’t work!e.g. assuming our language also has numbers andbooleans:

succ if(errorasBool then3else8)⟶ succ(errorasBool)

Anotheralternative:VariabletypeIn a system with universal polymorphism (like OCaml),the variability of typing for errorcan be dealt with byassigning it a variable type ?

Γ ⊢ error∶6α (T-ERROR)

Anotheralternative:VariabletypeIn a system with universal polymorphism (like OCaml),the variability of typing for error can be dealt with byassigning it a variable type!

Γ ⊢ error∶6α (T-ERROR)

In effect, we are replacing the uniqueness of typingproperty by a weaker (but still very useful) propertycalled most general typing.– i.e., although a term may havemany types, we always

have a compact way of representing the set of all ofits possible types.

Yetanotheralternative:minimaltype

Alternatively, in a system with subtyping (which will bediscussed in chapter 15) and a minimal Bot type, we cangive error a unique type:

Yetanotheralternative:minimaltypeAlternatively, in a system with subtyping (which will bediscussed in chapter 15) and a minimal Bot type, we cangive error a unique type:

Note :Whatwe’vereallydoneisjustpushedthecomplexity oftheolderrorruleontotheBot type!

Fornow...Let’sstickwiththeoriginalrule

andlivewiththeresultingnon-determinism ofthetypingrelation.

TypesafetyPropertyofpreservation?

Thepreservationtheoremrequiresnochangeswhenweadderror:

ifatermoftypeT reducestoerror,that’sfine,sinceerror haseverytypeT.

TypesafetyPropertyofpreservation?

Thepreservationtheoremrequiresnochangeswhenweadderror::

ifatermoftypeT reducestoerror,that’sfine,sinceerror haseverytypeT.

Whereas,Progressrequiresalittlemorecare.

ProgressFirst,note thatwedonot wanttoextendthesetofvaluestoincludeerror,sincethiswouldmakeournewruleforpropagating errors throughapplications.

overlapwith ourexistingcomputationruleforapplications:

e.g,thetermλx:Nat. 0 error

couldevaluatetoeither0 (whichwouldbewrong)orerror (whichiswhatweintend).

ProgressInstead,wekeeperror asanon-valuenormalform,andrefinethestatementofprogresstoexplicitlymentionthepossibilitythattermsmayevaluate to𝑒𝑟𝑟𝑜𝑟insteadoftoavalue.

Theorem[Progress]: Supposet isaclosed,well-typednormalform.Theneither t isavalue or𝑡 = 𝑒𝑟𝑟𝑜𝑟.

Handlingexceptions

Catchingexceptions

Evaluation

Typing

Exceptionscarryingvalues

ExceptionscarryingvaluesWhensomethingunusualhappened,it’susefultosendbacksomeextrainformationaboutwhichunusual thinghashappenedsothatthehandlercantakesomeactionsdependingonthisinformation.

ExceptionscarryingvaluesWhensomethingunusualhappened,it’susefultosendbacksomeextrainformationaboutwhichunusual thinghashappenedsothatthehandlercantakesomeactionsdependingonthisinformation.

ExceptionscarryingvaluesWhensomethingunusualhappened,it’susefultosendbacksomeextrainformationaboutwhichunusual thinghashappenedsothatthehandlercantakesomeactionsdependingonthisinformation.

Atomictermerror isreplacedbyatermconstructorraiset

where 𝑡 istheextrainformationthatwewanttopasstotheexceptionhandler.

Evaluation

Evaluation

TypingTotypecheck raise expressions,weneedtochooseatypeforthevalues thatarecarriedalongwithexceptions, let’scallitT_`a

b⊢cd:efghb⊢ijklmcd∶e

(T-RAISE)

b⊢cd∶eb⊢cn∶efgh⟶eb⊢ciocdpkcqcn∶e

(T-TRY)

WhatisT_`a ?Further,weneedtodecidewhattype touseasT_`a.Thereareseveralpossibilities.1. Numericerrorcodes:T_`a =Nat (asinUnix)2. Errormessages:T_`a =String3. Apredefined varianttype:

4. Anextensible varianttype(asinOcaml)5. Aclassof“throwable objects”(asinJava)

Recapitulation:Errorhandling

Recapitulation:Exceptionscarryingvalues

RecapitulationRaisingexceptionismorethananerrormechanism: it’saprogrammablecontrolstructure– Sometimesawaytoquicklyescape fromthecomputation.– Andallowprogramstoeffectnon-local“jumps” intheflowof

controlbysettingahandlerduringevaluationofanexpressionthatmaybeinvokedbyraisinganexception.

– Exceptionsarevalue-carryinginthesensethatonemaypassavalueto theexceptionhandlerwhentheexceptionisraised.

– Exceptionvalueshaveasingletype,T_`a ,whichissharedbyallexceptionhandler.

RecapitulationE.g., ExceptionsareusedinOCaml asacontrolmechanism, either tosignalerrors,or tocontroltheflowofexecution.– Whenanexceptionisraised,thecurrentexecutionisaborted,

andcontrolisthrowntothemostrecentlyenteredactiveexceptionhandler,whichmaychoosetohandletheexception,orpassitthroughtothenextexceptionhandler.

– T_`a is defined to be an extensible data type, in the sense thatnew constructors may be introduced using exceptiondeclaration, with no restriction on the types of value that maybe associated with the constructor.

ExamplesinOCaml#letrecassoc key=function

(k,v)::l->ifk=keythenvelseassoc keyl

|[]->raiseNot_found;;val assoc :'a->('a*'b)list->'b=<fun>

#assoc 2l;;- :string="World“#assoc 3l;;- Exception:Not_found.#"Hello"̂ assoc 2l;;- :string="HelloWorld"

ExamplesinOCamlletfind_index p=

letrecfindn=function[]->raise(Failure"notfound")

|x::L-> ifp(x)thenraise(Foundn)elsefind(n+1)L

intryfind1L withFoundn->n;;

HW forchap14• 14.3.1