Type Checking
Type Checking
What is a Type?
• Short for “data type”
• Classification identifying kinds of data
• A set of possible values which a variable can
possess
• Operations that can be done on member values
• A representation (perhaps in memory)
Type Intuition
• Structural equivalence
– Two types are equivalent if they have the same
structure
– Two type-expressions are structurally equivalent
if either they are the same basic type or they are
formed by applying the same type constructor to
structurally equivalent types
• Name equivalence
– Each type name is viewed as a distinct type
Checking Structural Equivalence
Type-Checking Example
Type-Checking Example
• We will use the following type constructors
– array(I,T) : creates a type expression for an array of type T with index set I
– pointer(T) : creates a type expression of type pointer to type T
– function(T,T) : creates a type expression of type function from type T to type T
• We will also use the following:
– id.entry : this attribute gives the location of the corresponding identifier in the symbol
table
– addtype(id.entry, type) : enters the type information to the symbol table
– lookup(id.entry) : returns the type information stored in the symbol table
• If we detect an error, we will set the type of the corresponding program segment
to type-error
Type Checking: How should it work?
• Let’s examine a program that is part of the language defined above
x: char; //this declares a new variable “ x ” of type char
y: pointer char; //this declares “ y ” to be of type pointer(char)
x := ‘ c ’ ; //this assignment is a literal (which should be a char) to a
//char
x := * y; //this de-references y (of type pointer(char)) to get
//something of type char, and then assigns it to x
(which is of //type char)
• Let us now draw the parse tree for this program
• We will walk the parse tree (depth first walk – walk down the left-
most un-touched branch and then back up)
• Show how the type-checking should progress
Type-Checking Example: Parse Tree
Type Checking Example: Simple Example
Type Checking Example: Declarations
Type Checking Example: Expressions
Type Checking Example: Expressions
Type Checking: Statements
Type Inference