Professional Documents
Culture Documents
Cs 160
Cs 160
Cs 160
Discussion 2
William Eiers & Seemanta Saha
Project 2
• Build scanner & recursive-descent parser in C++
Start → ExprList
○ Ambiguous
○ No operator precedence
Grammar Techniques
● Techniques for modifying grammar:
○ Precedence introduction
○ Left-recursion elimination
○ Left factoring
Precedence Introduction
• Parent nodes in parse tree require information
from child nodes for processing
1 + 2 * 3
Expression →
Expression + Expression
Expression →
| Term
Expression + Expression
| Expression * Expression
Term →
| num
Term * Term
| num
Operator Precedence
• () is the highest
becomes
becomes
Expression’ → + Expression
| - Expression
Step 2 : Scanner
• Reads input from standard input stream (STDIN)
• Identifies tokens and handles line numbers
• Make tokens available and useful to parser
• nextToken function, returns next token
• eatToken function, consumes a given token
Scanner Example
Scanner Tips
● Whitespace is ignored between tokens
● Whitespace includes space, tab, newline, etc.
● Whitespace is not allowed inside a single token
● Easiest to examine one character at a time
○ Use a switch-case statement
● nextToken and eatToken should be consistent. Be
careful when fetching a token and consuming a token.
Step 3: Recursive
Descent Parser
• Each non-terminal has corresponding function
E → T + T * F
Recursive Descent Example
E → number
| ( E )
Recursive Descent Example
S→ E
E → FE’
E’→ +FE’ | -FE’ | ε
F → m | (E) | num
Let’s compute First and
Follow sets for the
grammar from the
previous page
Step 4: Expression
Evaluation
● Activated with -e command line flag
• Thrown by parser