Upload
others
View
0
Download
0
Embed Size (px)
Citation preview
Lecture 10. Types and Type Checking
Wei Le
2015.9
Type
I Type is a property of program constructs such as expressions
I It defines a set of values (range of variables) and a set of operationson those values
I Classes are one instantiation of the modern notion of the typeI fields and methods of a Java class are meant to correspond to values
and operations
Type System
I A type system is a collection of rules that assign types to programconstructs (more constraints added to checking the validity of theprograms, violation of such constraints indicate errors)
I A languages type system specifies which operations are valid forwhich types
I Type systems provide a concise formalization of the semanticchecking rules
I Type rules are defined on the structure of expressions
I Type rules are language specific
Why do we need type systems
Consider the assembly language fragment
addi $r1, $r2, $r3
What are the types of $r1, $r2, $r3?
I Assembly language is untyped (MIPS assembly)
I This instruction allows you to add the contents of a register to animmediate value (a constant) and store the result in a (possibly)another register.
Why do we need type systems
Consider the assembly language fragment
addi $r1, $r2, $r3
What are the types of $r1, $r2, $r3?
I Assembly language is untyped (MIPS assembly)
I This instruction allows you to add the contents of a register to animmediate value (a constant) and store the result in a (possibly)another register.
Why do we need type systems
Consider the assembly language fragment
addi $r1, $r2, $r3
What are the types of $r1, $r2, $r3?
I Assembly language is untyped (MIPS assembly)
I This instruction allows you to add the contents of a register to animmediate value (a constant) and store the result in a (possibly)another register.
Why do we need type systems
I It doesnt make sense to add a function pointer and an integer in C
I It does make sense to add two integers
I But both have the same assembly language implementation!
Use of Types
I Detect errors:I Memory errors, such as attempting to use an integer as a pointer.I Violations of abstraction boundaries, such as using a private field
from outside a class.
I Help compilation:I When Python sees x+y, its type systems tells it almost nothing
about types of x and y, so code must be general.I In C, C++, Java, code sequences for x+y are smaller and faster,
because representations are known.
Type Checking and Type Inference
I Type Checking is the process of verifying fully typed programs
I Type Inference is the process of filling in missing type information
I The two are different, but are often used interchangeably
Inference Rule
From English to an Inference Rule
I Rules of inference are a compact notation of if-then statements
I Symbol ∧ is ”and”
I Symbol ⇒ is ”if-then”
I x : T is ”x has type T”
From English to an Inference Rule
From English to an Inference Rule
From English to an Inference Rule
Example
Two Rules
Example
Static and Dynamic Typed Languages
I Statically typed languages: all or almost all type checking occurs atcompilation time. (C, Java)
I Dynamically typed languages: almost all checking of types is done aspart of program execution (Scheme)
I Untyped languages: no type checking (assembly, machine code)
Static and Dynamic Types
Relations of Static and Dynamic Types in Simple TypeSystems
So far:
A set of basic concepts:
I type
I type systems
I type checking
I type inference
I inference rules
I static and dynamic typed languages
I static and dynamic types
Semantic Analysis Related to Types
Goals:
I What is the type of the expression – type inference (what is thevalue the expression potentially produces? based on its range, whattype it is?)
I Do we have a correct assignment (following type rules) of types onall the expressions in the program? – type checking
Perspectives of studying types:
I Language designers: designing the type systems
I Compilers: type checking programs
Next:
I We do an overview of the two perspectives
Designing a Type SystemTwo Conflict Goals:
In another word: There is a tradeoff between
I Flexible rules that do not constrain programming
I Restrictive rules that ensure safety of execution
Soundness
I It is a property of the type systemI Intuitively, a sound type system can correctly predict the type of a
variable at runtimeI There can be many sound type rules, we need to use the most
precise ones so it can be useful
Tradeoffs of Static and Dynamic Type Checking Systems
I static type system does not have knowledge of input values orexecution behaviors
I static type system disallows some correct programs, cannot predictprecisely all the behaviors (some program runs correctly will berejected)
I better static type system or dynamic type system
Static
I Static checking catches many programming errors at compile time
I Avoids overhead of runtime type checking
I Using various devices to recover the flexibility lost by ”going static:”subtyping, coercions, type parameterization
Dynamic:
I Static type systems are restrictive; can require more work to doreasonable things.
I Rapid prototyping easier in a dynamic type system.
Using Subtypes
I In languages such as Java, can define types (classes) either toI Implement a type, orI Define the operations on a family of types without (completely)
implementing themI Hence, relaxes static typing a bit: we may know that something is a
Y without knowing precisely which subtype it has
Implicit Coercions
Coercion Examples
Type Checking Algorithm
One Pass Type Checking for Cool
So far:
I Concepts
I Overview of type system design and type checking algorithms
Next: COOL (Why Cool is a good language to learn when learning basicconcepts?)
I Cool type system touches all the key concepts: e.g., subtyping,method dispatch
Cool Types
I Class names
I SELF TYPE Note: there are no base types (as in Java int)
I The user declares types for all identifiers
I The compiler infers types for expressions (Infers a type for everyexpression)
Rules for Constant
Rules for New
Two More Rules
Type Inference: Determining Types for Every AST Node
Type Derivations
Get Into More Complicated Rules
Important ones:
I Let
I If-then-else, case
I Method
I Self Type
Pay attention to:
I notation and concept development
I typing rule design
Type Rules and Type Environment
I The type rules define the type of every Cool expression in a givencontext.
I The context is the type environment, which describes the type ofevery unbound identifier appearing in an expression.
Type Rules and Type environment
Type rules have general format:
I O environment for object
I M environment for methods
I C containing class
I The dots above the horizontal bar stand for other statements aboutthe types of sub-expressions of e. These other statements arehypotheses of the rule; if the hypotheses are satisfied, then thestatement below the bar is true.
Type Environment for Object
Type Environment for Object
Notation Understanding
I O is a function (implemented in the symbol table: mapping betweenvariables and types)
I O[T/x ] is a also function, extend O with a pair of: x of type T
I The type environment provides the type of free variables in thecurrent scope
I During type checking, you can look for the type of a particularvariable on the AST in the type environment O
I O[T/x ] ` e : T execute the expression e in this environment, andget the type T
Example:
An Example
New Rule
Let: No Initialization
Let Example
Let Example
Type Inference Approach
I The type environment gives types to the free identifiers in thecurrent scope
I The type environment is passed down the AST from the roottowards the leaves
I Types are computed up the AST from the leaves towards the root
Let With Initialization
Let With Initialization
Subtyping
I Reflexive
I Transitive
Let with Initialization Modified
Let with Initialization – More Examples
How it is different from the previous Let rule?
Examples of Wrong Typing Rules
Examples of Wrong Typing Rules
Examples of Wrong Typing Rules
Examples of Wrong Typing Rules
Typing Rules
I The typing rules use very concise notation
I They are very carefully constructed
I Virtually any change in a rule either:I Makes the type system unsound (bad programs are accepted as well
typed)I makes the type system less usable (perfectly good programs are
rejected)
Assignment
Initialized Attributes
If-then-else
If-then-else
Least Upper Bound: Operations
I inheritance tree (rooted at object)
I class hierarchy descent from the object
I walk back the tree to find the parent of the two types
If-then-else
Case
Method Dispatch
Notes on Method Dispatch
Type Environment: Method
Discussion
I study type system from programming languages and compiler pointsof view
I ”type rule is weak?” vs ”weakly typed programming languages?”
Three types of dispatch in Cool
We first discuss two:
[email protected] () invokes the method f in class B on the object that is the valueof e.
The Dispatch Rule
Static Dispatch
The class T of the method f is given in the dispatch, and the type T0
must conform to T .
Self Type
Tradeoffs between complexity and flexibility
Static and Dynamic Types in Cool
Static and Dynamic Types in Cool
Self Type: a Motivating Example
Self Type: a Motivating Example
Self Type: a Motivating Example
Self Type: a Motivating Example
Self Type: a Motivating Example
Self Type
I A special type
I A concept of static type not dynamic type
I Helps with the expressiveness and flexibility (accept more correctprograms)
I It is like a ”type variable”
I An example to show tradeoffs between complexity vs expressivenessof the type systems
Important Typing Rule Regarding Self Type
Operations on Self Type
Operations on Self Type
Operations on Self Type
Operations on Self Type
Self Type in Cool
Self Type in Cool
Type Checking Rules with Self Type
Type Checking Rules with Self Type
Type Checking Rules with Self Type
Old rule for method dispatch:
Type Checking Rules with Self Type
Type Checking Rules with Self Type
Type Checking Rules with Self Type
Type Checking Rules with Self Type
Type Checking Rules with Self Type
Type Checking Rules with Self Type
Type Systems