Download Types and Type Inference in Programming Languages - Prof. Zhendong Su and more Assignments Programming Languages in PDF only on Docsity!
Prof. Su ECS 140A Lecture 5-6 1
Programming Languages
ECS 140A
13:40-15:00 Tu/Th
55 Roessler
Prof. Su ECS 140A Lecture 5-6 2
Announcements
- HW2 due Thursday, April 23rd
Prof. Su ECS 140A Lecture 5-6 3
Outline
- General discussion of types
- What is a type?
- Compile-time vs run-time checking
- Conservative program analysis
- Type inference
- Good example of static analysis algorithm
- Will study algorithm and examples
- Polymorphism
- Polymorphism vs. overloading
- Uniform vs. non-uniform implementation of polymorphism
Prof. Su ECS 140A Lecture 5-6 4
Type
A type is a collection of computable values
that share some structural property
- Examples
- Int, String
- Int x Int
- Int + Bool
- Int -> Bool
- (Int -> Int) -> Bool
- Int * (or โInt refโ)
- โNon-examplesโ
- {3, true, \x.x}
- Even integers
- {f:int -> int | if x> then f(x) > x*(x+1)}
Distinction between sets that are types and sets that are not types is language dependent
Prof. Su ECS 140A Lecture 5-6 5
Type Equivalence
- What does it mean for types to be the same?
- Two main approaches
- Name equivalence
- Types are the same if they are given the same name
- Structural equivalence
- Types are equivalence if they have the same structure
- Example struct { int x; int y; } x,y; // x, y are name equivalent struct { int x, int y; } z; // z is not name equivalent to x, y // but is structural equivalent to x, y
Prof. Su ECS 140A Lecture 5-6 6
Uses for types
- Program organization and documentation
- Separate types for separate concepts
- Represent concepts from problem domain
- Indicate intended use of declared identifiers
- Types can be checked, unlike program comments
- Identify and prevent errors
- Compile-time or run-time checking can prevent meaningless computations such as 3 + true - โBillโ
- Support optimization
- Example: short integers require fewer bits
- Access record component by known offset
Prof. Su ECS 140A Lecture 5-6 10
Compile-time vs run-time checking
- Lisp uses run-time type checking
(car x) make sure x is list before taking car of x
- C/Java uses compile-time type checking f(x) must have f : A -> B and x : A
- Basic tradeoff
- Both prevent type errors
- Run-time checking slows down execution
- Compile-time checking restricts program flexibility Lisp list: elements can have different types C/Java list: all elements must have same type
Prof. Su ECS 140A Lecture 5-6 11
Expressiveness
- In Lisp, we can write function like (lambda (x) (cond ((less x 10) x) (T (car x)))) Some uses will produce type error, some will not
- Static typing always conservative if (big-hairy-boolean-expression) then ((lambda (x) โฆ ) 5) else ((lambda (x) โฆ ) 10) Cannot decide at compile time if run-time error will occur
Prof. Su ECS 140A Lecture 5-6 12
Relative type-safety of languages
- Not safe: BCPL family, including C and C++
- Casts, pointer arithmetic
- Almost safe: Algol family, Pascal, Ada.
- Dangling pointers.
- Allocate a pointer p to an integer, deallocate the memory referenced by p, then later use the value pointed to by p
- No language with explicit deallocation of memory is fully type-safe
- Safe: Lisp, ML, Smalltalk, and Java
- Lisp, Smalltalk: dynamically typed
- ML, Java: statically typed
Prof. Su ECS 140A Lecture 5-6 13
Program analysis tools
- Growing area of commercial activity
- Lint, Purify, โฆ
- Coverity, Fortify, PreFix, PreFast, โฆ
- Two kinds of analysis
- Sound (or conservative)
- If analysis says program is correct, then it is
- If analysis does not say correct, program may be correct
- Unsound
- If analysis says correct, it might be incorrect
Prof. Su ECS 140A Lecture 5-6 14
Type checking and type inference
- Standard type checking int f(int x) { return x+1; }; int g(int y) { return f(y+1)*2;};
- Look at body of each function and use declared types of identifies to check agreement
- Type inference int f(int x) { return x+1; }; int g(int y) { return f(y+1)*2;};
- Look at code without type information and figure out what types could have been declared
Prof. Su ECS 140A Lecture 5-6 15
Motivation
- Types and type checking
- Type systems have improved steadily since Algol 60
- Important for modularity, compilation, reliability
- Type inference
- Widely regarded as important language innovation
- ML type inference gives you some idea of how many other static analysis algorithms work
Prof. Su ECS 140A Lecture 5-6 19
Types with type variables
- Example
val it = fn : (int -> t) -> t
- How does this work?
\
g
Assign types to leaves Propagate to internal nodes : s : int and generate constraints
t (s = int->t)
s->t
Solve by substitution
= (int->t)->t
Graph for \g. (g 2)
Prof. Su ECS 140A Lecture 5-6 20
Use of Polymorphic Function
- Function
val it = fn : (int -> t) -> t
- Possible applications
val it = fn : int -> int - f(add); > val it = 4 : int - fun isEven(x) = ...; > val it = fn : int -> bool - f(isEven); > val it = true : bool
Prof. Su ECS 140A Lecture 5-6 21
Recognizing type errors
- Function
val it = fn : (int -> t) -> t
- Incorrect use
- fun not(x) = if x then false else true;
val it = fn : bool -> bool - f(not); Type error: cannot make bool -> bool = int -> t
Prof. Su ECS 140A Lecture 5-6 22
Another Type Inference Example
- Function Definition
val it = fn : (t -> t)*t -> t
- Type Inference
Solve by substitution
= (v->v)*v->v \
@ g
x
g
Assign types to leaves
: t
: s
: s
Propagate to internal nodes and generate constraints
v (s = u->v)
s*t->v
u (s = t->u)
Graph for <g,x>. g(g x)
Prof. Su ECS 140A Lecture 5-6 23
Polymorphic Datatypes
- Datatype with type variable
- โa is syntax for โtype variable aโ
- datatype โa list = nil | cons of โa*(โa list)
nil : โa list cons : โa*(โa list) -> โa list
- Polymorphic function
- fun length nil = 0 | length (cons(x,rest)) = 1 + length(rest)
length : โa list -> int
- Type inference
- Infer separate type for each clause
- Combine by making two types equal (if necessary)
Prof. Su ECS 140A Lecture 5-6 24
Type inference with recursion
- Second Clause length(cons(x,rest)) = 1 + length(rest)
- Type inference
- Assign types to leaves, including function name
- Proceed as usual
- Add constraint that type of function body = type of function name
rest
x
length
cons
: t
\
โa list->int = t
: โa*โa list ->โa list
We do not expect you to master this
Prof. Su ECS 140A Lecture 5-6 28
Parametric Polymorphism: ML vs. C++
- ML polymorphic function
- Declaration has no type information
- Type inference: type expression with variables
- Type inference: substitute for variables as needed
- C++ function template
- Declaration gives type of function arg, result
- Place inside template to define type variables
- Function application: type checker does instantiation
Prof. Su ECS 140A Lecture 5-6 29
Example: swap two values
โข ML
- fun swap(x,y) = let val z = !x in x := !y; y := z end; val swap = fn : 'a ref * 'a ref -> unit
- C++ template void swap(T& x, T& y){ T tmp = x; x=y; y=tmp; }
Declarations look similar, but compiled very differently
Prof. Su ECS 140A Lecture 5-6 30
Implementation
- ML
- Swap is compiled into one function
- Typechecker determines how function can be used
- C++
- Swap is compiled into linkable format
- Linker duplicates code for each type of use
- Why the difference?
- ML ref cell is passed by pointer, local x is pointer to value on heap
- C++ arguments passed by reference (pointer), but local x is on stack, size depends on type
Prof. Su ECS 140A Lecture 5-6 31
Another example
- C++ polymorphic sort function template void sort( int count, T * A[count] ) { for (int i=0; i<count-1; i++) for (int j=i+1; j<count-1; j++) if (A[j] < A[i]) swap(A[i],A[j]); }
- What parts of implementation depend on type?
- Indexing into array
- Meaning and implementation of <
Prof. Su ECS 140A Lecture 5-6 32
Summary
- Types are important in modern languages
- Program organization and documentation
- Prevent program errors
- Provide important information to compiler
- Type inference
- Determine best type for an expression, based on known information about symbols in the expression
- Polymorphism
- Single algorithm (function) can have many types
- Overloading
- Symbol with multiple meanings, resolved at compile time