Winter 2007-2008 Compiler Construction T7 – semantic analysis part II type-checking Mooly Sagiv and Roman Manevich School of Computer Science Tel-Aviv.

Slides:



Advertisements
Similar presentations
CS3012: Formal Languages and Compilers Static Analysis the last of the analysis phases of compilation type checking - is an operator applied to an incompatible.
Advertisements

Winter Compiler Construction T6 – semantic analysis part I scopes and symbol tables Mooly Sagiv and Roman Manevich School of Computer Science.
CPSC 388 – Compiler Design and Construction
Type Checking, Inference, & Elaboration CS153: Compilers Greg Morrisett.
Semantics Static semantics Dynamic semantics attribute grammars
Attribute Grammars Prabhaker Mateti ACK: Assembled from many sources.
Intermediate Code Generation
Intermediate Representation III. 2 PAs PA2 deadline is
1 Mooly Sagiv and Greta Yorsh School of Computer Science Tel-Aviv University Modern Compiler Design.
CS7100 (Prasad)L16-7AG1 Attribute Grammars Attribute Grammar is a Framework for specifying semantics and enables Modular specification.
Overview of Previous Lesson(s) Over View  Front end analyzes a source program and creates an intermediate representation from which the back end generates.
Compiler Construction
Denotational Semantics Syntax-directed approach, generalization of attribute grammars: –Define context-free abstract syntax –Specify syntactic categories.
Cse321, Programming Languages and Compilers 1 6/19/2015 Lecture #18, March 14, 2007 Syntax directed translations, Meanings of programs, Rules for writing.
1 Control Flow Analysis Mooly Sagiv Tel Aviv University Textbook Chapter 3
Compiler Construction Semantic Analysis I Ran Shaham and Ohad Shacham School of Computer Science Tel-Aviv University.
Cse321, Programming Languages and Compilers 1 6/23/2015 Lecture #15, March. 5, 2007 Judgments for mini-Java Multiple type environments Class Hierarchy.
Compiler Construction Semantic Analysis II Ran Shaham and Ohad Shacham School of Computer Science Tel-Aviv University.
Compiler Summary Mooly Sagiv html://
Compiler Construction Semantic Analysis II Rina Zviel-Girshin and Ohad Shacham School of Computer Science Tel-Aviv University.
Chapter 2 A Simple Compiler
Compiler Construction Semantic Analysis I Rina Zviel-Girshin and Ohad Shacham School of Computer Science Tel-Aviv University.
Compiler Construction Recap Rina Zviel-Girshin and Ohad Shacham School of Computer Science Tel-Aviv University.
Cs164 Prof. Bodik, Fall Symbol Tables and Static Checks Lecture 14.
CSC 8310 Programming Languages Meeting 2 September 2/3, 2014.
Symbol Table (  ) Contents Map identifiers to the symbol with relevant information about the identifier All information is derived from syntax tree -
2.2 A Simple Syntax-Directed Translator Syntax-Directed Translation 2.4 Parsing 2.5 A Translator for Simple Expressions 2.6 Lexical Analysis.
Semantic Analysis III + Intermediate Representation I.
1 Semantic Analysis Aaron Bloomfield CS 415 Fall 2005.
Winter Compiler Construction T8 – semantic analysis recap + IR part 1 Mooly Sagiv and Roman Manevich School of Computer Science Tel-Aviv University.
3-1 Chapter 3: Describing Syntax and Semantics Introduction Terminology Formal Methods of Describing Syntax Attribute Grammars – Static Semantics Describing.
ISBN Chapter 3 Describing Semantics -Attribute Grammars -Dynamic Semantics.
CS412/413 Introduction to Compilers and Translators Spring ’99 Lecture 8: Semantic Analysis and Symbol Tables.
Compiler Construction Compiler Construction Semantic Analysis I.
Interpretation Environments and Evaluation. CS 354 Spring Translation Stages Lexical analysis (scanning) Parsing –Recognizing –Building parse tree.
1 Mooly Sagiv and Greta Yorsh School of Computer Science Tel-Aviv University Modern Compiler Design.
410/510 1 of 18 Week 5 – Lecture 1 Semantic Analysis Compiler Construction.
CS 363 Comparative Programming Languages Semantics.
Compiler Construction Dr. Noam Rinetzky and Orr Tamir School of Computer Science Tel Aviv University
Chapter 3 Part II Describing Syntax and Semantics.
CS536 Semantic Analysis Introduction with Emphasis on Name Analysis 1.
Semantic Analysis Semantic Analysis v Lexically and syntactically correct programs may still contain other errors v Lexical and syntax analyses.
CS536 Types 1. Roadmap Back from our LR Parsing Detour Name analysis – Static v dynamic – Scope Today – Type checking 2 Scanner Parser Tokens Semantic.
Compiler Construction Compiler Construction Semantic Analysis I.
Semantic Analysis II. Messages Please check lecturer notices in the Moodle Appeals  Legitimate: “I don’t have the bug you mentioned…”  Illegitimate:
1 A Simple Syntax-Directed Translator CS308 Compiler Theory.
Semantic Analysis III + Intermediate Representation I.
Semantic Analysis II Type Checking EECS 483 – Lecture 12 University of Michigan Wednesday, October 18, 2006.
CS412/413 Introduction to Compilers Radu Rugina Lecture 13 : Static Semantics 18 Feb 02.
Winter Compiler Construction Mooly Sagiv and Roman Manevich School of Computer Science Tel-Aviv University.
CS412/413 Introduction to Compilers Radu Rugina Lecture 11: Symbol Tables 13 Feb 02.
Prof. Necula CS 164 Lecture 171 Operational Semantics of Cool ICOM 4029 Lecture 10.
Scope of Variable. 2 Scope and visibility Scope (visibility) of identifier = portion of program where identifier can be referred to Lexical scope = textual.
Compiler Design Lecture 10 Semantic Analysis. int aintegers int a[2][3]array(2, array(3, integer)) int f(int, float, char) int x float x char  int Int.
CSE 420 Lecture Program is lexically well-formed: ▫Identifiers have valid names. ▫Strings are properly terminated. ▫No stray characters. Program.
Compiler Design Lecture 10 Semantic Analysis. int aintegers int a[2][3]array(2, array(3, integer)) int f(int, float, char) int x float x char  int Int.
LECTURE 10 Semantic Analysis. REVIEW So far, we’ve covered the following: Compilation methods: compilation vs. interpretation. The overall compilation.
Lecture 9 Symbol Table and Attributed Grammars
Chapter 3 – Describing Syntax
Context-Sensitive Analysis
Winter Compiler Construction
Constructing Precedence Table
Semantic Analysis with Emphasis on Name Analysis
Compiler Design 18. Object Oriented Semantic Analysis (Symbol Tables, Type Checking) Kanat Bolazar March 30, 2010.
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
Syntax-Directed Translation
Mooly Sagiv and Roman Manevich School of Computer Science
SYNTAX DIRECTED DEFINITION
COMPILER CONSTRUCTION
Presentation transcript:

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

2 Announcements PA3 will be published next week

3 Today: Static semantics Creating types Type-checking Overall flow of semantic analysis Today IC Language ic Executable code exe Lexical Analysis Syntax Analysis Parsing ASTSymbol Table etc. Inter. Rep. (IR) Code Generation Next time: PA3 – semantic analysis (T6 + T7)

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

6 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;... }...

7 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)

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

9 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; } }... }

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

11 Type judgments 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: b:bool, x:int  b:bool x:int  1 + x < 4:bool foo:int->string, x:int  foo(x) : string

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

13 Some IC expression rules 1 A  true : bool A  E1 : intA  E2 : int A  E1 op E2 : int A  false : bool A  int-literal : int A  string-literal : string op  { +, -, /, *, %} A  E1 : intA  E2 : int A  E1 rop E2 : bool rop  {, >=} A  E1 : TA  E2 : T A  E1 rop E2 : bool rop  { ==,!=}

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

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

16 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

17 45 > 32 && !false BinopExpr UnopExpr BinopExpr … op=AND op=NEG op=GT intLiteral val=45 intLiteral val=32 boolLiteral val=false : int : bool A  false : bool A  int-literal : int A  E1 : intA  E2 : int A  E1 rop E2 : bool rop  {, >=} A  E1 : bool A  E2 : bool A  E1 lop E2 : bool lop  { &&,|| } A  E1 : bool A  !E1 : bool Algorithm example

18 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; }... }

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

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

21 Subtyping Inheritance induces subtyping relation Type hierarchy is a tree (anti-symmetric relation) 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[]

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

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

24 More rules A  S 1 A  S 2 ;…;S n A  S 1 ;…;S n [sequence] E,x 1 :t 1,…, E,x n :t n, ret :t r  S body E  t r m(t 1 x 1,…,t n x n ) {S body } [method] methods(C)={m 1,…,m k } Env(C,m i )  m i for all i=1…k  C [class] classes(P)={C 1,…,C n }  C i for all i=1…n  P [program]

25 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 Disclaimer: This is only a suggestion

26 PA3 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)

27 See you next week