Attribute Grammars. Attribute Grammars

Size: px
Start display at page:

Download "Attribute Grammars. Attribute Grammars"

Transcription

1 Attribute Grammars Definitions: synthesized, inherited, dependence graph Example: syntax-directed translation S-attributed grammars -attributed grammars Bottom Up euation of inherited attributes Top Down translation Attribute Grammars! BGR, Fall05 Attribute Grammars Attributes: properties associated with nonterminal symbols of a context free grammar E.G., Binary numbers. B " 0 (B) = 0 2. B " (B) = 3. " B () = (B); len() = 4. " B () = 2*( ) + (B) len() = len( ) + Semantic rules defining attributes are side-effect free 5. N " (N) = (); len(n) = len() Attribute Grammars! BGR, Fall05 2

2 Parse Tree of 0 2 N, len Represent dependences between semantic functions of attributes, len, len B,len B B 0 Attribute Grammars! BGR, Fall05 3 Dependence Graph: acyclic, euated in topsort order, contains attribute instances Euate(Decorate) Parse Tree Initial ues N, len, len,len B, len B B 0 Attribute Grammars! BGR, Fall05 4 0

3 Euate Euate Parse Tree,len B N 5, len 2, len B 0 5, len Attribute Grammars! BGR, Fall05 5 B 0 Euate Parse Tree Euate len; Full euation yields (N) = 5; len(n) = 3. N, len, len 2, len B 3 3,len B B 0 Attribute Grammars! BGR, Fall05 6

4 Classifications Inherited attributes: Values based on attributes of parent (HS nonterminal) or siblings (nonterminals on RHS of same production Synthesized attributes: Values based on attributes of descendents (child nonterminals in same production) Attribute Grammars! BGR, Fall05 7 Classifications ocal context: always within focus of a single production Dependence edges go only one level in parse tree Terminals can be associated with ues returned by the scanner Distinguished nonterminal cannot have inherited attributes Attribute Grammars! BGR, Fall05 8

5 Example - Identifiers Identifiers with no letters repeated (e.g., moon - illegal, money - legal) D " I str(i) = {}; (D) = (I); accept, if (D)!= error I " I str() = str(i); str(i ) = (); (I) = (I ) I " str() = str(i); (I) = () " a b z () = concatenation of returned by scanner to str(), if this character is not a repeated letter, else error. (note: any comparison to error returns error.) Attribute Grammars! BGR, Fall05 9 Inherited Attributes D " I str(i) = {}; (D) = (I); accept, if (D)!= error I " I str() = str(i); str(i ) = (); (I) = (I ) I " str() = str(i); (I) = () " a b z () = concatenation of returned by scanner to str(), if this character is not a repeated letter, else error. (note: any comparison to error returns error.) Attribute Grammars! BGR, Fall05 0

6 Synthesized Attributes D " I str(i) = {}; (D) = (I); accept, if (D)!= error I " I str() = str(i); str(i ) = (); (I) = (I ) I " str() = str(i); (I) = () " a b z () = concatenation of returned by scanner to str(), if this character is not a repeated letter, else error. (note: any comparison to error returns error.) Attribute Grammars! BGR, Fall05 Parse Tree of abc D I str a str I str str I str b str Attribute Grammars! BGR, Fall05 2 c

7 Decorated Parse Tree a D I abc str abc I str str abc a a ab I str str a ab b str ab abc abc Attribute Grammars! BGR, Fall05 3 c symb is the symbol table gathered from the declarations and checked in the <declarations> statements. Compiler Example <Pgm> symb <body> symb Int-decl symb <assign_stmt> symb Integer <decl-list> symb <id> := <expr> <id>, <decl-list> symb symb symb symb <id> <id>, <decl-list> symb symb symb <id> symb Attribute Grammars! BGR, Fall05 4

8 Syntax-directed Translation Idea: to use attribute grammars to cover some of the context-sensitive issues in translation Syntax-directed definition: an attributed grammar such that every grammar symbol has an attribute. Conceptually, attribute euation is Build parse tree Find attribute dependences Decorate parse tree Attribute Grammars! BGR, Fall05 5 Euation Methods Want to interleave attribute euation with parsing Use dependence graph (but cannot handle circular dependences) Predetermine euation order at compiler construction time, using knowledge of grammar Ad-hoc: chosen parsing method imposes eution order when interleaved with parsing; restricts grammars that can be handled Attribute Grammars! BGR, Fall05 6

9 S-attributed Grammars S-attributed grammars: all attributes are synthesized Easy to interleave with BU parsing by using a parallel stack for attribute ues Euate as do a reduction Important: can code semantic functions a priori, because know all the handles from the grammar, so know where the associated attributes will be in the stack when a reduction is about to take place. Attribute Grammars! BGR, Fall05 7 Attribute Grammars Attributes: properties associated with nonterminal symbols of a context free grammar E.G., Binary numbers. B " 0 (B) = 0 2. B " (B) = 3. " B () = (B); len() = 4. " B () = 2*( ) + (B) len() = len( ) + Semantic rules defining attributes are side-effect free 5. N " (N) = (); len(n) = len() Attribute Grammars! BGR, Fall05 8

10 Example - Binary Nos. B " 0 (B) = 0 2. B " (B) = 3. " B () = (B); len() = 4. " B () = 2*( ) + (B) len() = len( ) + 5. N " (N) = (); len(n) = len() Stack Input $ $ shift $ (B _) $ red(2), find B $ ( ) $ red(3), find $ ( ) ( _) $ shift $ ( ) (B _) $ red(2), find B $ ( 3 2) $ red (5), find $ (N 3 2) $ accept (<symbol> () len()) Attribute Grammars! BGR, Fall05 9 -attributed Grammars Every attribute in the grammar is synthesized, or for production A " X X k an inherited attribute X k only depends on attributes of X X k- or inherited attributes of A. Can use depth-first euation scheme on parse tree Includes all syntax-directed definitions from () grammars Attribute Grammars! BGR, Fall05 20

11 -attributed Grammars Translation scheme: embeds semantic actions to euate attributes in RHS of productions (use { } to delimit actions) to accomplish depth-first euation order. An inherited attributed for a nonterminal on RHS of production, must be computed in an action BEFORE that symbol Attribute Grammars! BGR, Fall05 2 -attributed Grammars 2. An action cannot refer to a synthesized attribute of a symbol to the right of the action 3. A synthesized attribute of the HS nonterminal can only be computed after all attributes it refers to are computed; place this action at the end of the RHS of the production Attribute Grammars! BGR, Fall05 22

12 Example - Identifiers as a Translation Scheme D " {str(i) = # } I {(D) = (I)} {accept, if (D)!= error} I " { str() = str(i)} {str(i ) = ()!} I {(I) = (I )} I " { str() = str(i) } {(I) = ()} " a b z {() = concatenation of returned by scanner to str(), if this character is not a repeated letter, else error} Try to euate earlier example abc with depth-first walk and these rules. Attribute Grammars! BGR, Fall05 23 Intuition Can see TD parsing relates well to -attributed grammars Can see BU parsing relates well to S-attributed grammars Attribute Grammars! BGR, Fall05 24

13 BU E of Inherited Attribs Idea: transform grammar so all embedded actions of translation scheme occur at end of RHS of some production (at a reduction) without changing R(k) nature of the grammar Can handle all -attributed defns corresponding to () grammars plus some R() Attribute Grammars! BGR, Fall05 25 Marker Nonterminals Used to move all actions to end of RHS of productions Always X " # for X, a marker nonterminal. Replace an embedded action by a unique marker nonterminal that generates # Make the action for that nonterminal the same as the embedded action removed But: grammar must stay R(k) after these changes (this needs to be checked.) anguage accepted is same. Actions occur in same order during parse. Attribute Grammars! BGR, Fall05 26

14 Example, ASU p 309 S " E E " E + T E - T T T " num S " E E " T R R " + T { print + } R R " - T { print - } R R " # T " num {print num} becomes after recursion remo with actions: Attribute Grammars! BGR, Fall05 27 R() grammar Marker Nonterminals After transformation S " E S " E E " T R E " T R R " + T { print + } R R " +! T M R R " - T { print - } R R " - T N R R " # R " # T " num {print num} M " # { print + } N " # {print - } T " num {print num} Attribute Grammars! BGR, Fall05 28

15 Marker Nonterminals (Copies) Handling copy rules with marker nonterminals A " X Y where i(y) = s(x) Translation scheme would be: A " X {i(y) = s(x)} Y Example of this in our identifier grammar str(i ) = () in I " I would become I " {str(i ) = ()} I Attribute Grammars! BGR, Fall05 29 Example D I a I a ab Attribute Grammars! BGR, Fall05 30 b

16 Example Stack Input Attribute Stack $ a b $ $ $ a b $ $ $ b $ a (()) $ b $ a $ $ ab (( )) $ I $ ab ((I)) $ I $ ab ((I)) $ D $ ab ((D)) Attribute Grammars! BGR, Fall05 3 Marker Nonterminals,(Copies ii) In previous example, copies never need to be performed as ue is at top of attribute stack due to shape of grammar rules Not always this lucky S " a A C i(c) = s(a) [.] S " b A B C i(c) = s(a) [2.] C " c s(c) = g (i(c)) Problem: in., s(a) is in stack(top) when find C but in 2., s(a) is in stack(top-). Must rewrite grammar to try to make attribute ue end up in same place in both rules. Attribute Grammars! BGR, Fall05 32

17 Grammar Transformation S " a A C i(c) = s(a) [.] S " b A B M C i(m) = s(a); i(c) = s(m) [2. ] C " c s(c) = g (i(c)) M " # s(m) = i(m) M saves the ue of s(a) so it goes on the ue stack at the same place in both rules., 2. ; when encounter C, makes i(c) in same stack position. Attribute Grammars! BGR, Fall05 33 Marker Nonterminals,, (Non-copies) Previous transformation works even for non-copy actions: if S " b A C has action i(c) = f(s(a)) then s(a) is on stack, not f(s(a)). Fix: S " a A N C, i(n) = s(a), i(c) = s(n) N " #, s(n) = f(i(n)) Problem: can destroy the R() property of grammar with added markers; () grammars remain okay. Attribute Grammars! BGR, Fall05 34

18 Top Down Translation -attributed grammars work well with TD translation, but when remove left recursion must also transform attributes Involves changing all synthesized attributes to a mixture of inherited and synthesized Attribute Grammars! BGR, Fall05 35 S " E E " E + T E " E - T E " T T " int Example (S) = (E) (E) = (E ) + (T) (E) = (E ) - (T) (E) = (T) (T) = int_ue All synthesized attributes (-attributed). Attribute Grammars! BGR, Fall05 36

19 Removing eft Recursion E " E $ % & " % A; A " $ ' # E E E E $ $ becomes % $ A A % $ A Want to specify attribute transformations as well! # Attribute Grammars! BGR, Fall05 37 Example S " E {(S) = (E)} E " T {i(r) = (T)} R {(E) = s(r)} R " + T {i(r ) = i(r) + (T)} R {s(r) = s(r )} R " - T { i(r ) = i(r) - (T)} R {s(r) = s(r )} R " # {s(r) = i(r)} T " int {(T) = int_const} Attribute Grammars! BGR, Fall05 38

20 Corresponding Parse Trees E S + ( S E E - ( int(4) T R i s va l ( int(3) int(2) - T R i s int (2) int(3) + T R i s int(4) Attribute Grammars! BGR, Fall05 39 # Transformation, ASUp304ff A " A Y {a(a)= g(a(a ), y(y))} A " X {a(a) = f(x(x))} Becomes A " X {i(r) = f(x(x))} R { a(a) = s(r)} R " Y {i(r ) = g(i(r), y(y))} R {s(r) = s(r )} R " # {s(r) = i(r)} Attribute Grammars! BGR, Fall05 40

21 A A f(x(x)) A Y Transformation g{g(f(x(x)),y(y )),y(y 2 )} Y 2 g(f(x(x)),y(y )) X Y A R R g{g(f(x(x)),y(y )),y(y 2 )} f(x(x)) g(f(x(x)),y(y )) X Y 2 R g(g(f(x(x)),y(y )),y(y 2 )) # Attribute Grammars! BGR, Fall05 4

Syntactic Directed Translation

Syntactic Directed Translation Syntactic Directed Translation Translation Schemes Copyright 2016, Pedro C. Diniz, all rights reserved. Students enrolled in the Compilers class at the University of Southern California have explicit permission

More information

Syntax-Directed Translation Part I

Syntax-Directed Translation Part I 1 Syntax-Directed Translation Part I Chapter 5 COP5621 Compiler Construction Copyright Robert van Engelen, Florida State University, 2007-2011 2 The Structure of our Compiler Revisited Character stream

More information

Syntax-Directed Translation Part II

Syntax-Directed Translation Part II Syntax-Directed Translation Part II Chapter 5 Slides adapted from : Robert van Engelen, Florida State University Alessandro Artale, Free University of Bolzano Syntax-Directed Translation Schemes Syntax-directed

More information

LL(k) Parsing. Predictive Parsers. LL(k) Parser Structure. Sample Parse Table. LL(1) Parsing Algorithm. Push RHS in Reverse Order 10/17/2012

LL(k) Parsing. Predictive Parsers. LL(k) Parser Structure. Sample Parse Table. LL(1) Parsing Algorithm. Push RHS in Reverse Order 10/17/2012 Predictive Parsers LL(k) Parsing Can we avoid backtracking? es, if for a given input symbol and given nonterminal, we can choose the alternative appropriately. his is possible if the first terminal of

More information

Syntax-Directed Translation

Syntax-Directed Translation Syntax-Directed Translation 1 Syntax-Directed Translation 1. We associate information with the programming language constructs by attaching attributes to grammar symbols. 2. Values of these attributes

More information

More Assigned Reading and Exercises on Syntax (for Exam 2)

More Assigned Reading and Exercises on Syntax (for Exam 2) More Assigned Reading and Exercises on Syntax (for Exam 2) 1. Read sections 2.3 (Lexical Syntax) and 2.4 (Context-Free Grammars) on pp. 33 41 of Sethi. 2. Read section 2.6 (Variants of Grammars) on pp.

More information

[Syntax Directed Translation] Bikash Balami

[Syntax Directed Translation] Bikash Balami 1 [Syntax Directed Translation] Compiler Design and Construction (CSc 352) Compiled By Central Department of Computer Science and Information Technology (CDCSIT) Tribhuvan University, Kirtipur Kathmandu,

More information

Syntax-Directed Translation. Introduction

Syntax-Directed Translation. Introduction Syntax-Directed Translation Introduction Translation of languages guided by context-free grammars Attach attributes to the grammar symbols Values of the attributes are computed by semantic rules associated

More information

Syntax Directed Translation

Syntax Directed Translation Syntax Directed Translation Beyond syntax analysis An identifier named x has been recognized. Is x a scalar, array or function? How big is x? If x is a function, how many and what type of arguments does

More information

COMP 181. Prelude. Prelude. Summary of parsing. A Hierarchy of Grammar Classes. More power? Syntax-directed translation. Analysis

COMP 181. Prelude. Prelude. Summary of parsing. A Hierarchy of Grammar Classes. More power? Syntax-directed translation. Analysis Prelude COMP 8 October, 9 What is triskaidekaphobia? Fear of the number s? No aisle in airplanes, no th floor in buildings Fear of Friday the th? Paraskevidedekatriaphobia or friggatriskaidekaphobia Why

More information

Semantic analysis. Syntax tree is decorated with typing- and other context dependent

Semantic analysis. Syntax tree is decorated with typing- and other context dependent Semantic analysis Semantic analysis Semantic analysis checks for the correctness of contextual dependences: { nds correspondence between declarations and usage of identiers, { performs type checking/inference,

More information

Syntax Directed Translation

Syntax Directed Translation Syntax Directed Translation Rupesh Nasre. CS3300 Compiler Design IIT Madras Aug 2015 Character stream Lexical Analyzer Machine-Independent Code Optimizer F r o n t e n d Token stream Syntax Analyzer Syntax

More information

Compilers. 5. Attributed Grammars. Laszlo Böszörmenyi Compilers Attributed Grammars - 1

Compilers. 5. Attributed Grammars. Laszlo Böszörmenyi Compilers Attributed Grammars - 1 Compilers 5. Attributed Grammars Laszlo Böszörmenyi Compilers Attributed Grammars - 1 Adding Attributes We connect the grammar rules with attributes E.g. to implement type-checking or code generation A

More information

CS 406: Syntax Directed Translation

CS 406: Syntax Directed Translation CS 406: Syntax Directed Translation Stefan D. Bruda Winter 2015 SYNTAX DIRECTED TRANSLATION Syntax-directed translation the source language translation is completely driven by the parser The parsing process

More information

Chapter 4 :: Semantic Analysis

Chapter 4 :: Semantic Analysis Chapter 4 :: Semantic Analysis Programming Language Pragmatics, Fourth Edition Michael L. Scott Copyright 2016 Elsevier 1 Chapter04_Semantic_Analysis_4e - Tue November 21, 2017 Role of Semantic Analysis

More information

RYERSON POLYTECHNIC UNIVERSITY DEPARTMENT OF MATH, PHYSICS, AND COMPUTER SCIENCE CPS 710 FINAL EXAM FALL 96 INSTRUCTIONS

RYERSON POLYTECHNIC UNIVERSITY DEPARTMENT OF MATH, PHYSICS, AND COMPUTER SCIENCE CPS 710 FINAL EXAM FALL 96 INSTRUCTIONS RYERSON POLYTECHNIC UNIVERSITY DEPARTMENT OF MATH, PHYSICS, AND COMPUTER SCIENCE CPS 710 FINAL EXAM FALL 96 STUDENT ID: INSTRUCTIONS Please write your student ID on this page. Do not write it or your name

More information

Syntax-Directed Translation

Syntax-Directed Translation Syntax-Directed Translation ALSU Textbook Chapter 5.1 5.4, 4.8, 4.9 Tsan-sheng Hsu tshsu@iis.sinica.edu.tw http://www.iis.sinica.edu.tw/~tshsu 1 What is syntax-directed translation? Definition: The compilation

More information

More On Syntax Directed Translation

More On Syntax Directed Translation More On Syntax Directed Translation 1 Types of Attributes We have productions of the form: A X 1 X 2 X 3... X n with semantic rules of the form: b:= f(c 1, c 2, c 3,..., c n ) where b and the c s are attributes

More information

Summary: Semantic Analysis

Summary: Semantic Analysis Summary: Semantic Analysis 1 Basic Concepts When SA is performed: Semantic Analysis may be performed: In a two-pass compiler: after syntactic analysis is finished, the semantic analyser if called with

More information

Syntax-Directed Translation. CS Compiler Design. SDD and SDT scheme. Example: SDD vs SDT scheme infix to postfix trans

Syntax-Directed Translation. CS Compiler Design. SDD and SDT scheme. Example: SDD vs SDT scheme infix to postfix trans Syntax-Directed Translation CS3300 - Compiler Design Syntax Directed Translation V. Krishna Nandivada IIT Madras Attach rules or program fragments to productions in a grammar. Syntax directed definition

More information

A Simple Syntax-Directed Translator

A Simple Syntax-Directed Translator Chapter 2 A Simple Syntax-Directed Translator 1-1 Introduction The analysis phase of a compiler breaks up a source program into constituent pieces and produces an internal representation for it, called

More information

Part 5 Program Analysis Principles and Techniques

Part 5 Program Analysis Principles and Techniques 1 Part 5 Program Analysis Principles and Techniques Front end 2 source code scanner tokens parser il errors Responsibilities: Recognize legal programs Report errors Produce il Preliminary storage map Shape

More information

Abstract Syntax Trees & Top-Down Parsing

Abstract Syntax Trees & Top-Down Parsing Review of Parsing Abstract Syntax Trees & Top-Down Parsing Given a language L(G), a parser consumes a sequence of tokens s and produces a parse tree Issues: How do we recognize that s L(G)? A parse tree

More information

10/18/18. Outline. Semantic Analysis. Two types of semantic rules. Syntax vs. Semantics. Static Semantics. Static Semantics.

10/18/18. Outline. Semantic Analysis. Two types of semantic rules. Syntax vs. Semantics. Static Semantics. Static Semantics. Outline Semantic Analysis In Text: Chapter 3 Static semantics Attribute grammars Dynamic semantics Operational semantics Denotational semantics N. Meng, S. Arthur 2 Syntax vs. Semantics Syntax concerns

More information

Parsing. Handle, viable prefix, items, closures, goto s LR(k): SLR(1), LR(1), LALR(1)

Parsing. Handle, viable prefix, items, closures, goto s LR(k): SLR(1), LR(1), LALR(1) TD parsing - LL(1) Parsing First and Follow sets Parse table construction BU Parsing Handle, viable prefix, items, closures, goto s LR(k): SLR(1), LR(1), LALR(1) Problems with SLR Aho, Sethi, Ullman, Compilers

More information

Introduction to Syntax Directed Translation and Top-Down Parsers

Introduction to Syntax Directed Translation and Top-Down Parsers Introduction to Syntax Directed Translation and Top-Down Parsers 1 Attributes and Semantic Rules Let s associate attributes with grammar symbols, and semantic rules with productions. This gives us a syntax

More information

Parsing II Top-down parsing. Comp 412

Parsing II Top-down parsing. Comp 412 COMP 412 FALL 2018 Parsing II Top-down parsing Comp 412 source code IR Front End Optimizer Back End IR target code Copyright 2018, Keith D. Cooper & Linda Torczon, all rights reserved. Students enrolled

More information

If you are going to form a group for A2, please do it before tomorrow (Friday) noon GRAMMARS & PARSING. Lecture 8 CS2110 Spring 2014

If you are going to form a group for A2, please do it before tomorrow (Friday) noon GRAMMARS & PARSING. Lecture 8 CS2110 Spring 2014 1 If you are going to form a group for A2, please do it before tomorrow (Friday) noon GRAMMARS & PARSING Lecture 8 CS2110 Spring 2014 Pointers. DO visit the java spec website 2 Parse trees: Text page 592

More information

CS 441G Fall 2018 Exam 1 Matching: LETTER

CS 441G Fall 2018 Exam 1 Matching: LETTER CS 441G Fall 2018 Exam 1 Matching: match the best term from the following list to its definition by writing the LETTER of the term in the blank to the left of the definition. All 31 definitions are given

More information

Abstract Syntax Trees & Top-Down Parsing

Abstract Syntax Trees & Top-Down Parsing Abstract Syntax Trees & Top-Down Parsing Review of Parsing Given a language L(G), a parser consumes a sequence of tokens s and produces a parse tree Issues: How do we recognize that s L(G)? A parse tree

More information

Abstract Syntax Trees & Top-Down Parsing

Abstract Syntax Trees & Top-Down Parsing Review of Parsing Abstract Syntax Trees & Top-Down Parsing Given a language L(G), a parser consumes a sequence of tokens s and produces a parse tree Issues: How do we recognize that s L(G)? A parse tree

More information

CSE P 501 Exam 11/17/05 Sample Solution

CSE P 501 Exam 11/17/05 Sample Solution 1. (8 points) Write a regular expression or set of regular expressions that generate the following sets of strings. You can use abbreviations (i.e., name = regular expression) if it helps to make your

More information

Grammars & Parsing. Lecture 12 CS 2112 Fall 2018

Grammars & Parsing. Lecture 12 CS 2112 Fall 2018 Grammars & Parsing Lecture 12 CS 2112 Fall 2018 Motivation The cat ate the rat. The cat ate the rat slowly. The small cat ate the big rat slowly. The small cat ate the big rat on the mat slowly. The small

More information

COP5621 Exam 3 - Spring 2005

COP5621 Exam 3 - Spring 2005 COP5621 Exam 3 - Spring 2005 Name: (Please print) Put the answers on these sheets. Use additional sheets when necessary. Show how you derived your answer when applicable (this is required for full cred

More information

CPS 506 Comparative Programming Languages. Syntax Specification

CPS 506 Comparative Programming Languages. Syntax Specification CPS 506 Comparative Programming Languages Syntax Specification Compiling Process Steps Program Lexical Analysis Convert characters into a stream of tokens Lexical Analysis Syntactic Analysis Send tokens

More information

Context-sensitive Analysis

Context-sensitive Analysis Context-sensitive Analysis Beyond Syntax There is a level of correctness that is deeper than grammar fie(a,b,c,d) int a, b, c, d; { } fee() { int f[3],g[0], h, i, j, k; char *p; fie(h,i, ab,j, k); k =

More information

Abstract Syntax Tree

Abstract Syntax Tree Abstract Syntax Tree Condensed form of parse tree, useful for representing language constructs. The production S if B then s1 else s2 may appear as if-then-else B s1 s2 1 Abstract Syntax tree Chain of

More information

Compiler Principle and Technology. Prof. Dongming LU April 15th, 2019

Compiler Principle and Technology. Prof. Dongming LU April 15th, 2019 Compiler Principle and Technology Prof. Dongming LU April 15th, 2019 PART TWO 6. Semantic Analysis Contents Part One 6.1 Attributes and Attribute Grammars Part Two 6.2 Algorithms for Attribute Computation

More information

Semantic Analysis with Attribute Grammars Part 1

Semantic Analysis with Attribute Grammars Part 1 with Attribute Grammars Part 1 Department of Computer Science and Automation Indian Institute of Science Bangalore 560 012 NPTEL Course on Principles of Compiler Design Outline of the Lecture Introduction

More information

QUESTIONS RELATED TO UNIT I, II And III

QUESTIONS RELATED TO UNIT I, II And III QUESTIONS RELATED TO UNIT I, II And III UNIT I 1. Define the role of input buffer in lexical analysis 2. Write regular expression to generate identifiers give examples. 3. Define the elements of production.

More information

Chapter 3: Describing Syntax and Semantics. Introduction Formal methods of describing syntax (BNF)

Chapter 3: Describing Syntax and Semantics. Introduction Formal methods of describing syntax (BNF) Chapter 3: Describing Syntax and Semantics Introduction Formal methods of describing syntax (BNF) We can analyze syntax of a computer program on two levels: 1. Lexical level 2. Syntactic level Lexical

More information

Syntax-Directed Translation

Syntax-Directed Translation Syntax-Directed Translation 1 Syntax-Directed Translation 2 Syntax-Directed Translation 3 Syntax-Directed Translation In a syntax-directed definition, each production A α is associated with a set of semantic

More information

Lecture 14 Sections Mon, Mar 2, 2009

Lecture 14 Sections Mon, Mar 2, 2009 Lecture 14 Sections 5.1-5.4 Hampden-Sydney College Mon, Mar 2, 2009 Outline 1 2 3 4 5 Parse A parse tree shows the grammatical structure of a statement. It includes all of the grammar symbols (terminals

More information

Context-sensitive Analysis. Copyright 2003, Keith D. Cooper, Ken Kennedy & Linda Torczon, all rights reserved.

Context-sensitive Analysis. Copyright 2003, Keith D. Cooper, Ken Kennedy & Linda Torczon, all rights reserved. Context-sensitive Analysis Copyright 2003, Keith D. Cooper, Ken Kennedy & Linda Torczon, all rights reserved. Beyond Syntax There is a level of correctness that is deeper than grammar fie(a,b,c,d) int

More information

Chapter 4 - Semantic Analysis. June 2, 2015

Chapter 4 - Semantic Analysis. June 2, 2015 Chapter 4 - Semantic Analysis June 2, 2015 The role of the semantic analyzer Compilers use semantic analysis to enforce the static semantic rules of a language It is hard to generalize the exact boundaries

More information

We now allow any grammar symbol X to have attributes. The attribute a of symbol X is denoted X.a

We now allow any grammar symbol X to have attributes. The attribute a of symbol X is denoted X.a Attribute Grammars Attribute Grammars were invented by Don Knuth as a way to unify all of the stages of compiling into one. They give a formal way to pass semantic information (types, values, etc.) around

More information

Test I Solutions MASSACHUSETTS INSTITUTE OF TECHNOLOGY Spring Department of Electrical Engineering and Computer Science

Test I Solutions MASSACHUSETTS INSTITUTE OF TECHNOLOGY Spring Department of Electrical Engineering and Computer Science Department of Electrical Engineering and Computer Science MASSACHUSETTS INSTITUTE OF TECHNOLOGY 6.035 Spring 2013 Test I Solutions Mean 83 Median 87 Std. dev 13.8203 14 12 10 8 6 4 2 0 0 10 20 30 40 50

More information

Defining Languages GMU

Defining Languages GMU Defining Languages CS463 @ GMU How do we discuss languages? We might focus on these qualities: readability: how well does a language explicitly and clearly describe its purpose? writability: how expressive

More information

Programming Languages and Compilers (CS 421)

Programming Languages and Compilers (CS 421) Programming Languages and Compilers (CS 421) Sasa Misailovic 4110 SC, UIUC https://courses.engr.illinois.edu/cs421/fa2017/cs421a Based in part on slides by Mattox Beckman, as updated by Vikram Adve, Gul

More information

Programming Languages and Compilers (CS 421)

Programming Languages and Compilers (CS 421) Programming Languages and Compilers (CS 421) Elsa L Gunter 2112 SC, UIUC http://courses.engr.illinois.edu/cs421 Based in part on slides by Mattox Beckman, as updated by Vikram Adve and Gul Agha 10/31/17

More information

Syntax Analysis Check syntax and construct abstract syntax tree

Syntax Analysis Check syntax and construct abstract syntax tree Syntax Analysis Check syntax and construct abstract syntax tree if == = ; b 0 a b Error reporting and recovery Model using context free grammars Recognize using Push down automata/table Driven Parsers

More information

Semantic actions for expressions

Semantic actions for expressions Semantic actions for expressions Semantic actions Semantic actions are routines called as productions (or parts of productions) are recognized Actions work together to build up intermediate representations

More information

Syntax-Directed Translation

Syntax-Directed Translation Syntax-Directed Translation What is syntax-directed translation? The compilation process is driven by the syntax. The semantic routines perform interpretation based on the syntax structure. Attaching attributes

More information

Lecture Overview Code generation in milestone 2 o Code generation for array indexing o Some rational implementation Over Express Over o Creating

Lecture Overview Code generation in milestone 2 o Code generation for array indexing o Some rational implementation Over Express Over o Creating 1 ecture Overview Code generation in milestone 2 o Code generation for array indexing o Some rational implementation Over Express Over o Creating records for arrays o Short-circuiting Or o If statement

More information

SEMANTIC ANALYSIS TYPES AND DECLARATIONS

SEMANTIC ANALYSIS TYPES AND DECLARATIONS SEMANTIC ANALYSIS CS 403: Type Checking Stefan D. Bruda Winter 2015 Parsing only verifies that the program consists of tokens arranged in a syntactically valid combination now we move to check whether

More information

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Compiler Design

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Compiler Design i About the Tutorial A compiler translates the codes written in one language to some other language without changing the meaning of the program. It is also expected that a compiler should make the target

More information

Action Table for CSX-Lite. LALR Parser Driver. Example of LALR(1) Parsing. GoTo Table for CSX-Lite

Action Table for CSX-Lite. LALR Parser Driver. Example of LALR(1) Parsing. GoTo Table for CSX-Lite LALR r Driver Action Table for CSX-Lite Given the GoTo and parser action tables, a Shift/Reduce (LALR) parser is fairly simple: { S 5 9 5 9 void LALRDriver(){ Push(S ); } R S R R R R5 if S S R S R5 while(true){

More information

Principles of Programming Languages

Principles of Programming Languages Principles of Programming Languages h"p://www.di.unipi.it/~andrea/dida2ca/plp- 14/ Prof. Andrea Corradini Department of Computer Science, Pisa Lesson 11! Syntax- Directed Transla>on The Structure of the

More information

Using an LALR(1) Parser Generator

Using an LALR(1) Parser Generator Using an LALR(1) Parser Generator Yacc is an LALR(1) parser generator Developed by S.C. Johnson and others at AT&T Bell Labs Yacc is an acronym for Yet another compiler compiler Yacc generates an integrated

More information

Semantic Analysis. Role of Semantic Analysis

Semantic Analysis. Role of Semantic Analysis Semantic Analysis Chapter 4 Role of Semantic Analysis Following parsing, the next two phases of the "typical" compiler are semantic analysis (intermediate) code generation The principal job of the semantic

More information

LECTURE 7. Lex and Intro to Parsing

LECTURE 7. Lex and Intro to Parsing LECTURE 7 Lex and Intro to Parsing LEX Last lecture, we learned a little bit about how we can take our regular expressions (which specify our valid tokens) and create real programs that can recognize them.

More information

Syntax-Directed Translation. Concepts Introduced in Chapter 5. Syntax-Directed Definitions

Syntax-Directed Translation. Concepts Introduced in Chapter 5. Syntax-Directed Definitions Concepts Introduced in Chapter 5 Syntax-Directed Definitions Translation Schemes Synthesized Attributes Inherited Attributes Dependency Graphs Syntax-Directed Translation Uses a grammar to direct the translation.

More information

Formal Languages. Formal Languages

Formal Languages. Formal Languages Regular expressions Formal Languages Finite state automata Deterministic Non-deterministic Review of BNF Introduction to Grammars Regular grammars Formal Languages, CS34 Fall2 BGRyder Formal Languages

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Context Free Grammars and Parsing 1 Recall: Architecture of Compilers, Interpreters Source Parser Static Analyzer Intermediate Representation Front End Back

More information

2.2 Syntax Definition

2.2 Syntax Definition 42 CHAPTER 2. A SIMPLE SYNTAX-DIRECTED TRANSLATOR sequence of "three-address" instructions; a more complete example appears in Fig. 2.2. This form of intermediate code takes its name from instructions

More information

LECTURE NOTES ON COMPILER DESIGN P a g e 2

LECTURE NOTES ON COMPILER DESIGN P a g e 2 LECTURE NOTES ON COMPILER DESIGN P a g e 1 (PCCS4305) COMPILER DESIGN KISHORE KUMAR SAHU SR. LECTURER, DEPARTMENT OF INFORMATION TECHNOLOGY ROLAND INSTITUTE OF TECHNOLOGY, BERHAMPUR LECTURE NOTES ON COMPILER

More information

Introduction to Syntax Analysis. The Second Phase of Front-End

Introduction to Syntax Analysis. The Second Phase of Front-End Compiler Design IIIT Kalyani, WB 1 Introduction to Syntax Analysis The Second Phase of Front-End Compiler Design IIIT Kalyani, WB 2 Syntax Analysis The syntactic or the structural correctness of a program

More information

Chapter 3 (part 3) Describing Syntax and Semantics

Chapter 3 (part 3) Describing Syntax and Semantics Chapter 3 (part 3) Describing Syntax and Semantics Chapter 3 Topics Introduction The General Problem of Describing Syntax Formal Methods of Describing Syntax Attribute Grammars Describing the Meanings

More information

COLLEGE OF ENGINEERING, NASHIK. LANGUAGE TRANSLATOR

COLLEGE OF ENGINEERING, NASHIK. LANGUAGE TRANSLATOR Pune Vidyarthi Griha s COLLEGE OF ENGINEERING, NASHIK. LANGUAGE TRANSLATOR By Prof. Anand N. Gharu (Assistant Professor) PVGCOE Computer Dept.. 22nd Jan 2018 CONTENTS :- 1. Role of lexical analysis 2.

More information

Parsing - 1. What is parsing? Shift-reduce parsing. Operator precedence parsing. Shift-reduce conflict Reduce-reduce conflict

Parsing - 1. What is parsing? Shift-reduce parsing. Operator precedence parsing. Shift-reduce conflict Reduce-reduce conflict Parsing - 1 What is parsing? Shift-reduce parsing Shift-reduce conflict Reduce-reduce conflict Operator precedence parsing Parsing-1 BGRyder Spring 99 1 Parsing Parsing is the reverse of doing a derivation

More information

COP PRINCIPLES OF PROGRAMMING LANGUAGES NOTES ON ATTRIBUTE GRAMMARS.

COP PRINCIPLES OF PROGRAMMING LANGUAGES NOTES ON ATTRIBUTE GRAMMARS. COP 5555 - PRINCIPLES OF PROGRAMMING LANGUAGES NOTES ON ATTRIBUTE GRAMMARS. I. Introduction. These notes are intended to supplement class lectures on attribute grammars. We will begin with functional graphs,

More information

Intermediate Formats. for object oriented languages

Intermediate Formats. for object oriented languages Intermediate Formats for object oriented languages Program Representation Goals Enable Program Analysis and Transformation Semantic Checks, Correctness Checks, Optimizations Structure Translation to Machine

More information

Final Term Papers 2013

Final Term Papers 2013 Solved by: Sahar (well wisher) Class BSCS 6 th Semester Subject CS606 (COMPILER CONSTRUCTION) Solution Type: Final Term Solved Subjective including Papers of Year : 2013,2012,2011,2010,2009 2006 Institute:

More information

Principles of Programming Languages COMP251: Syntax and Grammars

Principles of Programming Languages COMP251: Syntax and Grammars Principles of Programming Languages COMP251: Syntax and Grammars Prof. Dekai Wu Department of Computer Science and Engineering The Hong Kong University of Science and Technology Hong Kong, China Fall 2007

More information

Semantic actions for declarations and expressions

Semantic actions for declarations and expressions Semantic actions for declarations and expressions Semantic actions Semantic actions are routines called as productions (or parts of productions) are recognized Actions work together to build up intermediate

More information

Examples of attributes: values of evaluated subtrees, type information, source file coordinates,

Examples of attributes: values of evaluated subtrees, type information, source file coordinates, 1 2 3 Attributes can be added to the grammar symbols, and program fragments can be added as semantic actions to the grammar, to form a syntax-directed translation scheme. Some attributes may be set by

More information

CMPT 379 Compilers. Parse trees

CMPT 379 Compilers. Parse trees CMPT 379 Compilers Anoop Sarkar http://www.cs.sfu.ca/~anoop 10/25/07 1 Parse trees Given an input program, we convert the text into a parse tree Moving to the backend of the compiler: we will produce intermediate

More information

CSE 12 Abstract Syntax Trees

CSE 12 Abstract Syntax Trees CSE 12 Abstract Syntax Trees Compilers and Interpreters Parse Trees and Abstract Syntax Trees (AST's) Creating and Evaluating AST's The Table ADT and Symbol Tables 16 Using Algorithms and Data Structures

More information

SYED AMMAL ENGINEERING COLLEGE (An ISO 9001:2008 Certified Institution) Dr. E.M. Abdullah Campus, Ramanathapuram

SYED AMMAL ENGINEERING COLLEGE (An ISO 9001:2008 Certified Institution) Dr. E.M. Abdullah Campus, Ramanathapuram CS6660 COMPILER DESIGN Question Bank UNIT I-INTRODUCTION TO COMPILERS 1. Define compiler. 2. Differentiate compiler and interpreter. 3. What is a language processing system? 4. List four software tools

More information

Abstract Syntax Trees Synthetic and Inherited Attributes

Abstract Syntax Trees Synthetic and Inherited Attributes Abstract Syntax Trees Synthetic and Inherited Attributes Lecture 22 Sections 5.1-5.2 Robb T. Koether Hampden-Sydney College Mon, Mar 16, 2015 Robb T. Koether (Hampden-Sydney College)Abstract Syntax TreesSynthetic

More information

Introduction to Syntax Analysis

Introduction to Syntax Analysis Compiler Design 1 Introduction to Syntax Analysis Compiler Design 2 Syntax Analysis The syntactic or the structural correctness of a program is checked during the syntax analysis phase of compilation.

More information

Semantic actions for declarations and expressions. Monday, September 28, 15

Semantic actions for declarations and expressions. Monday, September 28, 15 Semantic actions for declarations and expressions Semantic actions Semantic actions are routines called as productions (or parts of productions) are recognized Actions work together to build up intermediate

More information

Chapter 3. Describing Syntax and Semantics

Chapter 3. Describing Syntax and Semantics Chapter 3 Describing Syntax and Semantics Chapter 3 Topics Introduction The General Problem of Describing Syntax Formal Methods of Describing Syntax Attribute Grammars Describing the Meanings of Programs:

More information

CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages CS 314 Principles of Programming Languages Lecture 5: Syntax Analysis (Parsing) Zheng (Eddy) Zhang Rutgers University January 31, 2018 Class Information Homework 1 is being graded now. The sample solution

More information

COP4020 Programming Languages. Semantics Robert van Engelen & Chris Lacher

COP4020 Programming Languages. Semantics Robert van Engelen & Chris Lacher COP4020 Programming Languages Semantics Robert van Engelen & Chris Lacher Overview Static semantics Dynamic semantics Attribute grammars Abstract syntax trees Static Semantics Syntax concerns the form

More information

Parsers. Xiaokang Qiu Purdue University. August 31, 2018 ECE 468

Parsers. Xiaokang Qiu Purdue University. August 31, 2018 ECE 468 Parsers Xiaokang Qiu Purdue University ECE 468 August 31, 2018 What is a parser A parser has two jobs: 1) Determine whether a string (program) is valid (think: grammatically correct) 2) Determine the structure

More information

CS606- compiler instruction Solved MCQS From Midterm Papers

CS606- compiler instruction Solved MCQS From Midterm Papers CS606- compiler instruction Solved MCQS From Midterm Papers March 06,2014 MC100401285 Moaaz.pk@gmail.com Mc100401285@gmail.com PSMD01 Final Term MCQ s and Quizzes CS606- compiler instruction If X is a

More information

GRAMMARS & PARSING. Lecture 7 CS2110 Fall 2013

GRAMMARS & PARSING. Lecture 7 CS2110 Fall 2013 1 GRAMMARS & PARSING Lecture 7 CS2110 Fall 2013 Pointers to the textbook 2 Parse trees: Text page 592 (23.34), Figure 23-31 Definition of Java Language, sometimes useful: http://docs.oracle.com/javase/specs/jls/se7/html/index.html

More information

COP4020 Programming Languages. Semantics Prof. Robert van Engelen

COP4020 Programming Languages. Semantics Prof. Robert van Engelen COP4020 Programming Languages Semantics Prof. Robert van Engelen Overview Static semantics Dynamic semantics Attribute grammars Abstract syntax trees COP4020 Spring 2011 2 Static Semantics Syntax concerns

More information

CSE 413 Programming Languages & Implementation. Hal Perkins Autumn 2012 Grammars, Scanners & Regular Expressions

CSE 413 Programming Languages & Implementation. Hal Perkins Autumn 2012 Grammars, Scanners & Regular Expressions CSE 413 Programming Languages & Implementation Hal Perkins Autumn 2012 Grammars, Scanners & Regular Expressions 1 Agenda Overview of language recognizers Basic concepts of formal grammars Scanner Theory

More information

MidTerm Papers Solved MCQS with Reference (1 to 22 lectures)

MidTerm Papers Solved MCQS with Reference (1 to 22 lectures) CS606- Compiler Construction MidTerm Papers Solved MCQS with Reference (1 to 22 lectures) by Arslan Arshad (Zain) FEB 21,2016 0300-2462284 http://lmshelp.blogspot.com/ Arslan.arshad01@gmail.com AKMP01

More information

Code Structure Visualization

Code Structure Visualization TECHNISCHE UNIVERSITEIT EINDHOVEN Department of Mathematics and Computer Science MASTER S THESIS Code Structure Visualization by G.L.P.M. Lommerse Supervisor: Dr. Ir. A.C. Telea (TUE) Eindhoven, August

More information

Computing Inside The Parser Syntax-Directed Translation, II. Comp 412

Computing Inside The Parser Syntax-Directed Translation, II. Comp 412 COMP 412 FALL 2018 Computing Inside The Parser Syntax-Directed Translation, II Comp 412 source code IR IR target Front End Optimizer Back End code Copyright 2018, Keith D. Cooper & Linda Torczon, all rights

More information

A parser is some system capable of constructing the derivation of any sentence in some language L(G) based on a grammar G.

A parser is some system capable of constructing the derivation of any sentence in some language L(G) based on a grammar G. Top Down Parsing 1 Parsers Formal Definitions of a Parser A parser is some system capable of constructing the derivation of any sentence in some language L(G) based on a grammar G. which talks about a

More information

LECTURE 3. Compiler Phases

LECTURE 3. Compiler Phases LECTURE 3 Compiler Phases COMPILER PHASES Compilation of a program proceeds through a fixed series of phases. Each phase uses an (intermediate) form of the program produced by an earlier phase. Subsequent

More information

Syntax Analysis. Amitabha Sanyal. (www.cse.iitb.ac.in/ as) Department of Computer Science and Engineering, Indian Institute of Technology, Bombay

Syntax Analysis. Amitabha Sanyal. (www.cse.iitb.ac.in/ as) Department of Computer Science and Engineering, Indian Institute of Technology, Bombay Syntax Analysis (www.cse.iitb.ac.in/ as) Department of Computer Science and Engineering, Indian Institute of Technology, Bombay September 2007 College of Engineering, Pune Syntax Analysis: 2/124 Syntax

More information

CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages CS 314 Principles of Programming Languages Lecture 2: Syntax Analysis Zheng (Eddy) Zhang Rutgers University January 22, 2018 Announcement First recitation starts this Wednesday Homework 1 will be release

More information

Plan for Today. Regular Expressions: repetition and choice. Syntax and Semantics. Context Free Grammars

Plan for Today. Regular Expressions: repetition and choice. Syntax and Semantics. Context Free Grammars Plan for Today Context Free s models for specifying programming languages syntax semantics example grammars derivations Parse trees yntax-directed translation Used syntax-directed translation to interpret

More information

Context-sensitive Analysis

Context-sensitive Analysis Context-sensitive Analysis Beyond Syntax There is a level of correctness that is deeper than grammar fie(a,b,c,d) int a, b, c, d; { } What is wrong with this program? (let me count the ways ) fee() { int

More information

Wednesday, September 9, 15. Parsers

Wednesday, September 9, 15. Parsers Parsers What is a parser A parser has two jobs: 1) Determine whether a string (program) is valid (think: grammatically correct) 2) Determine the structure of a program (think: diagramming a sentence) Agenda

More information