Presentation is loading. Please wait.

Presentation is loading. Please wait.

Compiler Construction Compiler Construction Semantic Analysis I.

Similar presentations


Presentation on theme: "Compiler Construction Compiler Construction Semantic Analysis I."— Presentation transcript:

1 Compiler Construction Compiler Construction Semantic Analysis I

2 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.

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

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

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

7 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

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

10 Semantic Analysis

11 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 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 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 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 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 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 17 Scope nesting Scopes may be enclosed in other scopes void foo(){ int a; … { int a; } } same name but different symbol

18 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 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 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 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 22 Symbol table An environment that stores information about identifiers A data structure that captures scope information SymbolKindTypeProperties valuefieldint… testmethod-> intprivate setValuemethodint -> voidpublic

23 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 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 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 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 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 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 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 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 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 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 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 34 Symbol table implementation Using java.util.HashMap  HashMap keys should obey equals / hashcode contracts  Safe when key is symbol name ( String )

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


Download ppt "Compiler Construction Compiler Construction Semantic Analysis I."

Similar presentations


Ads by Google