Compiler Construction Compiler Construction Semantic Analysis I.

Slides:



Advertisements
Similar presentations
Winter Compiler Construction T6 – semantic analysis part I scopes and symbol tables Mooly Sagiv and Roman Manevich School of Computer Science.
Advertisements

CPSC 388 – Compiler Design and Construction
Semantic Analysis and Symbol Tables
Symbol Table.
1 Mooly Sagiv and Greta Yorsh School of Computer Science Tel-Aviv University Modern Compiler Design.
Winter Compiler Construction T7 – semantic analysis part II type-checking Mooly Sagiv and Roman Manevich School of Computer Science Tel-Aviv.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Compiler Construction LR(0) + Visitor Ran Shaham and Ohad Shacham School of Computer Science Tel-Aviv University.
Compiler Construction Abstract Syntax Tree Ran Shaham and Ohad Shacham School of Computer Science Tel-Aviv University.
Tutorial 6 & 7 Symbol Table
Compiler Construction Semantic Analysis I Ran Shaham and Ohad Shacham School of Computer Science Tel-Aviv University.
Compiler Construction Abstract Syntax Tree Rina Zviel-Girshin and Ohad Shacham School of Computer Science Tel-Aviv University.
Compiler Construction Semantic Analysis II Ran Shaham and Ohad Shacham School of Computer Science Tel-Aviv University.
Environments and Evaluation
Compiler Construction Semantic Analysis II Rina Zviel-Girshin and Ohad Shacham School of Computer Science Tel-Aviv University.
Chapter 2 A Simple Compiler
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
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.
Attribute Grammars They extend context-free grammars to give parameters to non-terminals, have rules to combine attributes Attributes can have any type,
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.
CSc 453 Semantic Analysis Saumya Debray The University of Arizona Tucson.
1 Abstract Syntax Tree--motivation The parse tree –contains too much detail e.g. unnecessary terminals such as parentheses –depends heavily on the structure.
CPSC 388 – Compiler Design and Construction Parsers – Context Free Grammars.
Semantic Analysis Legality checks –Check that program obey all rules of the language that are not described by a context-free grammar Disambiguation –Name.
OOPs Object oriented programming. Based on ADT principles  Representation of type and operations in a single unit  Available for other units to create.
Semantic Analysis CS 671 February 5, CS 671 – Spring The Compiler So Far Lexical analysis Detects inputs with illegal tokens –e.g.: main$
Chapter 1 Introduction Dr. Frank Lee. 1.1 Why Study Compiler? To write more efficient code in a high-level language To provide solid foundation in parsing.
COMPILERS Semantic Analysis hussein suleman uct csc3005h 2006.
1 Semantic Analysis Aaron Bloomfield CS 415 Fall 2005.
COMPILERS Symbol Tables hussein suleman uct csc3003s 2007.
CS412/413 Introduction to Compilers and Translators Spring ’99 Lecture 8: Semantic Analysis and Symbol Tables.
MIT Intermediate Formats Martin Rinard Laboratory for Computer Science Massachusetts Institute of Technology.
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.
Semantic Analysis. Find 6 problems with this code. These issues go beyond syntax.
Compiler Construction Dr. Noam Rinetzky and Orr Tamir School of Computer Science Tel Aviv University
Chapter 2. Design of a Simple Compiler J. H. Wang Sep. 21, 2015.
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.
Winter Compiler Construction T5 – AST Mooly Sagiv and Roman Manevich School of Computer Science Tel-Aviv University.
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 II Type Checking EECS 483 – Lecture 12 University of Michigan Wednesday, October 18, 2006.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
CS412/413 Introduction to Compilers Radu Rugina Lecture 11: Symbol Tables 13 Feb 02.
6. Semantic Analysis. Semantic Analysis Phase – Purpose: compute additional information needed for compilation that is beyond the capabilities of Context-
Abstract Syntax Tree. 2 Compiler IC Program ic x86 executable exe Lexical Analysis Syntax Analysis Parsing ASTSymbol Table etc. Inter. Rep. (IR) Code.
Syntax-Directed Definitions CS375 Compilers. UT-CS. 1.
MiniJava Compiler A multi-back-end JIT compiler of Java.
CSc 453 Semantic Analysis Saumya Debray The University of Arizona Tucson.
Scope of Variable. 2 Scope and visibility Scope (visibility) of identifier = portion of program where identifier can be referred to Lexical scope = textual.
Lecture 9 Symbol Table and Attributed Grammars
Chapter 7 User-Defined Methods.
A Simple Syntax-Directed Translator
Constructing Precedence Table
Java Primer 1: Types, Classes and Operators
Semantic Analysis with Emphasis on Name Analysis
Compiler Design 18. Object Oriented Semantic Analysis (Symbol Tables, Type Checking) Kanat Bolazar March 30, 2010.
Syntax Errors; Static Semantics
Java Programming Language
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
CSE401 Introduction to Compiler Construction
Winter Compiler Construction T5 – AST
COMPILERS Semantic Analysis
Presentation transcript:

Compiler Construction Compiler Construction Semantic Analysis I

PA 1 2 Solution must compile Ant Parser, Ant Build => Try outside Eclipse! Turn in all files needed for project to compile (including build.xml) Fail program only on critical errors. User code having errors is not a reason to fail. Output errors and gracefully return 0. Your compiler should not crash. Your printouts should match given outputs. Use diff. Pay attention to what goes on in the forum. Our instructions in response to questions in the forum must be followed.

PAs Groups Mails PA2  Syntax analysis & AST construction  3 weeks 3

4 Compiler IC Program ic x86 executable exe Lexical Analysis Syntax Analysis Parsing AST Symbol Table etc. Inter. Rep. (IR) Code Generation IC compiler Visitor Scopes Symbol table Agenda:

5 Separate operations on objects of a data structure from object representation Each operation (pass) may be implemented as separate visitor Use double-dispatch to find right method for object Visitor Pattern

Visitor pattern in Java 6 interface Visitor { visit(A a); visit(B b); visit(C c); } class A { A x; accept(Visitor v) { v.visit(this); } } class B { accept(Visitor v) { v.visit(this); } } class op1 implements Visitor { visit(A a) {…} visit(B b) {…} visit(C c) {…} } × class op2 implements Visitor { visit(A a) {…} visit(B b) {…} visit(C c) {…} } class op3 implements Visitor { visit(A a) {…} visit(B b) {…} visit(C c) {…} } class C { accept(Visitor v) { v.visit(this); } }

Double dispatch example 7 Visitor v = new op1(); // op1/2/3 x = ???? // x can be A/B/C x.accept(v); class op1 implements Visitor { visit(A a) { } visit(B b) { … } } class B { accept(Visitor v) { // always calls visit(B b) v.visit(this); } } 1 st dispatch 2 nd dispatch

Straight Line Program example 8 prog  stmt_list stmt_list  stmt stmt_list  stmt_list stmt stmt  var = expr; stmt  print(expr); expr  expr + expr expr  expr - expr expr  expr * expr expr  expr / expr expr  - expr expr  ( expr ) expr  number expr  readi() expr  var ASTNode StmtExpr PrintStmt AssignStmt BinaryOpExpr UnaryOpExpr NumberExpr ReadIExpr StmtList VarExpr (Code available on web site. Demonstrates scanning, parsing, AST + visitors)web site

9 Visitor variations interface PropagatingVisitor { /** Visits a statement node with a given * context object (book-keeping) * and returns the result * of the computation on this node. */ Object visit(Stmt st, Object context); Object visit(Expr e, Object context); Object visit(BinaryOpExpr e, Object context);... } Propagate values down the AST (and back) SLPEvaluator example

Semantic Analysis

11 Semantic analysis: motivation Syntax analysis is not enough int a; a = “hello”; int a; b = 1; Assigning wrong type Assigning undeclared variable int a; int a; a = 1; Variable re declaration

12 Goals of semantic analysis Check “correct” use of programming constructs Context sensitive  Beyond context-free grammars  Deeper analysis than lexical and syntax analysis Semantic rules for checking correctness  Scope rules  Type-checking rules  Other specific rules Guarantee partial correctness  Runtime checks  pointer dereferencing  array access ……

13 Semantic rules: examples A variable must be declared before being used A variable should not be declared multiple times A variable should be initialized before being used Non-void method should contain return statement along all execution paths break / continue statements allowed only in loops this keyword cannot be used in static method main method should have specific signature

14 Example of semantic rules Type rules are an important class of semantic rules  In an assignment, RHS and LHS must have the same type  The type of a conditional test expression must be Boolean

15 Scope Scope of identifier  portion of program where identifier can be referred to Scope  Statement block  Method body  Class body  Module / package / file  Whole program (multiple modules)

16 Scope example class Foo { int value; int test() { int b = 3; return value + b; } void setValue(int c) { value = c; { int d = c; c = c + d; value = c; } class Bar extends Foo { void setValue(int c) { value = c; test(); } scope of local variable b scope of formal parameter c scope of c scope of local variable in statement block d scope of method test scope of field value

17 Scope nesting Scopes may be enclosed in other scopes void foo(){ int a; … { int a; } } same name but different symbol

18 Scope tree Generally scope hierarchy forms a tree class Foo { int value; int test() { int b = 3; return value + b; } void setValue(int c) { value = c; { int d = c; c = c + d; value = c; } Foo value test b setValue c block I d block I

19 Subclasses Scope of subclass enclosed in scope of its superclass  Subtype relation must be acyclic Class Foo { int a; } Class Bar extends Foo { } Bar sees “a” as well

20 Scope hierarchy in IC Global scope  The names of all classes defined in the program Class scope  Instance scope: all fields and methods of the class  Static scope: all static methods  Scope of subclass nested in scope of its superclass Method scope  Formal parameters and local variables Code block scope  Variables defined in block

21 Scope rules in IC “When resolving an identifier at a certain point in the program, the enclosing scopes are searched for that identifier.” “local variables and method parameters can only be used after they are defined in one of the enclosing block or method scopes.” “Fields and virtual methods can be used in expressions of the form e.f or e.m() when e has class type C and the instance scope of C contains those fields and methods.” “ static methods can be used in expressions of the form C.m() if the static scope of C contains m.” …

22 Symbol table An environment that stores information about identifiers A data structure that captures scope information SymbolKindTypeProperties valuefieldint… testmethod-> intprivate setValuemethodint -> voidpublic

23 Symbol table Each entry in symbol table contains  name of an identifier  kind (variable/method/field…)  Type (int, string, myClass…)  Additional properties, e.g., final, public One symbol table for each scope

24 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

25 class Foo { int value; int test() { int b = 3; return value + b; } void setValue(int c) { value = c; { int d = c; c = c + d; value = c; } scope of value scope of b scope of c scope of d Symbol table example block1

26 class Foo { int value; int test() { int b = 3; return value + b; } void setValue(int c) { value = c; { int d = c; c = c + d; value = c; } Symbol table example SymbolKindTypeProperties valuefieldint… testmethod-> int setValuemethodint -> void (Foo) SymbolKindTypeProperties bvarint… (test) SymbolKindTypeProperties cvarint… (setValue) SymbolKindTypeProperties dvarint… (block1)

27 Checking scope rules SymbolKindTypeProperties valuefieldint… testmethod-> int setValuemethodint -> void SymbolKindTypeProperties bvarint… SymbolKindTypeProperties cvarint… SymbolKindTypeProperties dvarint… (Foo) (test)(setValue) (block1) void setValue(int c) { value = c; { int d = c; c = c + d; value = c; } lookup(value)

28 SymbolKindTypeProperties valuefieldint… testmethod-> int setValuemethodint -> void SymbolKindTypeProperties bvarint… SymbolKindTypeProperties cvarint… SymbolKindTypeProperties dvarint… (Foo) (test)(setValue) (block1) void setValue(int c) { value = c; { int d = c; c = c + d; myValue = c; } lookup(myValue) Error ! undefined symbol Catching semantic errors

29 Symbol table operations insert  Insert new symbol (to current scope) lookup  Try to find a symbol in the table  May cause lookup in parent tables  Report an error when symbol not found How do we check illegal re-definitions?

30 class MethodDecl Stmt MethodDecl ClassDecl root name=Foo name=setValue name=test VarDecl id=b StmtBlock Stmt VarDecl id=d Symbolkind globals Symbolkind Foo Symbol test Symbol setValue Foo testmethod setValuemethod bvar c Symbol block1 dvar Symbol table construction via AST traversal

31 class MethodDecl Stmt MethodDecl ClassDecl root name=Foo name=setValue name=test VarDecl id=b StmtBlock Stmt VarDecl id=d Symbolkind globals Symbolkind Foo Symbol test Symbol setValue Foo testmethod setValuemethod bvar c Symbol block1 dvar Linking AST nodes to enclosing table

32 public abstract class ASTNode { /** line in source program **/ private int line; /** reference to symbol table of enclosing scope **/ private SymbolTable enclosingScope; /** accept visitor **/ public abstract void accept(Visitor v); /** accept propagating visitor **/ public abstract U accept(PropagatingVisitor v,D context); /** return line number of this AST node in program **/ public int getLine() {…} /** returns symbol table of enclosing scope **/ public SymbolTable enclosingScope() {…} } What’s in an AST node

33 Symbol table implementation public class SymbolTable { /** map from String to Symbol **/ private Map entries; private String id; private SymbolTable parentSymbolTable; public SymbolTable(String id) { this.id = id; entries = new HashMap (); } … } public class Symbol { private String id; private Type type; private Kind kind; … }

34 Symbol table implementation Using java.util.HashMap  HashMap keys should obey equals / hashcode contracts  Safe when key is symbol name ( String )

35 Forward references class A { void foo() { bar(); } void bar() { … } Program root ClassDecl id=A MethodDecl id=foo retType=void MethodDecl id=bar retType=void Call id=bar() class Symbolkind globals Symbolkind A A foomethod barmethod Undefined identifier bar() bar used before encountered declaration How do we handle forward references?

36 Multiple phases Building visitor  A propagating visitor  Propagates reference to the symbol table of the current scope Checking visitor  On visit to node  perform check using symbol tables  Resolve identifiers  Look for symbol in table hierarchy

37 class MethodDecl ClassDecl root name=Foo name=setValue name=test VarDecl id=b StmtBlock Stmt VarDecl id=d Symbolkind globals Symbolkind Foo SymbolKind test Symbolkind setValue Foo testmethod setValuemethod bvar c Symbolkind block1 dvar Building phase unresolved symbol Stmt setValue()

38 class MethodDecl ClassDecl root name=Foo name=setValue name=test VarDecl id=b StmtBlock Stmt VarDecl id=d Symbolkind globals Symbolkind Foo SymbolKind test Symbolkind setValue Foo testmethod setValuemethod bvar c Symbolkind block1 dvar Checking phase Stmt setValue()

39 Forward references – solution 2 Use forward reference marker Update symbol table when symbol defined  Remove forward-reference marker Count unresolved symbols Upon exit check that #unresolved=0

40 Forward reference flag example class A { void foo() { bar(); } void bar() { … } Program root ClassDecl id=A MethodDecl id=foo retType=void MethodDecl id=bar retType=void Call id=bar() class Symbolkind globals SymbolkindFREF A A foomethod barmethodtrue