Presentation is loading. Please wait.

Presentation is loading. Please wait.

Catriel Beeri Pls/Winter 2004/5 types 1 Types Three chapters:  General introduction to types  A simple static monomorphic type system (with type checking.

Similar presentations


Presentation on theme: "Catriel Beeri Pls/Winter 2004/5 types 1 Types Three chapters:  General introduction to types  A simple static monomorphic type system (with type checking."— Presentation transcript:

1 Catriel Beeri Pls/Winter 2004/5 types 1 Types Three chapters:  General introduction to types  A simple static monomorphic type system (with type checking algorithm, correctness proofs)  Comments and discussion

2 Catriel Beeri Pls/Winter 2004/5 types 2 General introduction to types  Introduction  A classification of type disciplines  Static vs. dynamic type-checking

3 Catriel Beeri Pls/Winter 2004/5 types 3  Introduction 1 st try: Q: What is a type? A: Type – a set of values with common behavior For example: int, bool, list(int) Common behavior: same operations are applicable: +, -,.. for int; and, or, for bool; cons for list(int) How do we view an operation like <? Functions are also values, where are their types?

4 Catriel Beeri Pls/Winter 2004/5 types 4 2 nd try: A type system: A collection of sets closed under (finite) cross products Contains sets of functions (function spaces) with domain & range in the collection (~common behavior) Example: {int, bool, products of int/bool, functions from these to int or to bool }

5 Catriel Beeri Pls/Winter 2004/5 types 5 A type system: classification of the universe of values It has to be: sufficiently rich to describe values and their manipulation in programs For example: For functional languages, it has to be closed under formation of function space – to account for higher- order functions But not “too rich” E.g.: Should {0} be a type? (So 3/0 is a type error)

6 Catriel Beeri Pls/Winter 2004/5 types 6 Types – syntax vs. semantics It is useful to provide notations as names for types syntax semantics type expressions sets int the integers int  int unary functions on the integers int*int pairs of integers Algorithms manipulate the names, not the sets

7 Catriel Beeri Pls/Winter 2004/5 types 7 What are types used for in pl’s? 1.Storage organization & access code generation for composite values (optimization) 2.Detection/prevention of erroneous uses of values 3.Data organizations tailored for applications -- programmer-defined types 4.Abstraction and modularity: abstract data types, module facilities 1 -- implementation, 2 -- program correctness tool, 3, 4 – facilities for program design & programming in the large

8 Catriel Beeri Pls/Winter 2004/5 types 8 Types as a classification of values  (run-time) type error (= improper use of values) Each language construct has associated type errors, as per its intended semantics/use. Type-error is pl specific! (but, there is a lot of commonality)

9 Catriel Beeri Pls/Winter 2004/5 types 9 Type errors for FL: Application: Case of operand –operation: types & number of arguments not as specified –function: number of arguments not as specified (types for function arguments are not specified - discuss) – other: always a type error If: test value is not a boolean Tuple: none lambda -- ? let -- ?

10 Catriel Beeri Pls/Winter 2004/5 types 10 Examples: Wrong # or types of arguments for operations + (3,2,7), false + 3, 3 + `a`, Invalid operator 2 3 Wrong # of arguments for functions (define foo (lambda (x) ( … ))) (foo 3 5) Non-boolean test if 13 4 (2, 3)

11 Catriel Beeri Pls/Winter 2004/5 types 11 Many programming errors lead to type errors (estimates: 60-80% and more of logical errors) If type errors are not prevented nor handled, meaningless results are produced, then used A type discipline: the approach and algorithms used in a pl to prevent / detect, catch, handle, type errors It is common to use type system to mean both The collection of types The type discipline Garbage is produced, then it proliferates

12 Catriel Beeri Pls/Winter 2004/5 types 12  Classifications of type disciplines I. When are type errors considered? Untyped: types exist only in mind of programmer Machine/assembly language Dynamic typing: type errors are checked at run-time, before program steps (detection + handling) Scheme, scripting languages, smalltalk, …

13 Catriel Beeri Pls/Winter 2004/5 types 13 Static typing: checking at compile-time (prevention) Pascal, C, ML, C++, Java, ….. Some pl’s (typically OO) combine static typing with some dynamic checks – prevention & some detection + handling Java, … A sub-classification (of static systems): Monomorphic : (at most) one type to each value and expression (with some rare exceptions, e.g., =) Pascal, C Polymorphic: a value or expression can have many types ML, Java, C++ Most modern pl’s are polymorphic

14 Catriel Beeri Pls/Winter 2004/5 types 14 II. Which type errors are handled? Strong: all type errors are prevented/detected&handled dynamically or statically ML, Java, Weak: some errors are missed / not treated C (& and most other older pl’s) The two dimensions are independent: dynamic static strong v v weak v v

15 Catriel Beeri Pls/Winter 2004/5 types 15 Basic approach to dynamic type-checking : Tag values with type tags (called boxing) Test for type correctness before each step When run-time type error discovered, abort, or convert, or…. Cost: Extra storage Extra time for tests (note: tests for other errors are needed anyway)  Static vs. dynamic type-checking

16 Catriel Beeri Pls/Winter 2004/5 types 16 Static checking: reasoning about the program  A static type checker is a proof system (very different from a dynamic checker) Difficulty: the following problem is undecidable How does a static checker solve it? Will the execution of program P generate a run-time type error ?

17 Catriel Beeri Pls/Winter 2004/5 types 17 Static type-checking overcomes the difficulty by changing the pl : type annotations need (usually) to be provided for declared variables (not part of dynamically typed languages) this restricts the freedom of programmers and the generality of programs using constrained type systems : types need to be detailed rejecting some programs that will not generate run-time type errors : conservative checking

18 Catriel Beeri Pls/Winter 2004/5 types 18 We present examples to compare the two approaches Assumptions: –static: simple monomorphic (there is a huge variety of static type systems) –dynamic: no conversions (conversion makes sense as a way to handle a type error, after it is detected.)

19 Catriel Beeri Pls/Winter 2004/5 types 19 Dynamic :  if y’s value tag is int, can add 2 to y, result is int  Can multiply result by z, if its value is tagged int  If result obtained, can always be assigned to x (a variable has no type!)

20 Catriel Beeri Pls/Winter 2004/5 types 20 Static: Compiler ensures each evaluation is type-correct (w/o performing any evaluation) 1)Needs compile-time type environment :  (built-in knowledge)  y:cell(int), z:cell(int), x:cell(int) (or similar) (from type annotations in declarations of x, y, z) 2)Compiler infers type int for each sub-expression: 2, y, 2+y, z, (2+y)*z (do you see a type rule here?) 3)& assures that the type of x allows the assignment (why?)

21 Catriel Beeri Pls/Winter 2004/5 types 21  compiler associates types with values and with variables, expressions, cells (and ensures types of cells are preserved in assignments)

22 Catriel Beeri Pls/Winter 2004/5 types 22 if E1 then E2 else E3 Dynamic: –Evaluate E1, ensure its value is boolean –Then evaluate selected branch Static: To ensure type-correctness in all evaluations, must decide on a single type for the expression  both branches must have same static type (of course, the test must have type bool)  Conditionals are constrained to have branches of same type (conservative estimation of potential errors)

23 Catriel Beeri Pls/Winter 2004/5 types 23 Dynamic: no need to check; this is a value, no step Static: To type-check the body x+2, compiler needs a type for x in type environment  The parameter of the function needs a type annotation  A function type must include in type

24 Catriel Beeri Pls/Winter 2004/5 types 24 Dynamic: –The evaluation of the argument succeeds only if x has type float –To apply f (after argument has been computed), ensure it is bound to value with type unary function –After the application, if no error occurred during evaluation, check the result has tag int, ….

25 Catriel Beeri Pls/Winter 2004/5 types 25 Static: type environment must specify for x: its type is float f: –Its value (whatever that may be) is a unary function –It accepts a float argument –It returns an int (provided argument is of type float) (why is that needed?)  The type of f in type environment: float  int  Function types must be detailed: in-type  out-type (arity included)

26 Catriel Beeri Pls/Winter 2004/5 types 26 Dynamic: –To apply hd ensure that ls is bound to a list value (which is not empty) –For the +, ensure the element is an int Static: must declare a type in  out for hd, hence: –Type environment must include that ls is of type list(int), so hd has type list(int)  int –Assignment to ls, updates to its value, must respect this constraint Same for arrays, …  Most collection types must be homogeneous

27 Catriel Beeri Pls/Winter 2004/5 types 27 Summary: A dynamic type-checker is Simple -- check before each step Liberal – allows functions such lambda x. x ( a general identity function) append (appends two lists with any types of elements) Requires: input types for operations, but no output types Neither input nor output types for functions, just arity

28 Catriel Beeri Pls/Winter 2004/5 types 28 A static type checker is a proof system A monomorphic type cheker Requires type annotations for declared variables Requires detailed types – in  out for operations, functions –list(int),rather than just list  Restricts generality of programs: lambda x:int. x (identity for integers) append : list(int)*list(int  list(int) (append for specific list type)

29 Catriel Beeri Pls/Winter 2004/5 types 29 Associates types with additional entities (not just literals) cells, expressions, statements, … Makes conservative judgments about potential errors  some type-correct programs may be rejected

30 Catriel Beeri Pls/Winter 2004/5 types 30 About cells: These are values, and a type system induces a classification: cell(int), cell(float), … But, the operations read, write, make-ref are independent of type of contents (polymorphic) Dynamic type systems allow the type of a cell to change dynamically Static (monomorphic) systems force a unique type for a cell throughout computation

31 Catriel Beeri Pls/Winter 2004/5 types 31 About FL implementation If implemented w/o type tags & type error handling, it is an un-typed pl – unacceptable for high-level pl’s The syntax does not include type annotations for variables  it is implemented as a dynamically-typed pl: with type tags & dynamic error handling Types of values: int, bool, op, function, tuple These are discovered by lexical analysis and provided in the abstract syntax. (Note: can also implement as statically typed, with type inference)

32 Catriel Beeri Pls/Winter 2004/5 types 32 TFL a simple monomorphic statically-typed language (a statically-typed version of FL)  The type language  The typed language TFL  The type rules  Some proof trees  Some properties  A type checking algorithm  On the correctness of the rules

33 Catriel Beeri Pls/Winter 2004/5 types 33 Components (of a static type system): An un-typed base language - we take FL A type language (its expressions denote the types) The typed language TFL – the base pl + type annotations for declared variables Type rules, to specify the well-typed programs A type-checking algorithm Correctness proofs for rules, algorithm טיפוסים בהכרזות משתנים

34 Catriel Beeri Pls/Winter 2004/5 types 34  The type language are type constructors As usual, we use the abstract syntax of type expressions

35 Catriel Beeri Pls/Winter 2004/5 types 35 Conventions for concrete syntax of types  is right associative has higher priority than  Compare: right associativity of  left associativity of application What type for f in f x y ?

36 Catriel Beeri Pls/Winter 2004/5 types 36 Assumtions: types for literals (numbers, operations), are given, represented by a function typeOf: typeOf(0) = int, typeOf(1) = int, … typeOf(n)=int typeOf(true) = bool, typeOf(+) = typeOf(<) = (typeOf(O) is an arrow type, for each ) builtIn returns ER when types of operation & operand are incompatible as per typeOf *(this will be generalized later) *

37 Catriel Beeri Pls/Winter 2004/5 types 37 We write for E has type Examples: This notation is used in: Type annotations for declared variables Formulas in type rules

38 Catriel Beeri Pls/Winter 2004/5 types 38  The typed language, TFL Add type annotations to variables declared in lambda Examples:

39 Catriel Beeri Pls/Winter 2004/5 types 39 But, are types really needed for let declared variables? let x = 4 in 2*x --- the type int for x is known from the type of 4 If we decide the types in a let need to be declared, this serves only for a double check (but, types are needed in declarations w/o bodies, a-la OCAML) Need a new grammar for TFL!

40 Catriel Beeri Pls/Winter 2004/5 types 40 Terminology: Syntactically correct : pre-expressions Those that pass type-checking: expressions or (more commonly) well-typed programs (These are the syntax and type correct programs)

41 Catriel Beeri Pls/Winter 2004/5 types 41 On evaluation of well-typed programs: The programmer writes programs in TFL After type-checking, type annotations are erased erase: TFL  FL The FL program is executed; type tags are not needed - no type errors can occur (provided we apply a sound type-checking algorithm)

42 Catriel Beeri Pls/Winter 2004/5 types 42  The type rules The type of an expression depends on the types declared for the variables in it  Need type environment (or assignment): (compile-time) a finite mapping from variables to types For example, the body of needs to be checked in

43 Catriel Beeri Pls/Winter 2004/5 types 43 Notations: Environments: combine, with priority to G Convention: is left associative

44 Catriel Beeri Pls/Winter 2004/5 types 44 The basic formula in the rules: a type judgement Read: under the type environment H, the expression E has type H represents the knowledge about the types of declared variables, whose scope contains E We write when H is empty now, finally, to the rules! שיפוט טיפוס

45 Catriel Beeri Pls/Winter 2004/5 types 45 (This gives types to all TEL)

46 Catriel Beeri Pls/Winter 2004/5 types 46 The only rules (so far) with an environment change They reflect static scoping (H in (lambda) may contain a type for x!) (This ends the rules for TFL) The rules (applic), ( ) are also called  elimination,  introduction Why?

47 Catriel Beeri Pls/Winter 2004/5 types 47  Some proof trees In TFL, a function is a triple (domain, range, mapping) There are many identity functions, one per type

48 Catriel Beeri Pls/Winter 2004/5 types 48 Complete the tree

49 Catriel Beeri Pls/Winter 2004/5 types 49 Claim: The following is a derived rule schema What is the meaning of derived rule here? With this, the previous tree could be simplified. Should we?

50 Catriel Beeri Pls/Winter 2004/5 types 50 Additional derived rules are possible, e.g:

51 Catriel Beeri Pls/Winter 2004/5 types 51 One more example (use derived rule):

52 Catriel Beeri Pls/Winter 2004/5 types 52  Some properties Terminology & notation: E is well-typed if it has a (provable) typing -- WT(E) Typ(H,E) – E has a type under H The pair H, E is a goal, the type is the solution (why not just E as goal?) A rule is applicable to a goal H,E if ………

53 Catriel Beeri Pls/Winter 2004/5 types 53 Claim:[Unique applicability] Each goal H, E has at most one applicable rule, which is independent of H Hence, if E has a type under H, then the goal H, E has a unique applicable rule Proof: look at the rules Most of the following claims are a consequence

54 Catriel Beeri Pls/Winter 2004/5 types 54 Inversion: Atomic: Above are assumptions about typeOf + unique applicability Corollary: An atomic expression has at most one : type, proof tree for a typing under H An atomic value has a unique …..

55 Catriel Beeri Pls/Winter 2004/5 types 55 The above provide inversions for most rules, rest is for you Composite:

56 Catriel Beeri Pls/Winter 2004/5 types 56 Canonical forms for values:

57 Catriel Beeri Pls/Winter 2004/5 types 57 Claim [Uniqueness of typing] For given E, H there exists at most one proof tree for a typing of E under H, hence at most one type s.t. Proof: Induction on structure of E Basis: see inversion Induction: combine unique applicability & inversion The type system is monomorphic: one type for a well-typed expression (under H) Q: Does the type depend on H?

58 Catriel Beeri Pls/Winter 2004/5 types 58 Claim: WT(E)  the proof tree for each typing of E is isomorphic to the expression tree of E Proof: in each type rule, the goal premises are the direct sub-expressions of E (+ induction ) Hence, proving properties by induction on Type rules Typing proof tree Expression tree (= structure) Are the same

59 Catriel Beeri Pls/Winter 2004/5 types 59 Assume Typ(H,E) Claim: if E is not a lambda/let then for each direct sub-expression E’, Typ(H,E’) Claim: if E is then Similar claim for let – for you

60 Catriel Beeri Pls/Winter 2004/5 types 60 Corollary: Let F be a sub-expression of E, let x 1,…, x k be the declarations on the path from E’s root to F’s root that have F in scope, and let be their types Then F

61 Catriel Beeri Pls/Winter 2004/5 types 61 Still assuming Typ(H,E): Corollary: if x is free in E, then That is, E has a type under H only if H contains assumptions for all free variables of E Both proved by induction of proof trees/type rules

62 Catriel Beeri Pls/Winter 2004/5 types 62 The dependence of the type of an expression on the environment is precisely via the type assignments of its free variables  For a closed expression, the environment is irrelevant!

63 Catriel Beeri Pls/Winter 2004/5 types 63 Conclusions for type-checking: For a full program type-checking starts with the empty type environment (no other reasonable choice)*  If program contains a free variable, type-check fails For a closed program: There is at most one type Each sub-expression is associated with a unique type environment (~declarations that have it in scope) at most one type (under that environment) * (if a program imports modules, the type environment is not empty)


Download ppt "Catriel Beeri Pls/Winter 2004/5 types 1 Types Three chapters:  General introduction to types  A simple static monomorphic type system (with type checking."

Similar presentations


Ads by Google