1 Mooly Sagiv and Greta Yorsh School of Computer Science Tel-Aviv University Modern Compiler Design.

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.
Lecture 08a – Backpatching & Recap Eran Yahav 1 Reference: Dragon 6.2,6.3,6.4,6.6.
Compilation (Semester A, 2013/14) Lecture 6b: Context Analysis (aka Semantic Analysis) Noam Rinetzky 1 Slides credit: Mooly Sagiv and Eran Yahav.
Recap 1.Programmer enters expression 2.ML checks if expression is “well-typed” Using a precise set of rules, ML tries to find a unique type for the expression.
Winter Compiler Construction T7 – semantic analysis part II type-checking Mooly Sagiv and Roman Manevich School of Computer Science Tel-Aviv.
Compilation Encapsulation Or: Why Every Component Should Just Do Its Damn Job.
Semantic analysis Parsing only verifies that the program consists of tokens arranged in a syntactically-valid combination, we now move on to semantic analysis,
Objects and Classes David Walker CS 320. Advanced Languages advanced programming features –ML data types, exceptions, modules, objects, concurrency,...
Honors Compilers Semantic Analysis and Attribute Grammars Mar 5th 2002.
1 Semantic Processing. 2 Contents Introduction Introduction A Simple Compiler A Simple Compiler Scanning – Theory and Practice Scanning – Theory and Practice.
Tutorial 6 & 7 Symbol Table
Type Checking in Cool Alex Aiken (Modified by Mooly Sagiv)
Compiler Construction Semantic Analysis I Ran Shaham and Ohad Shacham School of Computer Science Tel-Aviv University.
Semantic analysis Enforce context-dependent language rules that are not reflected in the BNF, e.g.a function must have a return statement. Decorate AST.
Compiler Construction Semantic Analysis II Rina Zviel-Girshin and Ohad Shacham School of Computer Science Tel-Aviv University.
Objects and Classes David Walker CS 320. Advanced Languages advanced programming features –ML data types, exceptions, modules, objects, concurrency,...
Compiler Construction Semantic Analysis I 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 -
Abstract Syntax Trees Lecture 14 Wed, Mar 3, 2004.
1 Abstract Syntax Tree--motivation The parse tree –contains too much detail e.g. unnecessary terminals such as parentheses –depends heavily on the structure.
Semantic Analysis CS 671 February 5, CS 671 – Spring The Compiler So Far Lexical analysis Detects inputs with illegal tokens –e.g.: main$
COMPILERS Semantic Analysis hussein suleman uct csc3005h 2006.
1 Semantic Analysis Aaron Bloomfield CS 415 Fall 2005.
Chapter 6: User-Defined Functions
COMPILERS Symbol Tables hussein suleman uct csc3003s 2007.
CS412/413 Introduction to Compilers and Translators Spring ’99 Lecture 8: Semantic Analysis and Symbol Tables.
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
Compiler Construction Compiler Construction Semantic Analysis I.
Interpretation Environments and Evaluation. CS 354 Spring Translation Stages Lexical analysis (scanning) Parsing –Recognizing –Building parse tree.
Compiler (scalac, gcc) Compiler (scalac, gcc) Id3 = 0 while (id3 < 10) { println(“”,id3); id3 = id3 + 1 } Id3 = 0 while (id3 < 10) { println(“”,id3); id3.
Semantic Analysis. Find 6 problems with this code. These issues go beyond syntax.
Semantic Analysis CPSC 388 Ellen Walker Hiram College.
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
CS536 Semantic Analysis Introduction with Emphasis on Name Analysis 1.
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:
Bernd Fischer RW713: Compiler and Software Language Engineering.
CMSC 330: Organization of Programming Languages Operational Semantics a.k.a. “WTF is Project 4, Part 3?”
Semantic Analysis II Type Checking EECS 483 – Lecture 12 University of Michigan Wednesday, October 18, 2006.
Prof. Fateman CS 164 Lecture 161 Overview of Semantic Analysis Lecture 16.
CMSC 330: Organization of Programming Languages Operational Semantics.
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-
Scope of Variable. 2 Scope and visibility Scope (visibility) of identifier = portion of program where identifier can be referred to Lexical scope = textual.
Semantic Analysis. Find 6 problems with this code. These issues go beyond syntax.
CS 404Ahmed Ezzat 1 CS 404 Introduction to Compiler Design Lecture Ahmed Ezzat.
LECTURE 10 Semantic Analysis. REVIEW So far, we’ve covered the following: Compilation methods: compilation vs. interpretation. The overall compilation.
COMPILERS Semantic Analysis hussein suleman uct csc3003s 2009.
Design issues for Object-Oriented Languages
Lecture 9 Symbol Table and Attributed Grammars
Semantic analysis Jakub Yaghob
Name Spaces: ALL versus OOL
Context-Sensitive Analysis
A Simple Syntax-Directed Translator
Constructing Precedence Table
Semantic Analysis with Emphasis on Name Analysis
Abstract Syntax Trees Lecture 14 Mon, Feb 28, 2005.
Basic Program Analysis: AST
Syntax Errors; Static Semantics
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
UNIT V Run Time Environments.
CS 432: Compiler Construction Lecture 11
COMPILERS Semantic Analysis
Presentation transcript:

1 Mooly Sagiv and Greta Yorsh School of Computer Science Tel-Aviv University Modern Compiler Design T7 – Symbol Tables and Scoping Rules

2 What’s Wrong ? Let y : Int in x + 3 Let y : String  “abc” in y + 3

3 Today Goals:  Semantic checks - scoping rules  Symbol tables Next week  Type checking COOL code txt Executable code exe Lexical Analysis Syntax Analysis Parsing ASTSymbol Table etc. Inter. Rep. (IR) Code Gen.

4 Cool Semantic Analysis ? 1.All identifiers are declared 2.Types 3.Inheritance relations 4.Classes defined only once 5.Methods in a class defined only once 6.Reserved identifiers are not misused 7.Number of arguments (in call) matches the number of formals (in declaration) and the corresponding types 8.…

5 Semantic Analysis Checking for “correct meaning”  Warn about dubious meaning Long-distance and deep relations  Lexer and parser are only short-distance Implemented using AST traversals

6 Scope of an identifier The part of the program in which the identifier is accessible or visible An identifier may have restricted scope Same identifier may refer to different things in different parts of the program Different scopes for same name don’t overlap Not all kinds of identifiers follow the most-closely nested rule

7 Scopes class Foo { value : Int  39; test() : Int { let b:Int  3 in value + b }; setValue(c:Int):Int {{ value  c; let d:Int  c in { c  c + d; value  c; }; }}; }; public class Bar { value:Int  42; setValue(int c):Int { value  c; } scope of value scope of b scope of c scope of value scope of d

8 Where do identifiers come from ? (How do we introduce identifier bindings in Cool ?) Let expressions Formal parameters Attribute definitions Case expressions Class declarations (class names) Method declarations (method names) (object ids)

9 Scope rules Match identifier declarations with uses Why ? for type checking… Let y : String  “abc” in y + 3 Static scope - depends only on the program text, not runtime behavior

10 Scope of Let “most-closely nested” rule let x : Int  0 in { x; let x : Int  2 in x; }

11 Scope of Class Definitions Cannot be nested Globally visible Class name can be used before it is defined Class Foo { … let y : Bar in … } Class Bar { … }

12 Scope of Attributes Global within the class in which they are defined Can be used before defined in the class Class Foo { f() : Int { a }; a : Int  0; }

13 Scope of Methods Method need not be defined in the class in which it is used, but in some parent class Overriding - methods may be redefined class A { foo():Int { …}; }; class B inherits A { }; class C { b : B  new B; bar():Int{ b.foo() }; };

14 Scope of Methods Overriding - methods may be redefined class A { foo():Int { …}; }; class B inherits A { foo():Int {…}; }; class C { b : B  new B; bar():Int{ b.foo() }; };

15 Some Cool Scope Rules local variable declared before use attributes need not be declared before use variables cannot be defined multiple times in same scope, but can be redefined in nested scopes class A { x : String  “a”; foo(x : Int, x : String): SELF_TYPE{ x }; }; it is allowed to shadow method parameters

16 What is Symbol Table ? Scopes implemented using symbol tables Data-structure for “look-up”  key – identifier  value – type of identifier, other semantic properties

17 Symbol Table - 1 st Attempt SymbolKindTypeProperties avarInt… bvarInt… testmethod -> Int… class Test { a: Int  39; test(): Int { let b:Int  3 in a + b };

18 Symbol Table - 1 st Attempt SymbolKindTypeProperties avarInt… bvarInt… testmethod -> Int… avarString… class Test { a: Int  39; test(): Int { let a: String  “hello”, b:Int  3 in b };

19 Implementing Scopes Let x : Int  0 in e before processing e  add definition of x to current definitions  override any other definition of x after processing e  remove definition of x  restore old definition of x

20 Symbol Table – 2 nd Attempt class Foo { value : Int  39; test(b:Int) : Int { value + b }; setValue(c:Int):Int {{ value  c; let d:Int  c in { c  c + d; value  c; }; }}; };

21 Symbol Table – 2 nd Attempt SymbolKindTypeProperties valuevarInt… testmethod-> Int setValuemethodInt -> Int SymbolKindTypeProperties bvarInt… SymbolKindTypeProperties cvarInt… SymbolKindTypeProperties dvarInt… (Foo) (test)(setValue) (setValue-block) …

22 Symbol Table Lookup SymbolKindTypeProperties valuevarint… testmethod-> int setValuemethodint -> int SymbolKindTypeProperties bvarint… SymbolKindTypeProperties cvarint… SymbolKindTypeProperties dvarint… (Foo) (Test)(setValue) (setValue-block) setValue(c:Int):Int {{ value  c; let d :Int  c in { c  c + d; value  c; }; }}; Lookup(value)

23 Symbol Table Lookup SymbolKindTypeProperties valuevarint… testmethod-> int setValuemethodint -> int SymbolKindTypeProperties bvarint… SymbolKindTypeProperties cvarint… SymbolKindTypeProperties dvarint… (Foo) (Test)(setValue) (setValue-block) Lookup(myValue) Error ! setValue(c:Int):Int {{ value  c; let d :Int  c in { c  c + d; myValue  c; }; }};

24 Symbol Table Construction class Foo { value : Int  39; test(b:Int) : Int { value + b; }; setValue(c:Int):Int {{ value  c; let d:Int  c in { c  c + d; value  c; }; }}; }; Method Expr Method Class root name=Foo name=setValue name=test ExprLet Expr id=d (some details omitted)

25 class Symbol Table Construction via AST Traversal Method Expr Method Class root name=Foo name=setValue name=test ExprLet Expr (some details omitted) Symbolkind globals Symbolkind Foo Symbol test Symbol setValue Foo testmethod setValuemethod bvar c Symbol Let dvar id=d

26 class Symbol Table Construction via AST Traversal Method Expr Method Class root name=Foo name=setValue name=test ExprLet Expr (some details omitted) Symbolkind globals Symbolkind Foo Symbol test Symbol setValue Foo testmethod setValuemethod bvar c Symbol Let dvar id=d

27 Implementation SymbolTable.java  symbol table - stack of scopes  scope – hash table  key is AbstractSymbol  value is Object x generic – do we need store and lookup in other cases ? SymtabExample.java

28 Our Implementation Support enterScope()start a new nested scope lookup(x)finds current x (or null) addId(x)adds a symbol x to the table probe(x)true if x defined in current scope exitScope()exit current scope

29 Your Implementation Should … Symbol table key should combine id and kind  separating table in advance according to kinds method, attribute/local variable bindings, classes  implement using 2-level maps (kind->id->value)  implement this using key objects ( (kind,id)->value) )

30 Symbol Tables (cont’d) class A { foo() { bar(); } bar() { … } Program root Class id=A Method id=foo Method id=bar dispatch id=bar() class Symbolkind globals Symbolkind A A foomethod barmethod Undefined identifier bar()

31 Symbol Tables - Naïve solution Building visitor  Propagates (at least) a reference to the symbol table of the current scope  In some cases have to use type information (inherits) Checking visitor  On visit to node – perform check using symbol tables  Resolve identifiers  Try to find symbol in table hierarchy  In some cases have to use global type table and type information  You may postpone these checks

32 Symbol Tables – less naïve solution Use forward references And/or construct some of the symbol table during parsing

33 Symbol Tables (cont’d) class A { foo() { bar(); } bar() { … } Program root Class id=A Method id=foo Method id=bar Dispatch id=bar() class Symbolkind globals SymbolkindFREF A A foomethod barmethodtrue

34 Forward References Optimistically assume that symbol will be eventually defined Update symbol table when symbol defined  Remove forward-reference marker But check correctness when exiting scope  No forward references should exist at exit

35 Passes Can we check class names using symbol table?  No. Can we check class names in one pass ?  No. Semantic analysis requires multiple passes  probably more than 2 for Cool pass 1: gather all class names pass 2: do the checking

36 Inheritance Graph A node in the inheritance graph for each class  Parent and children in the inheritance graph  Predefined classes: Object, IO, Int, etc.  Int, String, Bool can’t be inherited  Is the class reachable/unreachable from the Object class via the "inherits from" relation?  A type checking environment

37 Check Inheritance Graph Local properties  base class is defined  base class can be inherited from  do not require traversing inheritance graph Global properties  find all classes reachable from root class Object  check that it really is a tree (no cycles)

38 Major Semantic Tasks initially the symbol table mapping class names to inheritance graph nodes is empty construct inheritance graph  predefined classes  user-defined classes check inheritance graph build symbol tables of features for each class check for Main class and main method type check all expressions