• No results found

Type Checking. Textbook: Types and Programming Languages Benjamin Pierce

N/A
N/A
Protected

Academic year: 2022

Share "Type Checking. Textbook: Types and Programming Languages Benjamin Pierce"

Copied!
52
0
0

Loading.... (view fulltext now)

Full text

(1)

Type Checking

Textbook: Types and Programming Languages

Benjamin Pierce

(2)

Plan

• Motivation (Chapter 1)

• Untyped Arithmetic Expressions (Chapter 3)

• Typed Arithmetic Expressions (Chapter 8)

• Untyped Lambda Calculus (Chapter 5)

• Typed Lambda Calculus (Chapter 9)

• Extensions

(3)

Challenges of Program Verification

• Specification of software behavior

• Reasoning about logical formulas

• The annotation burden

• The dynamic nature of software

• Automatically infer safe invariants from the code

• Concentrate on very simple properties with lightweight

annotations

(4)

June 4, 1996 The European Ariane5 rocket explodes 40s

into its maiden flight due to a software bug.

(5)

1997 Mars Rover Loses Contact

1999 Mars Climate Orbiter is Lost

1999 Mars polar Lander is lost

2004 Mar rover freezes

(6)

August 2005

As a Malaysia Airlines jetliner cruised from Perth, Australia, to Kuala Lumpur, Malaysia,

one evening last August, it suddenly took on a mind of its own and zoomed 3,000 feet upward.

The captain disconnected the autopilot and pointed the Boeing 777's nose down to avoid stalling, but was jerked into a steep dive.

He throttled back sharply on both engines, trying to slow the plane.

Instead, the jet raced into another climb.

The crew eventually regained control and manually flew their 177 passengers safely back to Australia.

Investigators quickly discovered the reason for the plane's roller-coaster ride 38,000 feet above the Indian Ocean.

A defective software program had provided incorrect data about the

aircraft's speed and acceleration, confusing flight computers. August 2005

(7)

Type Systems

• A tractable syntactic method for proving absence of certain program behaviors by classifying

phrases according to the kinds they compute

• Examples

– Whenever f is called, its argument must be integer – The arguments of f are not aliased

– The types of dimensions must match

– …

(8)

What is a type

• A denotation of set of values

– Int – Bool – …

• A set of legal operations

(9)

Static Type Checking

• Performed at compile-time

• Conservative (sound but incomplete)

– if <complex test> then 5 else <type error>

• Usually limited to simple properties

– Prevents runtime errors – Enforce modularity

– Protects user-defined abstractions – Allows tractable analysis

• Properties beyond scope (usually)

– Array out of bound – Division by zero – Non null reference

(10)

Error detection

• Early error detection

– Logical errors – Interface errors

– Dimension analysis

– Effectiveness also depends on the programmer

– Can be used for code maintenance

(11)

Abstraction

• Types define interface between different software components

• Enforces disciplined programming

• Ease software integration

(12)

Documentation

• Types are useful for reading programs

• Can be used by language tools

(13)

Language Safety

• A safe programming language protects its own abstraction

• Can be achieved by type safety

(14)

Statically vs. Dynamically Checked Languages Statically

Checked

Dynamically Checked

Safe ML, Haskel,

Java

Lisp, Scheme, Perl

Unsafe C, C++

(15)

Eiffel, 1989

Cook, W.R. (1989) - A Proposal for Making Eiffel Type-Safe, in Proceedings of ECOOP'89. S. Cook (ed.), pp. 57-70. Cambridge University Press.

Betrand Meyer, on unsoundness of Eiffel:

“Eiffel users universally report that they almost never run into such problems in real software development.”

(16)

Ten years later: Java

(17)

Efficiency

• Compilers can used types to optimize computations

• Pointer scope (Titanium)

• Region inference

(18)

Language Design

• Design the programming language with the type system

• But types incur some notational overhead

• Implicit vs. explicit types

– The annotation overhead

(19)

Untyped Arithmetic Expressions

Chapter 3

(20)

Untyped Arithmetic Expressions

t ::= terms

true constant true false constant false if t then t else t conditional 0 constant zero succ t successor pred t predecessor izzero t zero test

if false then 0 else 1 1

iszero (pred (succ 0)) true

(21)

Untyped Arithmetic Expressions

t ::= terms

true constant true false constant false if t then t else t conditional 0 constant zero succ t successor pred t predecessor izzero t zero test

succ true type error

if 0 then 0 else 0 type error

(22)

SOS for Booleans

t ::= terms

true constant true false constant false if t then t else t conditional v ::= values

true

false

if true then t1 else t2 → t1 (E-IFTRUE) if false then t1 else t2 → t2 (E-IFFALSE)

t1 → t’1

if t1 then t1 else t2 → if t’1 then t1 else t2

(E-IF)

t

1

→t’

1

(23)

SOS for Numbers

t ::= terms

0 constant zero succ t successor pred t predecessor iszero t zero test v ::= values

true true value false false value

nv numeric values

nv ::= numeric values 0 zero value

succ nv successor value

t1 → t’1

succ t1 → succ t’1 (E-SUCC) pred 0 → 0 (E-PREDZERO)

pred (succ nv1) → nv1 (E-PREDSUCC)

iszero 0 → true (E-ISZEROZERO) iszero (succ nv1) → false (E-ISZEROSUCC)

t

1

→t’

1

t1 → t’1

pred t1 →pred t’1 (E-PRED)

t1 → t’1

iszero t1 → iszero t’1(E-ISZERO)

(24)

Typed Arithmetic Expressions

Chapter 8

(25)

Stuck Computations

• The goal of the type system is to ensure at compile-time that no stuck ever occurs at runtime

• Safety (soundness)

– Progress: A well-typed term t never gets stuck

• Either it has value or there exists t’ such that t→ t’

– Preservation (subject reduction)

• If well type term takes a step in evaluation, then the

resulting term is also well typed

(26)

Type Rules for Boolean

T ::= types

Bool type of Boolean

t : T

true : Bool (T-TRUE)

false : Bool (T-FALSE)

t

1

: Bool t

2

: T t

3

: T

if t

1

then t

2

else t

3

: T (T-IF)

(27)

Type Rules for Numbers

T ::= types

Nat type of Natural numbers

t : T

0 : Nat (T-ZERO) t

1

: Nat

succ(t

1

) : Nat

T-SUCC

t

1

: Nat pred(t

1

) : Nat

T-PRED

t

1

: Nat

iszero(t

1

) : Bool

ISZERO

(28)

The Typing Relation

• Formally the typing relation is the smallest binary relation between terms and types

– in terms of inclusion

• A term t is typable (well typed) if there

exists some type T such that t : T

(29)

Inversion of the typing relation

• true : R ⇒ R = Bool

• false : R ⇒ R = Bool

• if t

1

then t

2

else t

3

: R ⇒ t

1

: Bool, t

2

: R, t

3

: R

• 0 : R ⇒ R = Nat

• succ t

1

: R ⇒ R = Nat and t

1

: Nat

• pred t

1

: R ⇒ R = Nat and t

1

: Nat

• iszero t1 : R ⇒ R = Bool and t

1

: Nat

(30)

Uniqueness of Types

• Each term t has at most one type

– If t is typable then

• its type is unique

• There is a unique type derivation tree for t

(31)

Safety

• Canonical Forms:

– If v is a value of type Boolean then v =true or v=false – If v is a value of type Nat then v belongs to nv

• Progress : If t is well defined then either t is a value or for some t’: t → t’

• Preservation: if t : T and t → t’ then t’ : T

nv ::= numeric values 0 zero value

succ nv successor value

(32)

Untyped Lambda Calculus

Chapter 5

(33)

Untyped Lambda Calculus

t ::= terms x variable

λ x. t abstraction

t t application

(λ x. x) (λ x. x) (λ x. x)

Syntactic Conventions

• Applications associates to left

• The body of abstraction extends as far as possible

(34)

Scope

• An occurrence of x is free in a term t if it is not in the body on an abstraction λx. t

– otherwise it is bound – λx is a binder

• FV: t → P(Var) is the set free variables of t

– FV(x) = {x}

– FV( λ x. t) = FV(t) – {x}

– FV (t

1

t

2

) = FV(t

1

) ∪FV(t

2

)

• Terms w/o free variables are combinators

– Example: λ x. x

(35)

Operational Semantics

(λ x. t

12

) t

2

→ [x ht

2

] t

12

(β-reduction)

[xhs]x =s

[x hs]y=y if y ≠ x

[x hs ] (λy. t1) = λy. [x hs ] t1 if y ≠ x and y∉FV(s) [x hs ] (t1 t2) = ([x hs ] t1) ([x hs ] t2)

(λ x. x) y → y

(λ x. x (λ x. x) ) (u r)→ u r (λ x. x)

(λ x (λy. x y)) (y z) → (λ x (λw. x w)) (y z) → λw. y z w

(36)

Operational Semantics

(λ x. t

12

) t

2

→ [x ht

2

] t

12

(β-reduction)

[xhs]x =s

[x hs]y=y if y ≠ x

[x hs ] (λy. t1) = λy. [x hs ] t1 if y ≠ x and y∉FV(s) [x hs ] (t1 t2) = ([x hs ] t1) ([x hs ] t2)

Evaluation orders:

•Full beta reduction

•Normal order

•Call by name

•Call by value

(λx. x)((λx. x)(λz. (λx. x) z))

(37)

Programming in the Lambda Calculus

• Turing complete

• Multiple arguments – λ(x, y). s = λx. λy.s

• Church Booleans – tru = λt. λf. t – fls =λt. λf. f

– test =λl. λm. λn. l m n – and = λb. λc. b c fls

• Pairs

– pair = λf. λb. λs. b f s – fst = λp. p tru

– snd = λp. p fls

• Church Numerals – c0 = λf. λz. z – c1 =λf. λz. s z – c2 = λf. λz. s (s z) – c3 = λf. λz. s (s (s z))

• Divergence

– omega= (λx. x x) (λx. x x)

(38)

Summary Lambda Calculus

• Powerful

• Useful to illustrate ideas

• But can be counterintuitive

• Usually extended with useful syntactic

sugars

(39)

Simple Typed Lambda Calculus

Chapter 9

(40)

Simple Typed Lambda Calculus

t ::= terms x variable

λ x: T. t abstraction

t t application

T::= types

T → T types of functions

(41)

SOS for Simple Typed Lambda Calculus

t ::= terms x variable

λ x: T. t abstraction

t t application v::= values

λ x: T. t abstraction values

T::= types

T → T types of functions

t1 → t2 t1 → t’1 t1 t2→ t’1 t2

(E-APP1)

t2 → t’2 t1 t2→ t1 t’2

(E-APP2)

(λ x: T

11

. t

12

) t

2

→ [x ht

2

] t

12

(E-APPABS)

(42)

t ::= terms x variable

λ x: T. t abstraction

T::= types

T → T types of functions

Γ::= context

∅ empty context

Γ, x : T term variable binding

Γd t : T

x : T ∈Γ

Γd x : T (T-VAR)

Γ, x : T1 d t2 : T2

Γd λx : T1. t2 : T2 : T1 → T2(T-ABS) Γ d t1 : T11 →T12

Γd t1 t2 : TΓ d t12 2 : T11 (T-APP)

Type Rules

(43)

t ::= terms x variable

λ x: T. t abstraction

t t application true constant true false constant false if t then t else t conditional T::= types

Bool Boolean type

T → T types of functions

Γ::= context

∅ empty context

Γ, x : T term variable binding

Γd t : T

x : T ∈Γ

Γd x : T (T-VAR)

Γ, x : T1 d t2 : T2

Γd λx : T1. t2 : T2 : T1 → T2(T-ABS) Γ d t1 : T11 →T12

Γd t1 t2 : TΓ d t12 2 : T11 (T-APP) Γ d true : Bool (T-TRUE)

Γ d false : Bool (T-FALSE) Γdt1 : Bool t2 : T t3 : T

Γd if t1 then t2 else t3 : T (T-IF)

(44)

Examples

• (λx:Bool. x ) true

• if true then (λx:Bool. x) else ( λx:Bool. x)

• if true then (λx:Bool. x) else ( λx:Bool.

λy:Bool. x)

(45)

The Typing Relation

• Formally the typing relation is the smallest ternary relation on contexts, terms and types

– in terms of inclusion

• A term t is typable in a given context Γ

(well typed) if there exists some type T such

that Γdt : T

(46)

Inversion of the typing relation

• Γ d x : R ⇒ x: R ∈Γ

• Γ d λx : T

1

. t2 : R ⇒ R = T

1

→ R

2

for some R

2

with Γd t

2

: R

2

• Γ d t

1

t

2

: R ⇒ there exists T

11

such that Γd t

1

: T

11

→ R and Γd t

2

: T

11

• Γ d true : R ⇒ R = Bool

• Γ d false : R ⇒ R = Bool

• Γ d if t

1

then t

2

else t

3

: R ⇒ Γ d t

1

: Bool,

Γ d t

2

: R, Γ d t

3

: R

(47)

Uniqueness of Types

• Each term t has at most one type in any given context

– If t is typable then

• its type is unique

• There is a unique type derivation tree for t

(48)

Safety

• Canonical Forms:

– If v is a value of type Boolean then v =true or v=false – If v is a value of type T1→ T2 then v =λx. T1. t2

• Progress :

If t is closed and well defined (dt : T for some T) then either t is a value of for some t’: t → t’

• Permutation: if Γ d t : T and < is a permutation of Γ then

< d t : T

• Weakening: if Γ d t : T and x ∉ dom(Γ) then Γ, x : S d t : T

• Preservation of types under substitution:

– If Γ, x : S d t : T and Γ d s : S then Γd [x hs] t : T

• Preservation: if Γd t : T and t → t’ then Γd t’ : T

(49)

Implicit vs. Explicit Types

• Do we have to spell out the type of every argument?

• Implicit type systems allow the

programmers to omit the types as long as the resulting type is unique

– Reduces the annotation burden

• A type inference algorithm infers a unique

type or issues an error

(50)

Other Issues

• The Curry-Howard Correspondence

• Erasure of typability

• Curry-Stlyle vs. Church style of languages

definition

(51)

Extensions

• Subtyping (Chapters 15-19)

– Most general type

• Recursive Types (Chapters 20, 21)

– NatList = <Nil: Unit, cons: {Nat, NatList}>

• Polymorphism (Chapters 22-28)

– length:list α → int

– Append: list α → α → list α

• Higher-order systems (Chapters 29-32)

(52)

Summary

• Type systems provide a useful for enforcing certain safety properties

– Can be combined with runtime systems and program analysis

• Interacts with the programmer

• A lot of interesting theory

References

Related documents

This requires a specific competence in project management techniques (both in case of packaged solutions and custom development) and a broad knowledge of ICT and Information

The following three measures were used to analyze the accuracy of the air quality forecasting models; the mean absolute error (MAE), the mean absolute percentage error (MAPE) and

psychosis onset in the ultra high risk for psychosis “prodromal” pop- ulation. Subjective symptoms of schizophrenia in research and the clinic: the basic symptom concept. The

Chapter V explored the relationship between the third tenet of CRT; CRT is committed to not only discussing race in relationship to society but to promoting social justice and

For covered services that are not recognized or reimbursed by Medicare, payment is based on the lesser of the Independence Blue Cross (IBC) applicable proprietary fee schedule or

The maximum total pressure in the combustion chamber is 1.17e+05, and the average total pressure in the combustion chamber is 1.10e+05, the average total pressure

McAfee VirusScan Enterprise 7.0.x McAfee VirusScan Enterprise 7.1.x McAfee VirusScan Enterprise 7.5.x McAfee VirusScan Enterprise 8.0.x McAfee VirusScan Enterprise

AdiFLAP: Pericardial adipose pedicle; AEMPS: Agencia Española de Medicamentos y Productos Sanitarios (Spanish); AGTP: Adipose graft transposition procedure; ATMP: Advanced