CPSC 388 - Compiler Design and Construction: Parsers - Context Free Grammars
CPSC 388 - Compiler Design and Construction: Parsers - Context Free Grammars
and Construction
Solution to HW3
Reading: 4.1-4.4
Optimizer
Code Generator
Scanner
Source Code:
Corresponding Tokens:
IDENT(position)
ASSIGN
IDENT(position)
PLUS
IDENT(rate)
TIMES
INT-LIT(60)
SEMI-COLON
Example Parse
Source Code:
position = initial + rate * 60 ;
Abstract-Syntax Tree: =
position +
Single non-terminal
Example with Boolean Expressions
“true” and “false” are boolean
expressions
If exp1 and exp2 are boolean
expressions, then so are:
exp1 || exp2
exp1 && exp2
! exp1
( exp1 )
Corresponding CFG
bexp → TRUE
bexp → FALSE
bexp → bexp OR bexp
bexp → bexp AND bexp
bexp → NOT bexp
bexp → LPAREN bexp RPAREN
UPPERCASE represent tokens (thus terminals)
lowercase represent non-terminals
CFG for Assignments
Here is CFG for simple assignment
statements
(Can only assign boolean expressions
to identifiers)
stmt → ID ASSIGN bexp SEMICOLON
CFG for simple IF statements
Combine these CFGs and add 2 more rules for
simple IF statements:
1. stmt → IF LPAREN bexp RPAREN stmt
2. stmt → IF LPAREN bexp RPAREN stmt ELSE stmt
3. stmt → ID ASSIGN bexp SEMICOLON
4. bexp → TRUE
5. bexp → FALSE
6. bexp → bexp OR bexp
7. bexp → bexp AND bexp
8. bexp → NOT bexp
9. bexp → LPAREN bexp RPAREN
You Try It
Write a context-free grammar for the
language of very simple while loops
(in which the loop body only contains
one statement) by adding a new
production with nonterminal stmt on
the left-hand side.
CFG Languages
The language defined by a context-free
grammar is the set of strings (sequences of
terminals) that can be derived from the
start nonterminal.
And So On…