CS5205Extended Type System1 CS5205: Foundation in Programming Languages Lecture 7 : Extended Type...
-
Upload
ralph-walsh -
Category
Documents
-
view
217 -
download
0
description
Transcript of CS5205Extended Type System1 CS5205: Foundation in Programming Languages Lecture 7 : Extended Type...
CS5205 Extended Type System 1
CS5205: Foundation in Programming Languages
Lecture 7 : Extended Type System
• Base & Unit Types• Sequencing• Ascription• Let bindings• Pairs, Tuples, Records• Sums, variants• Recursion • References• Exceptions
CS5205 Extended Type System 2
Pure Simply Typed Lambda CalculusPure Simply Typed Lambda Calculus
• t ::= termsx variable x:T.t abstractiont t application
• v ::= value x :T.t abstraction value
• T ::= typesT ! T type of functions
• ::= contexts empty context
, x:T type variable binding
CS5205 Extended Type System 3
Call-by-Value SemanticsCall-by-Value Semantics
( x.t) v ! [x v] t (E-AppAbs)
t1 ! t‘1
t1 t2 ! t’1 t2
(E-App1)
t2 ! t‘2
v1 t2 ! v1 t’2
(E-App2)
CS5205 Extended Type System 4
TypingTyping
x:T 2 ` x : T
` t1 : T1 ! T2 ` t2 : T1
` t1 t2 : T2
(T-Var)
(T-App)
, x:T1 ` t2 : T2
` x:T1.t2 : T1 ! T2 (T-Abs)
CS5205 Extended Type System 5
Where are the Base Types?Where are the Base Types?
• T ::= typesT ! T type of functions
Extend with uninterpreted base types, e.g.• T ::= types
T ! T type of functionsA base type 1B base type 2C base type 3 :
CS5205 Extended Type System 6
Examples Examples
x:A. x
f:A! B. x:A. f(x)
f:A! A. x:A. f(x)
f:B! B. x:B. f(f(x))
Base types are Bool, Nat, etc.The above types are monomorphic rather than polymorphic. For polymorphic types, we need to use type variables, denoted by say , , etc.
CS5205 Extended Type System 7
Unit TypeUnit Type
New Syntax:t ::= … terms
unit constant unitv ::= … values
unit constant unitT ::= … types
Unit unit typeNote that Unit type has only one possible value.
New Evaluation Rules: None
New Typing Rules : ` unit : Unit T-Unit
CS5205 Extended Type System 8
Sequencing : Basic Idea Sequencing : Basic Idea
Syntax : e1; e2
Evaluate an expression (to achieve some side-effect, such as printing), ignore its result and then evaluate another expression.
Examples:
(print x); x+1
(printcurrenttime); compute; (printcurrenttime)
CS5205 Extended Type System 9
Lambda Calculus with SequencingLambda Calculus with SequencingNew Syntax• t ::= … terms
t ; t sequence
unit ; t ! t (E-SeqUnit)
t1 ; t2 ! t‘1 ; t2
t1 ! t‘1 (E-Seq)
New Evaluation Rules:
CS5205 Extended Type System 10
Sequencing (cont) Sequencing (cont)
` t1 : Unit1 ` t2 : T2
` t1 ; t2 : T2
(T-Seq)
New Typing Rule:
CS5205 Extended Type System 11
Sequencing (Second Version)Sequencing (Second Version)
• Treat t1;t2 as an abbreviation for (x:Unit. t2) t1 .
• Then the evaluation and typing rules for abstraction and application will take care of sequencing!
• Such shortcuts are called derived forms (or syntactic sugar) and are heavily used in programming language definition.
CS5205 Extended Type System 12
Equivalence of Sequencing ExtensionEquivalence of Sequencing Extension
Let E be the simply typed lambda calculus with the Unit type and the sequencing construct.
Let I be the simply-typed lambda calculus with Unit only.
Let e 2 E ! I be the elaboration function that translates from E To I.
Then, we have for each term t:
• t !E t’ iff e(t) !I e(t’)
`E t:T iff `I e(t):T
CS5205 Extended Type System 13
Ascription : Motivation Ascription : Motivation
Sometimes, we want to say explicitly that a term has a certain type.
Reasons:• as comments for online documentation• for debugging type errors• control printing of types (together with type
syntax)• casting (as in Java)• resolve ambiguity (of more complex typing)
CS5205 Extended Type System 14
Ascription : Syntax Ascription : Syntax
New Syntax• t ::= … terms
t as T ascription
Example:
(f (g (h x y z))) as Bool
CS5205 Extended Type System 15
Ascription (cont)Ascription (cont)New Evaluation Rules:
New Typing Rules:
v as T ! v (E-Ascribe1)
t ! t‘
t as T ! t‘ as T (E- Ascribe2)
` t : T ` t as T : T
(T-Ascribe)
CS5205 Extended Type System 16
Let Bindings : Motivation Let Bindings : Motivation
• Let expression allow us to give a name to the result of an expression for later use and reuse.
• Examples:
let pi=<long computation> in …pi..pi..pi….
let square = x:Nat. x*x in ….(square 2)..(square 4)…
CS5205 Extended Type System 17
Lambda Calculus with Let BindingLambda Calculus with Let BindingNew Syntax
t ::= … termslet x=t in t let binding
let x=v in t2! [x v] t2
t1 ! t‘1
let x=t1 in t2 ! let x=t‘1 in t2
(E- Let2)
New Evaluation Rules
(E-Let1)
CS5205 Extended Type System 18
Let Binding (cont) Let Binding (cont)
` t1 : T1 , x:T1 ` t2 : T2
` let x=t1 in t2 : T2
(T-Let)
New Typing Rule:
CS5205 Extended Type System 19
Let Bindings as Derived FormLet Bindings as Derived Form
We can consider let expressions as derived form:
In untyped setting:let x=t1 in t2 abbreviates to ( x. t2) t1
In a typed setting:let x=t1 in t2 abbreviates to ( x:?. t2) t1
How to get type declaration for the formal parameter? Answer : Type inference (see next lecture).
CS5205 Extended Type System 20
Pairs : Motivation Pairs : Motivation
Pairs provide the simplest kind of data structures.
Examples: (9, 81)
x : Nat. (x, x*x)
CS5205 Extended Type System 21
Pairs : SyntaxPairs : Syntax
• t ::= … terms(t, t) variablet.1 first projectiont.2 second projection
• v ::= … value(v, v) pair value
• T ::= … typesT £ T product type
CS5205 Extended Type System 22
Pairs : Evaluation RulesPairs : Evaluation Rules
(v1, v2).1 ! v1
t ! t‘
t.1 ! t‘.1(E-Proj1)
(E-PairBeta1)
(v1, v2).2 ! v2 (E-PairBeta2)
t ! t‘
t.2 ! t‘.2(E-Proj2)
CS5205 Extended Type System 23
Pairs : Evaluation Rules (cont)Pairs : Evaluation Rules (cont)
t ! t‘
(v, t) ! (v, t‘)(E-Pair2)
t1 ! t‘1
(t1, t2) ! (t‘1, t2)
(E-Pair1)
CS5205 Extended Type System 24
Pairs : Typing RulesPairs : Typing Rules
` t1 : T1 ` t2 : T2
` (t1,t2) : T1 £ T2 (T-Pair)
` t : T1 £ T2
` t.1 : T1 (T-Proj1)
` t : T1 £ T2
` t.2 : T2 (T-Proj2)
CS5205 Extended Type System 25
Tuples Tuples
Tuples are a straightforward generalization of pairs, where n terms are combined in a tuple expression.
Example:(1, true, unit) : (Nat, Bool, Unit)(1,(true, 0)) : (Nat, (Bool, Nat))( ) : ( )
Note that n may be 0. Then the only value is ( ) with type ( ). Such a type is isomorphic to Unit.
CS5205 Extended Type System 26
Records Records
Sometimes it is better to have components labeled more meaningfully instead of via numbers 1..n, as in tuples
Tuples with labels are called records.
Example:{partno=5524, cost=30.27, instock =false}
has type {partno:Nat, cost:Float, instock:Bool}instead of:
(5524,30.27,false) : (Nat, Float, Bool)
CS5205 Extended Type System 27
Tuples as Records Tuples as Records
We can treat tuples as an abbreviation for records whose fields are numbers from 1 to n.
Example:
(1, true, unit) is abbreviation for {1=1, 2=true, 3=unit}
CS5205 Extended Type System 28
Pattern-Matching : Motivation Pattern-Matching : Motivation
It is often convenient to access some or all components of a record simultaneously as in:
let {partno=p, cost=c, instock=i} = accessdb key1 key2
in …p…c…i…
let construct can be extended with pattern-matching. Usually case construct also used for sum/variant type to be described next.
CS5205 Extended Type System 29
Pattern-Matching Pattern-Matching
New syntactic Form:
p ::= x variable pattern{li=pi}i 2 1..n record pattern
t ::= … termslet p=t in t pattern binding
CS5205 Extended Type System 30
Pattern-Matching (cont) Pattern-Matching (cont) Matching Rules :
match(x,v) = [x v]
for each i match(pi, vi) = i
match({li, pi}i 2 1..n, {li, vi}i 2 1..n)
= 1 ± … ± n
(M-Rcd)
(M-Var)
Evaluation Rules :
t1 ! t‘1
let p=t1 in t2! let p=t1‘ in t2
(E-Let)
let p=v in t ! match(p,v) t (E-LetV)
CS5205 Extended Type System 31
Sums : Motivation Sums : Motivation
Often, like to handle values of different structures with the same function. Examples:
PhysicalAddr={firstlast:String, add:String}VirtualAddr={name:String, email:String}
A sum type can then be written like this:
Addr = PhysicalAddr + VirtualAddr
CS5205 Extended Type System 32
Sums : Motivation Sums : Motivation
Given a sum type; e.g.
K = Nat + Bool
Need to use tags inl and inr to indicate that a value is a particular member of the sum type; e.g.
inl 5 : K but not inr 5 : K nor 5 : K inr true : K
CS5205 Extended Type System 33
Sums : Motivation Sums : Motivation
Given the address type:
Addr = PhysicalAddr + VirtualAddr
We can use case construct to analyse the particular value of sum type:
getName = a : Addr. case a ofinl x => a.firstlastinr y => y.name
CS5205 Extended Type System 34
Problem : Uniqueness of Types Problem : Uniqueness of Types
Given the address type:
PhysicalAddr={firstlast:String, add:String}VirtualAddr={name:String, email:String}PagingUser={name:String, pager:String}Addr = PhysicalAddr + VirtualAddrUserCoord = PagerUser + VirtualAddr
What is the type of :
inr {name : “chin”, email=“[email protected]”} ?
CS5205 Extended Type System 35
Resolving Ambiguous Types Resolving Ambiguous Types
• Analyse the program to find out what type should be. (Type inference)
• Given a type that includes all possible sum types. (Subtyping)
• Force programmer to explicitly declare the type using ascription.
CS5205 Extended Type System 36
Sums : SyntaxSums : Syntax
• t ::= … termsinl t as T tagging (left)inr t as T tagging (right)case t of {pi => ti} pattern matching
• v ::= … valueinl v as T tagged value (left)inr v as T tagged value (right)
• T ::= … typesT + T sum type
CS5205 Extended Type System 37
Sums : Evaluation RulesSums : Evaluation Rules
case (inl v as T) of {inl x1 ) t1 | inr x2 ) t2}
! [x1 v] t1
(E-CaseInl)
case (inr v as T) of {inl x1 ) t1 | inr x2 ) t2}
! [x2 v] t2
(E-CaseInr)
t ! t‘
case t of {p ) t} ! case t‘ of {p ) t} (E-Case)
CS5205 Extended Type System 38
Sums : Evaluation RulesSums : Evaluation Rules
t ! t‘
inl t as T ! inl t‘ as T (E-Inl)
t ! t‘
inr t as T ! inl t‘ as T (E-Inr)
CS5205 Extended Type System 39
Sums : Typing RulesSums : Typing Rules
` t1 : T1
` inl t1 as T1 £ T2 : T1 £ T2 (T-Inl)
` t2 : T2
` inr t2 as T1 £ T2 : T1 £ T2 (T-Inr)
CS5205 Extended Type System 40
Variants : Labeled Sums Variants : Labeled Sums
Instead of inl and inr, we may like to use nicer labels, just as in records. This is what variants do.
For types, instead of: T1 + T we write: <l1:T1 + l2:T2>
For terms, instead of: inl r as T1 + T we write: <l1= t> as <l1:T1 + l2:T2>
CS5205 Extended Type System 41
Variants : Example Variants : Example
An example using variant type:Addr =<physical : PhysicalAddr, virtual : VirtualAddr>
A variant value:a = <physical=pa> as Addr
Function over variant value:getName = a : Addr.
case a of<physical=x> ) x.firstlast<virtual=y> ) y.name
CS5205 Extended Type System 42
Application : Options Application : Options
Option type denotes a maybe value:OptionNat =<none : Unit, some : Nat>Table = Nat ! OptionNat
Operations on Table:emptyTable = n : Nat. <none=unit> as OptionNat
extendTable = t:Table. m:Nat v: Nat. n:Nat.
if equal n m then <some=v> as OptionNatelse t n
CS5205 Extended Type System 43
Application : Enumeration Application : Enumeration
Enumeration are variants that only make use of their labels. Each possible value is unit.
Weekday =<monday:Unit, tuesday:Unit, wednesday:Unit, thursday:Unit,
friday:Unit >
CS5205 Extended Type System 44
Application : Single-Field Variants Application : Single-Field Variants
Labels can be convenient to add more information on how the value is used.
Example, currency denominations (or units):
DollarAmount =<dollars:Float>
EuroAmount =<euros:Float>
CS5205 Extended Type System 45
Recursion : Motivation Recursion : Motivation
Recall the fix-point combinator:
fix = f. ( x. f ( y. x x y)) ( x. f ( y. x x y))
Unfortunately, it is not valid (well-typed) in simply typed lambda calculus.
Solution : provide this as a language primitive that is hardwired.
CS5205 Extended Type System 46
Recursion : Syntax & Evaluation RulesRecursion : Syntax & Evaluation Rules
New Syntax• t ::= … terms
fix t fixed point operator
New Evaluation
t ! t‘
fix t ! fix t’ (E-Fix)
fix ( x : T. t) ! [x fix ( x : T. t)] t (E-FixBeta)
CS5205 Extended Type System 47
Recursion : Typing RulesRecursion : Typing Rules
` t : T ! T
` fix t : T (T-Fix)
Can you guess the inherent type of fix?
CS5205 Extended Type System 48
References : Motivation References : Motivation
Many languages do not syntactically distinguish between references (pointers) from their values.
In C, we write: x = x+1
For typing, it is useful to make this distinction explicit; since operationally pointers and values are different.
CS5205 Extended Type System 49
References : Motivation References : Motivation
Introduce the syntax (ref t), which returns a reference to the result of evaluating t. The type of ref t is Ref T, if T is the type of t.
Remember that we have many type constructors already:
Nat £ float {partno:Nat,cost:float}Unit+Nat <none:Unit,some:Nat>
CS5205 Extended Type System 50
Typing : First AttemptTyping : First Attempt ` t : T
` ref t : Ref T (T-Ref)
` t : Ref T ` ! t : T
(T-Deref)
` t1 : Ref T1 ` t2 : T1
` t1 := t2 : Unit(T-Assign)
CS5205 Extended Type System 51
References : Motivation References : Motivation
What should be the value of a reference?
What should the assignment “do”?
How can we capture the difference of evaluating a dereferencing depending on the value of the reference?
How do we capture side-effects of assignment?
CS5205 Extended Type System 52
References : Motivation References : Motivation
Answer:
Introduce locations corresponding to references.
Introduce stores that map references to values.
Extend evaluation relation to work on stores.
CS5205 Extended Type System 53
References : Evaluation References : Evaluation
Instead of:
t ! t’
we now write:
t | !t’ | ’
where ’ denotes the changed store.
CS5205 Extended Type System 54
Evaluation of Application Evaluation of Application
t1 | !t’1 | ’
t1 t2 | ! t’1 t2 | ’ (E-Appl1)
( x : T.t) v | ! [x v] t | (E-AppAbs)
t2 | !t’2 | ’
v t2 | ! v t’2 | ’ (E-Appl2)
CS5205 Extended Type System 55
ValuesValues
The result of evaluating a ref expression is a location
• v ::= value x:T.t abstraction valueunit unit valuel store location
CS5205 Extended Type System 56
TermsTerms
Below is the syntax for terms. • t ::= terms
x variable x:T.t abstraction valueunit constant unitt t applicationref t reference creation! t dereferencet := t assignmentl store location
CS5205 Extended Type System 57
Evaluation of Deferencing Evaluation of Deferencing
t | !t’ | ’! t | ! ! t’ | ’
(E-Appl1)
lv ! l | ! v |
(E-DeRefLoc)
CS5205 Extended Type System 58
Evaluation of Assignment Evaluation of Assignment
t1 | !t’1 | ’
t1 := t2 | ! t’1 := t2 | ’ (E-Assign1)
(E-Assign)
t2 | !t’2 | ’
l := t2 | ! l := t’2 | ’ (E-Assign2)
l:=v2 | !unit | l v]
CS5205 Extended Type System 59
Evaluation of References Evaluation of References
t | !t’ | ’ref t | ! ref t’ | ’
(E-Ref)
l dom()
ref v | ! l | , (l v)(E-RefV)
CS5205 Extended Type System 60
Towards a Typing for Locations Towards a Typing for Locations
` (l) : T ` l : Ref T (T-Ref)
But where does come from? How about adding store to the typing relation
| ` (l) : T | ` l : Ref T (T-Ref)
..but..
CS5205 Extended Type System 61
Problem Problem
No finite type derivation for l with respect to the store.
(l1 x:Nat. (! l2)x, l2 x:Nat. (! l1)x)
CS5205 Extended Type System 62
Idea Idea
Instead of adding stores as argument to the typingrelation, we add store typings, which are mappingsfrom locations to types. Example for a store typing:
= (l1 Nat ! Nat, l2 Nat! Nat, l3 Unit)
CS5205 Extended Type System 63
Typing : Final Typing : Final
| ` t : T | ` ref t : Ref T
(T-Ref)
( l ) = T | ` l : Ref T
(T-Loc)
CS5205 Extended Type System 64
Typing : Final Typing : Final
| ` t : Ref T | ` ! t : T
(T-Deref)
| ` t1 : Ref T1 | ` t2 : T1
| ` t1 := t2 : Unit(T-Assign)
CS5205 Extended Type System 65
Safety = Preservation + Progress Safety = Preservation + Progress
Preservation, first attempt:
If | ` t : T and t | !t’ | ’, then | ` t’ : T
But the store and store typing may not agree!
| (l Unit ! Unit) ` ! l : Unit ! Unit ! l | (l unit) !unit | (l unit)
| ` unit : Unit for any ,
CS5205 Extended Type System 66
Well-Typed Stores Well-Typed Stores
A store is well-typed with respect to a typing context and a store typing , written as:
| `
if dom()=dom() and | ` ( l ) : ( l ) for every l 2 dom()
CS5205 Extended Type System 67
Preservation : Second Attempt Preservation : Second Attempt
If: | ` t : T and t | !t’ | ’and | `
then | ` t’ : T
But : rule (E-RefV) extends the store:
l dom()
ref v | ! l | , ( l v)(E-RefV)
CS5205 Extended Type System 68
Preservation : Final VersionPreservation : Final Version
If: | ` t : T and t | !t’ | ’and | `
then for some ’ , | ’ ` t’ : T and | ’ ` ’
CS5205 Extended Type System 69
Exceptions : MotivationExceptions : Motivation
During execution, situations may occur that requires drastic measures such as resetting the state of program or even aborting the program.
• division by zero• arithmetic overflow• array index out of bounds• …
CS5205 Extended Type System 70
ErrorsErrors
We can denote error explicitly: t ::= … terms
error run-time error
(E-AppErr1)error t ! error
(E-AppErr2)v error ! error
` error : T (T-Error)
for any T
Evaluation Rules:
Typing Rule:
CS5205 Extended Type System 71
Examples Examples
( x:Nat. 0) error
(fix ( x:Nat. x)) error
( x:Bool. x) error
( x:Bool. x) (error true)
CS5205 Extended Type System 72
Error Handling : Motivation Error Handling : Motivation
In implementation, the evaluation of error will forcethe runtime stack to be cleared so that programreleases its computational resources.
Idea of error handling : Install a marker on the stack. During clearing of stack frames, the markers can be checked and when the right one is found, execution can resume normally.
CS5205 Extended Type System 73
Error HandlingError Handling
display try (..complicated calculation..) with “cannot compute the result”
CS5205 Extended Type System 74
Error HandlingError HandlingProvide a try-with (similar to try-catch of Java) mechanism. t ::= … terms
try t with t trap errors
(E-TryV)try v with t ! v
(E-TryError)try error with t ! t
New Evaluation Rules:
t1!t’1
try t1 with t2! try t’1 with t2
(E-Try)
CS5205 Extended Type System 75
Typing Error HandlingTyping Error Handling
New Typing Rule:
` t1 : T ` t2 : T ` try t1 with t2 : T
(E-Try)
CS5205 Extended Type System 76
Exception Carrying Values: Motivation Exception Carrying Values: Motivation
Typically, we would like to know what kind of exceptional situation has occurred in order to take appropriate action.
Idea : Instead of errors, raise exception value that can be examined after trapping. This technique is called exception handling.
CS5205 Extended Type System 77
Exception Carrying ValueException Carrying ValueNew syntax:
t ::= … termsraise t raise exceptiontry t with t handle exception
CS5205 Extended Type System 78
Exception Carrying ValuesException Carrying ValuesNew Evaluation Rules:
t!t’raise t ! raise t’ (E-Raise)
(E-AppRaise1)(raise v) t ! raise v
v1 (raise v2) ! (raise v2) (E-AppRaise1)
(raise (raise v)) ! (raise v) (E-AppRaiseRaise)
CS5205 Extended Type System 79
Exception Carrying ValuesException Carrying Values
(E-TryV)try v with t ! v
(E-TryError)try (raise v) with t ! t v
New Evaluation Rules:
t1!t’1
try t1 with t2! try t’1 with t2
(E-Try)
CS5205 Extended Type System 80
Exception Carrying ValuesException Carrying ValuesNew Typing Rules:
` t1 : T ` Texn ! T ` try t1 with t2 : T
(E-Try)
` t : Texn ` raise t : T
(E-Raise)
CS5205 Extended Type System 81
What Values can serve as Exceptions? What Values can serve as Exceptions?
• Texn is Nat as in return codes for Unix system calls.
• Texn is String for convenience in printing out messages.
• Texn is a certain fixed variant type, such as:
< divideByZero : Unit, overflow : Unit,
fileNotFound : String >
• …
CS5205 Extended Type System 82
O’Caml Exceptions O’Caml Exceptions
• Exceptions are a special extensible variant type.
• Syntax (exception l of T) does variant extension.
• Syntax (raise l(t)) is short for:raise (<l=t>) as Texn
• Syntax of try is sugar for try and case.