Winter 2006 2007 Compiler Construction T 7 semantic

  • Slides: 27
Download presentation
Winter 2006 -2007 Compiler Construction T 7 – semantic analysis part II type-checking Mooly

Winter 2006 -2007 Compiler Construction T 7 – semantic analysis part II type-checking Mooly Sagiv and Roman Manevich School of Computer Science Tel-Aviv University

Announcements n n PA 2 deadline extended to December 13 PA 3 published today

Announcements n n PA 2 deadline extended to December 13 PA 3 published today n n Deadline December 27 Got ½ week extra for each assignment 2

Today ic Lexical Analysis Syntax Analysis Parsing IC AST Symbol Table etc. Inter. Rep.

Today ic Lexical Analysis Syntax Analysis Parsing IC AST Symbol Table etc. Inter. Rep. (IR) Code Generation Language n exe Executable code Today: n Static semantics n n Creating types Type-checking Overall flow of semantic analysis PA 3 – semantic analysis (T 6 + T 7) 3

Examples of type errors assigned type doesn’t match declared type relational operator applied to

Examples of type errors assigned type doesn’t match declared type relational operator applied to non-int type 1 < true int a; a = true; void foo(int x) { int x; foo(5, 7); } argument list doesn’t match formal parameters class A {…} class B extends A { void foo() { A a; B b; b = a; a is not a } subtype of b } 4

Types and type safety n A type represents a set of values computed during

Types and type safety n A type represents a set of values computed during the execution of a program n n Type safety means that types are used “consistently” n n n Consistency formally defined by typing rules Checking type-safety: bind types, check Type bindings define type of constructs in a program n n n boolean = {true, false} int = {-232, 232} void = {} Explicit bindings: int x; Implicit bindings: x = 1; Check: determine correct usage of type bindings according to typing rules 5

Class hierarchy for types abstract class Type {. . . } class Int. Type

Class hierarchy for types abstract class Type {. . . } class Int. Type extends Type {. . . } class Bool. Type extends Type {. . . } class Array. Type extends Type { Type elem. Type; } class Method. Type extends Type { Type[] param. Types; Type return. Type; . . . } class Class. Type extends Type { ICClass class. AST; . . . }. . . 6

Type comparison n Option 1: use a unique object for each distinct type n

Type comparison n Option 1: use a unique object for each distinct type n n n Option 2: implement a method t 1. equals(t 2) n n Resolve each type expression to same object Use reference equality for comparison (==) Perform deep (structural) test For object-oriented languages also need sub-typing: t 1. subtypeof(t 2) 7

Creating type objects n Can build types while parsing non terminal Type type; type

Creating type objects n Can build types while parsing non terminal Type type; type : : = BOOLEAN {: RESULT = Type. Table. bool. Type; : } | ARRAY LB type: t RB {: RESULT = Type. Table. array. Type(t); : } n n n Type objects = AST nodes for type expressions Store types in global type table When a class is defined n n Add entry to symbol table Add entry to global type table 8

Type table implementation class Type. Table { // Maps element types to array types

Type table implementation class Type. Table { // Maps element types to array types private Map<Type, Array. Type> unique. Array. Types; private Map<String, Class. Type> unique. Class. Types; public static Type bool. Type = new Bool. Type(); public static Type int. Type = new Int. Type(); . . . // Returns unique array type object public static Array. Type array. Type(Type elem. Type) { if (unique. Array. Types. contains. Key(elem. Type)) { // array type object already created – return it return unique. Array. Types. get(elem. Type); } else { // object doesn’t exist – create and return it Array. Type arrt = new Array. Type(elem. Type); unique. Array. Types. put(elem. Type, Array. Type); return arrt; } }. . . } 9

Type judgments n Static semantics = formal notation which describes type judgments E: T

Type judgments n Static semantics = formal notation which describes type judgments E: T means “E is a well-typed expression of type T” n Examples: n n 2 : int 2 * (3 + 4) : int true : bool “Hello” : string 10

Type judgments n n Need to account for symbols More general notation: A E:

Type judgments n n Need to account for symbols More general notation: A E: T means “In the context A the expression E is a well-typed expression with type T” Type context = set of type bindings id : T (symbol table) Examples: n n n b: bool, x: int b: bool x: int 1 + x < 4: bool foo: int->string, x: int foo(x) : string 11

Typing rules for expressions n Rules notation n “If E 1 has type int

Typing rules for expressions n Rules notation n “If E 1 has type int and E 2 has type int, then E 1 + E 2 has type int” optional rule name A E 1 : int A E 2 : int [+] A E 1+E 2 : int n No premises = axiom (AST leaves) A true : bool A false : bool A int-literal : int A string-literal : string 12

Some IC expression rules 1 A true : bool A false : bool A

Some IC expression rules 1 A true : bool A false : bool A int-literal : int A string-literal : string A E 1 : int A E 2 : int A E 1 op E 2 : int A E 1 : int A E 2 : int A E 1 rop E 2 : bool A E 1 : T A E 2 : T A E 1 rop E 2 : bool op { +, -, /, *, %} rop { <=, <, >, >=} rop { ==, !=} 13

Some IC expression rules 2 A E 1 : bool A E 2 :

Some IC expression rules 2 A E 1 : bool A E 2 : bool A E 1 lop E 2 : bool lop { &&, || } A E 1 : int A E 1 : bool A - E 1 : int A ! E 1 : bool A E 1 : T[] A E 1. length : int A E 1 : T[] A E 2 : int A E 1[E 2] : T A T C id : T A A new T() : T A id : T A E 1 : int A new T[E 1] : T[] 14

Meaning of rules n Inference rule says: given that antecedent judgments are true then

Meaning of rules n Inference rule says: given that antecedent judgments are true then consequent judgment is true A E 1 : int A E 2 : int E 1 : int E 2 : int [+] A E 1+E 2 : int + : int E 1 E 2 15

Type-checking algorithm 1. Construct types 1. 2. 3. 2. Add basic types to type

Type-checking algorithm 1. Construct types 1. 2. 3. 2. Add basic types to type table Traverse AST looking for user-defined types (classes, methods, arrays) and store in table Bind all symbols to types Traverse AST bottom-up (using visitor) 1. 2. For each AST node find corresponding rule (there is only one for each kind of node) Check if rule holds 1. 2. Yes: assign type to node according to consequent No: report error 16

Algorithm example … Binop. Expr op=AND A E 1 : bool A E 2

Algorithm example … Binop. Expr op=AND A E 1 : bool A E 2 : bool A E 1 lop E 2 : bool lop { &&, || } A E 1 : bool Binop. Expr op=GT : bool Unop. Expr op=NEG A !E 1 : bool A E 1 : int A E 2 : int A E 1 rop E 2 : bool int. Literal val=45 val=32 : int 45 > 32 && !false bool. Literal rop { <=, <, >, >=} val=false : bool A int-literal : int 17

Type-checking visitor class Type. Checker implements Propagating. Visitor<Type, Symbol. Table> { public Type visit(Arith.

Type-checking visitor class Type. Checker implements Propagating. Visitor<Type, Symbol. Table> { public Type visit(Arith. Binop. Exp e, Symbol. Table symtab) throws Exception { Type l. Type = e. left. accept(this, symtab); Type r. Type = e. right. accept(this, symtab); if (l. Type != Type. Table. int. Type()) throw new Type. Error(“Expecting int type, found “ + l. Type. to. String(), e. get. Line); if (r. Type != Type. Table. int. Type) throw new Type. Error(“Expecting int type, found “ + r. Type. to. String(), e. get. Line); // we only get here if no exceptions were thrown e. type = Type. Table. int. Type; }. . . } 18

Statement rules n n Statements have type void Judgments of the form A S

Statement rules n n Statements have type void Judgments of the form A S n n In environment A, S is well-typed Rule for while statement: E e: bool E S E while (e) S 19

Checking return statements n Use special entry {ret: Tr} to represent method return value

Checking return statements n Use special entry {ret: Tr} to represent method return value n n Add entry to symbol table when entering method Lookup entry when we hit return statement T subtype of T’ E e: T ret: T’ E T≤T’ E return e; ret: void E E return; 20

Subtyping n Inheritance induces subtyping relation n n Type hierarchy is a tree (anti-symmetric

Subtyping n Inheritance induces subtyping relation n n Type hierarchy is a tree (anti-symmetric relation) Subtyping rules: A extends B {…} A≤B n A≤B A≤A B≤C A≤C null ≤ A Subtyping does not extend to array types n A subtype of B then A[] is not a subtype of B[] 21

Type checking with subtyping n “A value of type S may be used wherever

Type checking with subtyping n “A value of type S may be used wherever a value of type T is expected” n n S≤T values(S) values(T) Subsumption rule connects subtyping relation and typing judgments A E: S S≤T A E: T n ”If expression E has type S, it also has type T for every T such that S ≤ T“ 22

IC rules with subtyping E e 1 : T 1 E e 2 :

IC rules with subtyping E e 1 : T 1 E e 2 : T 2 T 1 ≤ T 2 or T 2 ≤ T 1 op {==, !=} E e 1 op e 2 : bool Method invocation rules: 23

More rules A S 1 A S 2; …; Sn A S 1; …;

More rules A S 1 A S 2; …; Sn A S 1; …; Sn [sequence] E, x 1: t 1, …, E, xn: tn, ret: tr Sbody [method] E tr m(t 1 x 1, …, tn xn) {Sbody} methods(C)={m 1, …, mk} Env(C, mi) mi for all i=1…k [class] C classes(P)={C 1, …, Cn} Ci for all i=1…n [program] P 24

Semantic analysis flow n Parsing and AST construction n Construct and initialize global type

Semantic analysis flow n Parsing and AST construction n Construct and initialize global type table Phase 1: Symbol table construction n n n Resolve names Check scope rules using symbol table Phase 3: Type checking n n Construct class hierarchy and check that hierarchy is a tree Construct remaining symbol table hierarchy Assign enclosing-scope for each AST node Phase 2: Scope checking n n Combine library AST with IC program AST Assign type for each AST node Phase 4: Remaining semantic checks Disclaimer: This is only a suggestion 25

PA 3 n n n After semantic analysis phase should handle only legal programs

PA 3 n n n After semantic analysis phase should handle only legal programs (modulo 2 unchecked conditions) Note 1: some semantic conditions not specified in exercise (e. g. , shadowing fields) – see IC specification for all conditions Note 2: class A { A foo(){…} } class B extends A { B foo(){…} } Illegal in IC (no support for downcasting) 26

See you next week 27

See you next week 27