Lecture2 PDF
Lecture2 PDF
2130-001
Compiler Construction
Lecture 2:
Syntax-Directed Translator
Example:
Corresponds to a rule:
Nonterminals
They need more rules to define them.
Production Rules
stmt -> if (expr) stmt else stmt
Terminals
No more rules needed for them
Components of Context-Free Grammar
The process of finding a parse tree for a given string of terminals is called parsing.
Example
Deriving 9-5+2 from
Example
term->digit-term
digit -> 0|1|2|3|4|5|6|7|8|9 Right-associative
9-(5-2)
Precedence of Operators
• Associativity applies to occurrence of
the same operator
• What if operators are different?
• How will you evaluate: 9-5*2
• We say ‘*’ has higher precedence than ‘-’
if it takes its operands before ‘-’
Precedence of Operators
How to present this in productions?
|| means concatenate
Attribute values at nodes for 9-5+2
•Build the tree
•Start from leaves
•Using semantic rules till you reach root
With attributes
Concerning Tree Traversal
Depth first
•Preorder
•Postorder
Back to Parsing!
• We have a set of productions
• We have a string of terminals
• We need to form the parse-tree that
will generate that string
Given this set of productions: and this string:
term
expr -> term factor
term + term
factor -> + term factor | ε
term + term + term
…
Enough for Today
• Next time we will continue our trip for
building simple translator
• This lecture covered 2.1 -> 2.4