Static Check and Type System
Static Check and Type System
Yacc specification
Lex specification Code JVM specification
Type
generati
checking
on
4
Static Checking
• Typical examples of static checking are
– Type checks
– Flow-of-control checks
– Uniqueness checks
– Name-related checks
6
d = c + d; // FAIL
*d = a; // FAIL
a = op(d); // OK: static overloading (C++)
a = f(d); // OK: coersion of d to float
a = x->m(); // OK: dynamic binding (C++)
vector<int> v; // OK: template instantiation
7
Flow-of-Control Checks
myfunc() myfunc()
{ … { …
break; // ERROR switch (a)
} { case 0:
…
myfunc() break; // OK
{ … case 1:
while (n) …
{ … }
if (i>10) }
break; // OK
}
}
8
Uniqueness Checks
myfunc()
{ int i, j, i; // ERROR
…
}
struct myrec
{ int name;
};
struct myrec // ERROR
{ int id;
};
9
Name-Related Checks
Type Expressions
• Type expressions are used in declarations
and type casts to define or refer to a type
– Primitive types, such as int and bool
– Type constructors, such as pointer-to, array-of,
records and classes, templates, and functions
– Type names, such as typedefs in C and named
types in Pascal, refer to type expressions
12
13
14
fun fun
struct
val next
int pointer
Name Equivalence
• Each type name is a distinct type, even
when the type expressions that the names
refer to are the same
• Types are identical only if names match
• Used by Pascal (inconsistently)
type link = ^node; With name equivalence in Pascal:
var next : link; p ≠ next
last : link; p ≠ last
p : ^node; p = q = r
q, r : ^node; next = last
17
pointer = pointer
struct struct
val next val next
int pointer int
18
Type Systems
• A type system defines a set of types and
rules to assign types to programming
language constructs
• Informal type system rules, for example “if
both operands of addition are of type
integer, then the result is of type integer”
• Formal type system rules: Post systems
20
21
22
23
24
25
26
27
28
29
D → id : T { addtype(id.entry, T.type) }
T → boolean { T.type := boolean }
T → char { T.type := char }
T → integer { T.type := integer }
T → array [ num ] of T1 { T.type := array(1..num.val, T1.type) }
T → ^ T1 { T.type := pointer(T1)
Parametric types:
type constructor
31
T → T -> T E→E(E)
Example:
v : integer;
odd : integer -> boolean;
if odd(3) then
v := 1;
41
Parametric type:
type constructor
42