Symbol Table (  ) Contents Map identifiers to the symbol with relevant information about the identifier All information is derived from syntax tree -

Slides:



Advertisements
Similar presentations
CPSC 388 – Compiler Design and Construction
Advertisements

Symbol Table.
Intermediate Code Generation
Programming Languages and Paradigms
1 Compiler Construction Intermediate Code Generation.
Winter Compiler Construction T7 – semantic analysis part II type-checking Mooly Sagiv and Roman Manevich School of Computer Science Tel-Aviv.
Semantic analysis Parsing only verifies that the program consists of tokens arranged in a syntactically-valid combination, we now move on to semantic analysis,
The Symbol Table Lecture 13 Wed, Feb 23, The Symbol Table When identifiers are found, they will be entered into a symbol table, which will hold.
ISBN Chapter 10 Implementing Subprograms.
Elaboration or: Semantic Analysis Compiler Baojian Hua
Run time vs. Compile time
Environments and Evaluation
Stacks (Revised and expanded from CIT 591). What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on.
Stacks. 2 What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
Stacks. What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
1 Run time vs. Compile time The compiler must generate code to handle issues that arise at run time Representation of various data types Procedure linkage.
Cs164 Prof. Bodik, Fall Symbol Tables and Static Checks Lecture 14.
Attribute Grammars They extend context-free grammars to give parameters to non-terminals, have rules to combine attributes Attributes can have any type,
Chapter TwelveModern Programming Languages1 Memory Locations For Variables.
Chapter 7: Runtime Environment –Run time memory organization. We need to use memory to store: –code –static data (global variables) –dynamic data objects.
Imperative Programming
1 CSC 222: Computer Programming II Spring 2005 Stacks and recursion  stack ADT  push, pop, peek, empty, size  ArrayList-based implementation, java.util.Stack.
COMPILERS Semantic Analysis hussein suleman uct csc3005h 2006.
1 Semantic Analysis Aaron Bloomfield CS 415 Fall 2005.
Compiler Construction
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
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.
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.
CS 153: Concepts of Compiler Design October 5 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
Recap form last time How to do for loops map, filter, reduce Next up: dictionaries.
Exercise Determine the output of the following program assuming static and dynamic scoping. Explain the difference, if there is any. object MyClass { val.
Implementing Subprograms What actions must take place when subprograms are called and when they terminate? –calling a subprogram has several associated.
CS536 Semantic Analysis Introduction with Emphasis on Name Analysis 1.
CS 153: Concepts of Compiler Design October 7 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
Lecture by: Prof. Pooja Vaishnav.  Language Processor implementations are highly influenced by the kind of storage structure used for program variables.
Chapter 1 Introduction Major Data Structures in Compiler
Programming Languages
CSC 8505 Compiler Construction Runtime Environments.
Compiler (scalac, gcc) Compiler (scalac, gcc) I = 0 while (i < 10) { i = i + 1 } I = 0 while (i < 10) { i = i + 1 } source code i d 3 = 0 LF w i d 3 =
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
Bernd Fischer RW713: Compiler and Software Language Engineering.
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
CSE 130 : Winter 2009 Programming Languages Lecture 11: What’s in a Name ?
LECTURE 3 Compiler Phases. COMPILER PHASES Compilation of a program proceeds through a fixed series of phases.  Each phase uses an (intermediate) form.
CS412/413 Introduction to Compilers Radu Rugina Lecture 11: Symbol Tables 13 Feb 02.
Constructs for Data Organization and Program Control, Scope, Binding, and Parameter Passing. Expression Evaluation.
CS 153: Concepts of Compiler Design September 23 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak
Scope of Variable. 2 Scope and visibility Scope (visibility) of identifier = portion of program where identifier can be referred to Lexical scope = textual.
1 Compiler Construction Run-time Environments,. 2 Run-Time Environments (Chapter 7) Continued: Access to No-local Names.
Lecture 9 Symbol Table and Attributed Grammars
CS Data Structures Chapter 6 Stacks Mehmet H Gunes
Names and Attributes Names are a key programming language feature
A Simple Syntax-Directed Translator
Constructing Precedence Table
Semantic Analysis with Emphasis on Name Analysis
CS 153: Concepts of Compiler Design October 5 Class Meeting
CMPE 152: Compiler Design October 4 Class Meeting
Chapter 6 Intermediate-Code Generation
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
UNIT V Run Time Environments.
CMPE 152: Compiler Design March 7 Class Meeting
Symbol Table 薛智文 (textbook ch#2.7 and 6.5) 薛智文 96 Spring.
COMPILERS Semantic Analysis
Presentation transcript:

Symbol Table (  ) Contents Map identifiers to the symbol with relevant information about the identifier All information is derived from syntax tree - symbol table is for efficiency –in old one-pass compilers there was only symbol table, no syntax tree –in modern compiler: we could always go through entire tree, but symbol table can give faster and easier access to the part of syntax tree, or some additional information Goal: efficiently supporting phases of compiler In the name analysis phase: –finding which identifier refers to which definition –we store definitions What kinds of things can we define? What do we need to know for each ID? variables (globals, fields, parameters, locals): –need to know types, positions - for error messages –later: memory layout. To compile x.f = y into memcopy(addr_y, addr_x+6, 4) e.g. 3rd field in an object should be stored at offset e.g. +6 from the address of the object the size of data stored in x.f is 4 bytes –sometimes more information explicit: whether variable local or global methods, functions, classes: recursively have with their own symbol tables

Different Points, Different  class World { int sum; void add(int foo) { sum = sum + foo; } void sub(int bar) { sum = sum - bar; } int count; }

Imperative Way: Push and Pop class World { int sum; void add(int foo) { sum = sum + foo; } void sub(int bar) { sum = sum - bar; } int count; } change table, record change revert changes from table change table, record change revert changes from table

Imperative Symbol Table Hash table, mutable Map[ID,Symbol] Example: –hash function into array –array has linked list storing (ID,Symbol) pairs Undo stack: to enable entering and leaving scope Entering new scope (function,block): –add beginning-of-scope marker to undo stack Adding nested declaration (ID,sym) –lookup old value symOld, push old value to undo stack –insert (ID,sym) into table Leaving the scope –go through undo stack until the marker, restore old values

Functional: Keep Old Version class World { int sum; void add(int foo) { sum = sum + foo; } void sub(int bar) { sum = sum - bar; } int count; } create new  1, keep old  0

Functional Symbol Table Implemented Typical: Immutable Balanced Search Trees Updating returns new map, keeping old one –lookup and update both log(n) –update creates new path (copy log(n) nodes, share rest!) –memory usage acceptable sealedsealed abstract class BST case class Empty() extends BST case class Node(left: BST, value: Int, right: BST) extends BSTabstractclass caseclassextends caseclassextends Simplified. In practice, BST[A], store Int key and value A

Lookup defdef contains(key: Int, t : BST): Boolean = t match { case Empty() => false case Node(left,v,right) => { if (key == v) true else if (key < v) contains(key, left) else contains(key, right) } }matchcasefalsecaseiftrueelseifelse Running time bounded by tree height. contains(6,t) ?

Insertion defdef add(x : Int, t : BST) : Node = t match { case Empty() => Node(Empty(),x,Empty()) case Node(left,v,right) => { if (x < v) Node(add(x, left), v, right) else if (x==v) t else Node(left, v, add(x, right)) } }matchcase ifelseifelse Both add(x,t) and t remain accessible. Running time and newly allocated nodes bounded by tree height.

Balanced Trees: Red-Black Trees

Balanced Tree: Red Black Tree Goals: ensure that tree height remains at most log(size) add(1,add(2,add(3,...add(n,Empty())...))) ~ linked list preserve efficiency of individual operations: rebalancing arbitrary tree: could cost O(n) work Solution: maintain mostly balanced trees: height still O(log size) sealedsealed abstract class Color case class Red() extends Color case class Black() extends Colorabstractclass caseclassextends caseclassextends sealedsealed abstract class Tree case class Empty() extends Tree case class Node(c: Color,left: Tree,value: Int, right: Tree) extends Treeabstractclass caseclassextends caseclass extends

balanced tree constraints From 4. and 5.: tree height is O(size). Analysis is similar for mutable and immutable trees. for immutable trees: see book by Chris Okasaki

Balancing defdef balance(c: Color, a: Tree, x: Int, b: Tree): Tree = (c,a,x,b) match { case (Black(),Node(Red(),Node(Red(),a,xV,b),yV,c),zV,d) => Node(Red(),Node(Black(),a,xV,b),yV,Node(Black(),c,zV,d))matchcase case (Black(),Node(Red(),a,xV,Node(Red(),b,yV,c)),zV,d) => Node(Red(),Node(Black(),a,xV,b),yV,Node(Black(),c,zV,d))case case (Black(),a,xV,Node(Red(),Node(Red(),b,yV,c),zV,d)) => Node(Red(),Node(Black(),a,xV,b),yV,Node(Black(),c,zV,d)) case (Black(),a,xV,Node(Red(),b,yV,Node(Red(),c,zV,d))) => Node(Red(),Node(Black(),a,xV,b),yV,Node(Black(),c,zV,d)) case (c,a,xV,b) => Node(c,a,xV,b) }case

Insertion defdef add(x: Int, t: Tree): Tree = { def ins(t: Tree): Tree = t match { case Empty() => Node(Red(),Empty(),x,Empty()) case Node(c,a,y,b) => if (x < y) balance(c, ins(a), y, b) else if (x == y) Node(c,a,y,b) else balance(c,a,y,ins(b)) } makeBlack(ins(t)) }defmatchcase ifelseifelse defdef makeBlack(n: Tree): Tree = n match { case Node(Red(),l,v,r) => Node(Black(),l,v,r) case _ => n }matchcase Modern object-oriented languages (=Scala) support abstraction and functional data structures. Just use Map from Scala.

Compiler (scalac, gcc) Compiler (scalac, gcc) Id3 = 0 while (id3 < 10) { println(“”,id3); id3 = id3 + 1 } Id3 = 0 while (id3 < 10) { println(“”,id3); id3 = id3 + 1 } source code Compiler Construction i d 3 = 0 LF w i d 3 = 0 LF w id3 = 0 while ( id3 < 10 ) id3 = 0 while ( id3 < 10 ) lexer characters words (tokens) trees parser assign while i 0 + * 3 7i assign a[i] < i 10 making sense of trees

Evaluating an Expression scala prompt: >def min1(x : Int, y : Int) : Int = { if (x min1(10,5) res1: Int = 6 How can we think about this evaluation? x  10 y  5 if (x < y) x else y+1

Each Value has a Type scala prompt: >def min1(x : Int, y : Int) : Int = { if (x min1(10,5) res1: Int = 6 How can we think about this evaluation? x : Int  10 y : Int  5 if (x < y) x else y+1

We can compute types without values scala prompt: >def min1(x : Int, y : Int) : Int = { if (x min1(10,5) res1: Int = 6 How can we think about this evaluation? x : Int y : Int if (x < y) x else y+1

We do not like trees upside-down

Leaves are Up type rules move from leaves to root

Type Rules as Local Tree Constraints x : Int y : Int Type Rules for every type T, if then b has type Boolean, and...

Type Rules with Environment x : Int y : Int Type Rules

if the free variables of e have types given by gamma, then e (correctly) type checks and has type T If e 1 type checks in gamma and has type T 1 and... and e n type checks in gamma and has type T n then e type checks in gamma and has type T

Derivation Using Type Rules x : Int y : Int

Type Rule for Function Application We can treat operators as variables that have function type We can replace many previous rules with application rule:

Computing the Environment of a Class object World { var data : Int var name : String def m(x : Int, y : Int) : Boolean {... } def n(x : Int) : Int { if (x > 0) p(x – 1) else 3 } def p(r : Int) : Int = { var k = r + 2 m(k, n(k)) } } Type check each function m,n,p in this global environment

Extending the Environment class World { var data : Int var name : String def m(x : Int, y : Int) : Boolean {... } def n(x : Int) : Int { if (x > 0) p(x – 1) else 3 } def p(r : Int) : Int = { var k:Int = r + 2 m(k, n(k)) } }

Type Checking Expression in a Body class World { var data : Int var name : String def m(x : Int, y : Int) : Boolean {... } def n(x : Int) : Int { if (x > 0) p(x – 1) else 3 } def p(r : Int) : Int = { var k:Int = r + 2 m(k, n(k)) } }

Remember Function Updates

Type Rule for Method Bodies Type Rule for Assignments Type Rules for Block: { var x 1 :T 1... var x n :T n ; s 1 ;... s m ; e }

Blocks with Declarations in the Middle just expression empty declaration is first statement is first

Rule for While Statement

Rule for Method Call

Example to Type Check class World { var z : Boolean var u : Int def f(y : Boolean) : Int { z = y if (u > 0) { u = u – 1 var z : Int z = f(!y) + 3 z+z } else { 0 } }