Scope of Variable. 2 Scope and visibility Scope (visibility) of identifier = portion of program where identifier can be referred to Lexical scope = textual.

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.
Objects and Classes David Walker CS 320. Advanced Languages advanced programming features –ML data types, exceptions, modules, objects, concurrency,...
1 Mooly Sagiv and Greta Yorsh School of Computer Science Tel-Aviv University Modern Compiler Design.
Chapter 8 Scope, Lifetime and More on Functions. Definitions Scope –The region of program code where it is legal to reference (use) an identifier Three.
Winter Compiler Construction T7 – semantic analysis part II type-checking Mooly Sagiv and Roman Manevich School of Computer Science Tel-Aviv.
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.
Tutorial 6 & 7 Symbol Table
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 I Ran Shaham and Ohad Shacham School of Computer Science Tel-Aviv University.
Run time vs. Compile time
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.
Chapter 2 A Simple Compiler
Compilation 2007 Scopes and Environments Michael I. Schwartzbach BRICS, University of Aarhus.
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 -
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.
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.
COMPILERS Semantic Analysis hussein suleman uct csc3005h 2006.
Semantics CSE 340 – Principles of Programming Languages Fall 2015 Adam Doupé Arizona State University
1 Semantic Analysis Aaron Bloomfield CS 415 Fall 2005.
Names and Scope. Scope Suppose that a name is used many times for different entities in text of the program, or in the course of execution. When the name.
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.
Basic Semantics Associating meaning with language entities.
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.
Contextual Analysis (Chapter 5) 1 Course Overview PART I: overview material 1Introduction 2Language processors (tombstone diagrams, bootstrapping) 3Architecture.
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.
Semantics CSE 340 – Principles of Programming Languages Fall 2015 Adam Doupé Arizona State University
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.
Semantic Analysis II Type Checking EECS 483 – Lecture 12 University of Michigan Wednesday, October 18, 2006.
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-
CS 153: Concepts of Compiler Design September 23 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
CSc 453 Semantic Analysis Saumya Debray The University of Arizona Tucson.
©2004 Joel Jones 1 CS 403: Programming Languages Lecture 3 Fall 2004 Department of Computer Science University of Alabama Joel Jones.
Semantic Analysis. Find 6 problems with this code. These issues go beyond syntax.
COMPILERS Semantic Analysis hussein suleman uct csc3003s 2009.
Design issues for Object-Oriented Languages
Lecture 9 Symbol Table and Attributed Grammars
Name Spaces: ALL versus OOL
Context-Sensitive Analysis
Constructing Precedence Table
Semantic Analysis with Emphasis on Name Analysis
Basic Program Analysis: AST
Compiler Design 18. Object Oriented Semantic Analysis (Symbol Tables, Type Checking) Kanat Bolazar March 30, 2010.
Syntax Errors; Static Semantics
Scope of Variables.
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
UNIT V Run Time Environments.
CS 432: Compiler Construction Lecture 11
COMPILERS Semantic Analysis
SYMBOL TABLE Chuen-Liang Chen Department of Computer Science
Presentation transcript:

Scope of Variable

2 Scope and visibility Scope (visibility) of identifier = portion of program where identifier can be referred to Lexical scope = textual region in the program Statement block Method body Class body Module / package / file Whole program (multiple modules)

3 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 { int value; void setValue(int c) { value = c; test(); } scope of field value scope of local variable b scope of formal parameter c scope of c scope of value scope of local variable in statement block d scope of method test

4 Scope nesting Scopes may be enclosed in other scopes void foo() { int a; … {int a;} } Name disambiguation Generally scope hierarchy forms a tree Scope of subclass enclosed in scope of its superclass Subtype relation must be acyclic same name but different symbol

5 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 in code block of body method Code block scope Variables defined in block

6 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.” … (Section 10 in IC specification) How do we check these rules?

Symbol Table Basics 7

8 Symbol table An environment that stores information about identifiers A data structure that captures scope information Each entry in symbol table contains The name of an identifier Its kind (variable/method/field…) Type Additional properties, e.g., final, public (not needed for IC) One symbol table for each scope

9 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 Scope nesting mirrored in hierarchy of symbol tables

10 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 { int value; void setValue(int c) { value = c; } scope of value scope of b scope of c scope of value scope of d Symbol table example block1

11 SymbolKindTypeProperties valuefieldint… testmethod-> int setValuemethodint -> void SymbolKindTypeProperties bvarint… SymbolKindTypeProperties cvarint… SymbolKindTypeProperties dvarint… (Foo) (test) … Symbol table example cont. (setValue) (block1)

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

13 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

14 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?

15 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

16 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

17 Symbol table implementation Each table in the hierarchy could be implemented using java.util.HashMap Implement a hierarchy of symbol tables Can implement a Symbol class Use in subsequent phases instead of id name A programming note: HashMap keys should obey equals / hashcode contracts Safe when key is symbol name ( String )

18 Implementing table structure Hierarchy of symbol tables Pointer to enclosing table Can also keep list of sub-tables Symbol table key should include id and kind Can implement using 2-level maps (kind->id->entry) Separating table in advance according to kinds also acceptable

19 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? We will see two solutions

20 Solution 1 – multiple phases Multiple phase solution Building visitor Checking visitor Building visitor On visit to node – build corresponding symbol table class, method, block (and possibly nested blocks) Can maintain stack of symbol tables Push new table when entering scope Pop when exiting scope Link AST node to symbol table of corresponding scope Do not perform any checks

21 Building and checking Building visitor A propagating visitor Propagates reference to the symbol table of the current scope (or use table stack) In some cases have to use type information ( extends ) Populate tables with declarations/definitions Class definitions, method definitions, field definitions, variable declarations, formal arguments class A {void foo(){int B; int[] C;}}; Checking visitor On visit to node – perform check using symbol tables Resolve identifiers Look for symbol in table hierarchy

22 class MethodDecl Stmt 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 test() unresolved symbol

23 class MethodDecl Stmt 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 resolved symbols Checking phase test()

24 Forward references – solution 2 Use forward reference marker (flag) Optimistically assume that symbol will be eventually defined Update symbol table when symbol defined Remove forward-reference marker Count unresolved symbols and upon exit check that #unresolved=0 And/or construct some of the symbol table during parsing

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

Next-Symbol Table representation 26