Lecture#5 - Chap#2 (Syntax Directed Translator (Part-I) )
Lecture#5 - Chap#2 (Syntax Directed Translator (Part-I) )
Compiler Construction
A Simple Syntax-Directed Translator,
(Part-I)
by Safdar Hussain
Topics
• Syntax Definition (Structure of Compiler, Tokens vs Terminals, Tree Terminology, Grammars,
Parse Trees, Derivation, Ambiguity, Associativity & Precedence, left-associative grammars,
right-associative grammars, Syntax Statements, Multiple CFG 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
call id ( optparams )
optparams params |
params params, param |param
9 - 5 + 2 9 - 5 + 2
Parse tree for Left-associative grammar Parse tree for right-associative grammar
?
Safdar Hussain, Lecturer CS, Khwaja Fareed University, RYK 24
Tasks Solution
Consider the context-free grammar
SSS+|SS*|a
a) Show how the string aa+a* can be generated by this grammar.
b) Construct a parse tree for this string
c) What language does this grammar generate? Justify your
answer.
Answers
(a)- string generation (b)- parse tree (c)- Grammar’s language
S SS*
S SS+S* L = {Postfix expression
S aS+S* consisting of digits, plus and
S aa+S* multiple signs}
S aa+a*
Safdar Hussain, Lecturer CS, Khwaja Fareed University, RYK 25
Problem & Solution (CFG Tasks)
What language is generated by the following
grammars? In each case justify your answer.
a) S 0S1 | 01
b) S +SS | -SS | a
c) S S(S)S | Ԑ
?
Safdar Hussain, Lecturer CS, Khwaja Fareed University, RYK 26
Tasks Solution
What language is generated by the following grammars? In each
case justify your answer.
a) S 0S1 | 01
b) S +SS | -SS | a
c) S S(S)S | Ԑ
Q# Languages
a L = {0n 1n | n>=1}
?
Safdar Hussain, Lecturer CS, Khwaja Fareed University, RYK 28
Tasks Solution
Consider the following grammars: Which of the grammars
are ambiguous?
Q# Grammar Ambiguous? c
a S 0S1 |01 No
b S +SS | -SS | a No
For String = ()(), it can generate 2
trees
c S S(S)S | Ԑ Yes
?
Safdar Hussain, Lecturer CS, Khwaja Fareed University, RYK 30
Tasks Solution
Construct unambiguous context-free grammars for each of the
following languages. In each case show that your grammar is
correct.
a) Arithmetic expressions in postfix notation.
b) Left-associative lists of identifiers separated by commas.
c) Right-associative lists of identifiers separated by commas.
Q# Unambiguous CFGs
a E E E op | num
2 II 12 XII
3 III 13 XIII
4 IV 14 XIV
5 V 15 XV
6 VI 16 XVI
7 VII 17 XVII
8 VIII 18 XVIII
9 IX 19 XIX
10 X 20 XX
34