Professional Documents
Culture Documents
Lecture#6 - Chap#2 (Syntax Directed Translator (Part-II) )
Lecture#6 - Chap#2 (Syntax Directed Translator (Part-II) )
Compiler Construction
A Simple Syntax-Directed Translator,
(Part-II)
by Safdar Hussain
Topics
• Syntax-Directed Translation (Postfix Notation, Synthesized Attributes, Inherited Attributes
• Translation, Infix to postfix Translation, Attributed Grammars, Depth-First Traversals, SDD
• Translation Schemes, SDT Questions/Tasks)
Overview
• This chapter contains introductory material
• Building a simple compiler
– Syntax Definition
– Syntax-Directed Translation
– Parsing
– A Translator for Simple Expressions
– The Lexical Analyzer
Informal Notations
Informal Notations
SDT uses a CFG to specify the syntactic structure of the language &
associates a set of attributes with (non)terminals.
Further, with each production, associates a set of semantic rules for
computing values for the attributes.
The attributes contain the translated form of the input after the
computations are completed.
In SDT, every non-terminal can get 0 or more attributes.
In semantic rule, attribute can be a value (string, memory location,
number, etc.)
Safdar Hussain, Lecturer CS, Khwaja Fareed University, RYK 5
Syntax for Statements
stmt id:= expr
|if expr then stmt
|if expr then stmt else stmt
|while expr do stmt
|begin opt_stmts end
Ambiguous Grammar?
Postfix(9 – ( 5 + 2 ) )
= Postfix( 9 ) Postfix( ( 5 + 2 ) ) -
= Postfix( 9 ) Postfix( 5 + 2 ) –
= Postfix( 9 ) Postfix( 5 ) Postfix( 2 ) + –
=952+–
Synthesized
Inherited
Safdar Hussain, Lecturer CS, Khwaja Fareed University, RYK 9
Attributed Grammar
(SDD for infix to postfix translation)
Infix: 9-5+2 & Postfix: 95-2+
Production Semantic Rule
expr expr1 + term expr.t := expr1.t // term.t // “+”
expr expr1 - term expr.t := expr1.t // term.t // “-”
expr term expr.t := term.t
term 0 term.t := “0”
term 1 term.t := “1”
… …
term 9 term.t := “9”
Note:
Synthesized attributes are evaluated after visiting and
Inherited attributes are evaluated at first occurrence
term.t = 9
9 - 5 + 2
Embedded
semantic action
rest
expr +
term { print(“2”) }
{ print(“-”)}
- term 2
expr
{ print(“5”) }
term 5
{ print(“9”) }
9
Translates 9-5+2 into postfix 95-2+
term
{ print(“9”) }
9
Translates 9-5+2 into postfix 95-2+
NOTE: Construct annotated parse trees for the inputs 9-5+2 and 9-5*2 by yourself
NOTE: Construct annotated parse trees for the inputs 9-5+2 and 9-5*2 by yourself
29