Presentation is loading. Please wait.

Presentation is loading. Please wait.

Compiler Construction Semantic Analysis II Ran Shaham and Ohad Shacham School of Computer Science Tel-Aviv University.

Similar presentations


Presentation on theme: "Compiler Construction Semantic Analysis II Ran Shaham and Ohad Shacham School of Computer Science Tel-Aviv University."— Presentation transcript:

1 Compiler Construction Semantic Analysis II Ran Shaham and Ohad Shacham School of Computer Science Tel-Aviv University

2 2 PAs PA2 Deadline extension Dec 29 Fix PA1 grader’s notes in your IC.lex PA1 Escape characters should stay as they are \\n { str.append(“\n”) }\\n

3 3 Compiler IC Program ic x86 executable exe Lexical Analysis Syntax Analysis Parsing ASTSymbol Table etc. Inter. Rep. (IR) Code Generation IC compiler We saw: Scope Symbol tables Today: Type checking Recap

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

5 5 Types Type Set of values computed during program execution boolean = { true,false } int = {-2 32,2 32 } void = {} Type safety Types usage adheres formally defined typing rules

6 6 Type judgments e : T Formal notation for type judgments e is a well-typed expression of type T 2 : int 2 * (3 + 4) : int true : bool “Hello” : string

7 7 Type judgments E  e : T Formal notation for type judgments In the context E, e is a well-typed expression of T b:bool, x:int  b:bool x:int  1 + x < 4:bool foo:int->string, x:int  foo(x) : string Type context set of type bindings id : T (symbol table)

8 8 Typing rules Premise Conclusion [Name] Conclusion [Name] Axioms

9 9 Typing rules for expressions E  true : bool E  false : bool E  int-literal : int E  string-literal : string E  e 1 : intE  e 2 : int E  e 1 +e 2 : int [+] E  null : nullE  new T() : T AST leaves

10 10 Some IC expression rules 1 E  true : bool E  e1 : intE  e2 : int E  e1 op e2 : int E  false : bool E  int-literal : int E  string-literal : string op  { +, -, /, *, %} E  e1 : intE  e2 : int E  e1 rop e2 : bool rop  {, >=} E  e1 : TE  e2 : T E  e1 rop e2 : bool rop  { ==,!=}

11 11 Some IC expression rules 2 E  e1 : boolE  e2 : bool E  e1 lop e2 : bool lop  { &&,|| } E  e1 : int E  - e1 : int E  e1 : bool E  ! e1 : bool E  e1 : T[] E  e1. length : int E  e1 : T[]E  e2 : int E  e1[e2] : T E  e1 : int E  new T[e1] : T[] E  new T() : T id : T  E E  id : T

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

13 13 45 > 32 && !false BinopExpr UnopExpr BinopExpr … op=AND op=NEG op=GT intLiteral val=45 intLiteral val=32 boolLiteral val=false : int : bool E  false : bool E  int-literal : int E  e1 : intE  e2 : int E  e1 rop e2 : bool rop  {, >=} E  e1 : bool E  e2 : bool E  e1 lop e2 : bool lop  { &&,|| } E  e1 : bool E  !e1 : bool Algorithm example

14 14 Type-checking visitor class TypeChecker implements PropagatingVisitor { public Type visit(ArithBinopExp e, SymbolTable symtab) throws Exception { Type lType = e.left.accept(this, symtab); Type rType = e.right.accept(this, symtab); if (lType != TypeTable.intType()) throw new TypeError(“Expecting int type, found “ + lType.toString(), e.getLine); if (rType != TypeTable.intType) throw new TypeError(“Expecting int type, found “ + rType.toString(), e.getLine); // we only get here if no exceptions were thrown e.type = TypeTable.intType; }... }

15 15 Statement rules Statements have type void Judgments of the form E  S In environment E, S is well-typed E  e:bool E  S E  while (e) S E  e:bool E  S E  if (e) S E  e:bool E  S 1 E  S 2 E  if (e) S 1 else S 2 E  break E  continue

16 16 Checking return statements Special entry { ret :T r } represents return value Add to symbol table when entering method Lookup entry when hit return statement ret :void  E E  return; ret :T’  E T≤T’ E  return e; E  e:T T subtype of T’

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

18 18 Type checking with subtyping S ≤ T S may be used whenever T is expected An Expression E from type S also has type T E  e : S S ≤ T E  e : T

19 19 IC rules with subtyping E  e1 : T1 E  e2 : T2 T1 ≤ T2 or T2 ≤ T1 op {==,!=} E  e1 op e2 : bool

20 20 Semantic analysis flow Parsing and AST construction Combine library AST with IC program AST Construct and initialize global type table Phase 1: Symbol table construction 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 Resolve names Check scope rules using symbol table Phase 3: Type checking Assign type for each AST node Phase 4: Remaining semantic checks

21 21 Class hierarchy for types abstract class Type {...} class IntType extends Type {...} class BoolType extends Type {...} class ArrayType extends Type { Type elemType; } class MethodType extends Type { Type[] paramTypes; Type returnType;... } class ClassType extends Type { ICClass classAST;... }...

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

23 23 Type table implementation class TypeTable { // Maps element types to array types private Map uniqueArrayTypes; private Map uniqueClassTypes; public static Type boolType = new BoolType(); public static Type intType = new IntType();... // Returns unique array type object public static ArrayType arrayType(Type elemType) { if (uniqueArrayTypes.containsKey(elemType)) { // array type object already created – return it return uniqueArrayTypes.get(elemType); } else { // object doesn’t exist – create and return it ArrayType arrt = new ArrayType(elemType); uniqueArrayTypes.put(elemType,ArrayType); return arrt; } }... }

24 Recap

25 25 Semantic analysis flow example class A { int x; int f(int x) { boolean y;... } } class B extends A { boolean y; int t; } class C { A o; int z; }

26 26 Parsing and AST construction IntType BoolType A B C f : int->int … TypeTable Table populated with user-defined types during parsing (or special AST pass) class A { int x; int f(int x) { boolean y;... } } class B extends A { boolean y; int t; } class C { A o; int z; } parser.parse() ICClass name = A Field name = x type = IntType Method name = f Param name = x type = IntType Declaration varName = y initExpr = null type = BoolType fields[0] methods[0] body parameters[0] AST Program file = … classes[0] ICClass name = B super = A classes[1] classes[2] … ICClass name = C … …

27 27 Defined types and type table class A { int x; int f(int x) { boolean y;... } } class B extends A { boolean y; int t; } class C { A o; int z; } class TypeTable { public static Type boolType = new BoolType(); public static Type intType = new IntType();... public static ArrayType arrayType(Type elemType) {…} public static ClassType classType(String name, String super, ICClass ast) {…} public static MethodType methodType(String name,Type retType, Type[] paramTypes) {…} } abstract class Type { String name; boolean subtypeof(Type t) {...} } class IntType extends Type {...} class BoolType extends Type {...} class ArrayType extends Type { Type elemType; } class MethodType extends Type { Type[] paramTypes; Type returnType; } class ClassType extends Type { ICClass classAST; } IntType BoolType A B C f : int->int … TypeTable

28 28 Assigning types by declarations IntType BoolType... TypeTable ClassType name = A ClassType name = B ClassType name = C MethodType name = f retType paramTypes type super All type bindings available during parsing time ICClass name = A Field name = x type = IntType Method name = f Param name = x type = IntType Declaration varName = y initExpr = null type = BoolType fields[0] methods[0] body parameters[0] AST Program file = … classes[0] ICClass name = B super = A classes[1] classes[2] … ICClass name = C … …

29 29 Symbol tables ICClass name = A Field name = x type = IntType Method name = f Param name = x type = IntType Declaration varName = y initExpr = null type = BoolType fields[0] methods[0] body parameters[0] AST Program file = … classes[0] ICClass name = B super = A classes[1] classes[2] … ICClass name = C … … ACLASS B C Global symtab xFIELDIntType fMETHODint->int A symtab oCLASSA zFIELDIntType C symtab tFIELDIntType yFIELDBoolType B symtab xPARAMIntType yVARBoolType this VARA ret RET_VARIntType f symtab abstract class SymbolTable { private SymbolTable parent; } class ClassSymbolTable extends SymbolTable { Map methodEntries; Map fieldEntries; } class MethodSymbolTable extends SymbolTable { Map variableEntries; } abstract class Symbol { String name; } class VarSymbol extends Symbol {…} class LocalVarSymbol extends Symbol {…} class ParamSymbol extends Symbol {…}...

30 30 Scope nesting in IC SymbolKindTypeProperties Global SymbolKindTypeProperties Class SymbolKindTypeProperties Method SymbolKindTypeProperties Block names of all classes fields and methods formals + locals variables defined in block class GlobalSymbolTable extends SymbolTable {} class ClassSymbolTable extends SymbolTable {} class MethodSymbolTable extends SymbolTable {} class BlockSymbolTable extends SymbolTable {}

31 31 Symbol tables ICClass name = A Field name = x type = IntType Method name = f Param name = x type = IntType Declaration varName = y initExpr = null type = BoolType fields[0] methods[0] body parameters[0] AST Program file = … classes[0] ICClass name = B super = A classes[1] classes[2] … ICClass name = C … … ACLASS B C Global symtab xFIELDIntType fMETHODint->int A symtab oCLASSA zFIELDIntType C symtab tFIELDIntType yFIELDBoolType B symtab xPARAMIntType yVARBoolType this VARA ret RET_VARIntType f symtab this belongs to method scope ret can be used later for type-checking return statements Location name = x type = ? …

32 32 Sym. tables phase 1 : construction ICClass name = A Field name = x type = IntType Method name = f Param name = x type = IntType Declaration varName = y initExpr = null type = BoolType fields[0] methods[0] body parameters[0] AST Program file = … classes[0] ICClass name = B super = A classes[1] classes[2] … ICClass name = C … … ACLASS B C Global symtab xFIELDIntType fMETHODint->int A symtab oCLASSA zFIELDIntType C symtab tFIELDIntType yFIELDBoolType B symtab xPARAMIntType yVARBoolType this VARA ret RET_VARIntType f symtab class TableBuildingVisitor implements Visitor {... } Location name = x type = ? … Build tables, Link each AST node to enclosing table abstract class ASTNode { SymbolTable enclosingScope; } enclosingScope symbol ?

33 33 ICClass name = A Field name = x type = IntType Method name = f Param name = x type = IntType Declaration varName = y initExpr = null type = BoolType fields[0] methods[0] body parameters[0] AST Program file = … classes[0] ICClass name = B super = A classes[1] classes[2] … ICClass name = C … … ACLASS B C Global symtab xFIELDIntType fMETHODint->int A symtab oCLASSA zFIELDIntType C symtab tFIELDIntType yFIELDBoolType B symtab xPARAMIntType yVARBoolType this VARA ret RET_VARIntType f symtab class TableBuildingVisitor implements Visitor {... } During this phase, add symbols from definitions, not uses, e.g., assignment to variable x symbol ? Location name = x type = ? … Sym. tables phase 1 : construct

34 34 ICClass name = A Field name = x type = IntType Method name = f Param name = x type = IntType Declaration varName = y initExpr = null type = BoolType fields[0] methods[0] body parameters[0] AST Program file = … classes[0] ICClass name = B super = A classes[1] classes[2] … ICClass name = C … … ACLASS B C Global symtab xFIELDIntType fMETHODint->int A symtab oCLASSA zFIELDIntType C symtab tFIELDIntType yFIELDBoolType B symtab xPARAMIntType yVARBoolType this VARA ret RET_VARIntType f symtab symbol Location name = x type=? … Sym. tables phase 2 : resolve Resolve each id to a symbol, e.g., in x=5 in foo, x is the formal parameter of f check scope rules: illegal symbol re-definitions, illegal shadowing, illegal use of undefined symbols... class SymResolvingVisitor implements Visitor {... } enclosingScope

35 35 ICClass name = A Field name = x type = IntType Method name = f Param name = x type = IntType Declaration varName = y initExpr = null type = BoolType fields[0] methods[0] body parameters[0] AST Program file = … classes[0] ICClass name = B super = A classes[1] classes[2] … ICClass name = C … … Location name = x type = IntType … Type-check AST IntType BoolType... TypeTable class TypeCheckingVisitor implements Visitor {... } Use type-rules to infer types for all AST expression nodes Check type rules for statements

36 36 ICClass name = A Field name = x type = IntType Method name = f Param name = x type = IntType Declaration varName = y initExpr = null type = BoolType fields[0] methods[0] body parameters[0] AST Program file = … classes[0] ICClass name = B super = A classes[1] classes[2] … ICClass name = C … … Location name = x type = IntType … Miscellaneous semantic checks class SemanticChecker {... } Check remaining semantic checks: single main method, break/continue inside loops etc.

37 37 public Type visit(While whileStatement) { Type conditionType = whileStatement.getCondition().accept(this); whileStatement.setType(PrimitiveTypes.VOID); if (conditionType != PrimitiveTypes.BOOLEAN) Error ++loopDepth; whileStatement.getOperation().accept(this); --loopDepth; return null; }

38 38 public Type visit(Break breakStatement) { if (loopDepth == 0) error; setType(PrimitiveTypes.VOID); return null; }


Download ppt "Compiler Construction Semantic Analysis II Ran Shaham and Ohad Shacham School of Computer Science Tel-Aviv University."

Similar presentations


Ads by Google