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

49
Recap on References

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

Page 1: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

RecaponReferences

Page 2: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

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

Page 3: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

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

Page 4: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

TypingTypingbecomesathree-placerelation:Γ|Σ ⊢ t ∶ T

Page 5: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

PreservationTheorem:if

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

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

Page 6: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

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

Page 7: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

Chapter14:Exceptions

WhyexceptionsRaisingexceptions(abortingwholeprogram)

HandlingexceptionsExceptionscarryingvalues

Page 8: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

Exceptions

Page 9: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

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– ……

Page 10: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

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.

Page 11: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

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

#letheadl=matchlwith[] ->None

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

Page 12: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

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

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

Typeinference?

Page 13: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

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>

Page 14: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

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.

Page 15: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

Raisingexceptions(abortingwhole program)

Page 16: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

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

Evaluation

Syntactic forms

Page 17: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

TypingTyping

Page 18: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

TypingerrorsNotethatthetypingrule forerror allowsustogiveitanytypeT.

Whatifwehadbooleans andnumbersinthelanguage?

Page 19: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

TypingerrorsNotethatthetypingruleforerror allowsustogiveitanytypeT.

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

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

willtypecheck.

Whatifwehadbooleans andnumbersinthelanguage?

Page 20: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

Aside:Syntax-directednessNote:thisrule

hasaproblem fromthepointofviewofimplementation:itis not syntaxdirected.ThiswillcausetheUniquenessofTypestheoremtofail.

Forpurposesofdefiningthelanguageandprovingitstypesafety,thisisnotaproblem— UniquenessofTypesisnotcritical.

Let’sthinkalittleabouthowtherulemightbefixed...

Page 21: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

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.

Page 22: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

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

Page 23: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

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)

Page 24: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

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)

Page 25: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

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.

Page 26: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

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:

Page 27: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

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!

Page 28: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

Fornow...Let’sstickwiththeoriginalrule

andlivewiththeresultingnon-determinism ofthetypingrelation.

Page 29: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

TypesafetyPropertyofpreservation?

Thepreservationtheoremrequiresnochangeswhenweadderror:

ifatermoftypeT reducestoerror,that’sfine,sinceerror haseverytypeT.

Page 30: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

TypesafetyPropertyofpreservation?

Thepreservationtheoremrequiresnochangeswhenweadderror::

ifatermoftypeT reducestoerror,that’sfine,sinceerror haseverytypeT.

Whereas,Progressrequiresalittlemorecare.

Page 31: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

ProgressFirst,note thatwedonot wanttoextendthesetofvaluestoincludeerror,sincethiswouldmakeournewruleforpropagating errors throughapplications.

overlapwith ourexistingcomputationruleforapplications:

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

couldevaluatetoeither0 (whichwouldbewrong)orerror (whichiswhatweintend).

Page 32: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

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

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

Page 33: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

Handlingexceptions

Page 34: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

Catchingexceptions

Evaluation

Typing

Page 35: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

Exceptionscarryingvalues

Page 36: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

ExceptionscarryingvaluesWhensomethingunusualhappened,it’susefultosendbacksomeextrainformationaboutwhichunusual thinghashappenedsothatthehandlercantakesomeactionsdependingonthisinformation.

Page 37: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

ExceptionscarryingvaluesWhensomethingunusualhappened,it’susefultosendbacksomeextrainformationaboutwhichunusual thinghashappenedsothatthehandlercantakesomeactionsdependingonthisinformation.

Page 38: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

ExceptionscarryingvaluesWhensomethingunusualhappened,it’susefultosendbacksomeextrainformationaboutwhichunusual thinghashappenedsothatthehandlercantakesomeactionsdependingonthisinformation.

Atomictermerror isreplacedbyatermconstructorraiset

where 𝑡 istheextrainformationthatwewanttopasstotheexceptionhandler.

Page 39: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

Evaluation

Page 40: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

Evaluation

Page 41: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

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)

Page 42: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

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)

Page 43: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

Recapitulation:Errorhandling

Page 44: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

Recapitulation:Exceptionscarryingvalues

Page 45: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

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

controlbysettingahandlerduringevaluationofanexpressionthatmaybeinvokedbyraisinganexception.

– Exceptionsarevalue-carryinginthesensethatonemaypassavalueto theexceptionhandlerwhentheexceptionisraised.

– Exceptionvalueshaveasingletype,T_`a ,whichissharedbyallexceptionhandler.

Page 46: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

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.

Page 47: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

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"

Page 48: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

ExamplesinOCamlletfind_index p=

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

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

intryfind1L withFoundn->n;;

Page 49: Recap on References - GitHub Pages · 2020-04-19 · Aside: Syntax-directedness Note: this rule has a problem from the point of view of implementation: it is not syntax directed.

HW forchap14• 14.3.1