There are many possible ways to do this; here's one:
There are many possible ways to do this; here are two:
cons* vowel (cons+ vowel)* cons*
cons* vowel (cons vowel | cons+)*
stmt ::= FOR LPAREN forCond RPAREN LCURLY varDeclList stmtList RCURLY
forCond ::= ID ASSIGN exp COLON exp optFor
optFor ::= COLON exp | /* epsilon */
exp → exp ? term | term
term → factor $ term | factor
factor → INTLIT | ( exp )
expr
/ | \
/ | \
expr ? term
| / | \
term factor $ term
| | |
factor INTLIT factor
| (2) / | \
INTLIT ( expr )
(1) / | \
expr ? term
| |
term factor
| |
factor INTLIT
| (4)
INTLIT
(3)
exp → term exp'
exp' → ? term exp' | ε
term → factor $ term | factor
factor → INTLIT | ( exp )
exp → term exp' exp' → ? term exp' | ε term → factor term' term' → $ term | ε factor → INTLIT | ( exp )
| Grammar rule | Translation rule |
|---|---|
| program → varDeclList stmtList | program.trans = stmtList.trans |
| varDeclList → varDeclList varDecl | |
| varDeclList → varDecl | |
| varDecl → type ID ; | |
| type → INT | |
| type → BOOL | |
| stmtList → stmtList stmt | stmtList1.trans = union(stmtList2.trans, stmt.trans) |
| stmtList → stmt | stmtList.trans = stmt.trans |
| stmt → ID = exp ; | stmt.trans = exp.trans |
| stmt → IF ( exp ) { varDeclList stmtList } | stmt.trans = union(exp.trans, stmtList.trans) |
| exp → ID | exp.trans = new List(ID.val) |
| exp → INTLIT | exp.trans = new List() |
| exp → exp + exp | exp1.trans = union(exp2.trans, exp3.trans) |
| exp → exp * exp | exp1.trans = union(exp2.trans, exp3.trans) |
| exp → exp == exp | exp1.trans = union(exp2.trans, exp3.trans) |
| Non-terminal X | FIRST(X) | FOLLOW(X) |
|---|---|---|
| block | LCURLY | EOF, ELSE, ID, IF, RETURN, RCURLY |
| declList | TYPE, ε | ID, IF, RETURN, RCURLY |
| stmtList | ID, IF, RETURN, ε | RCURLY |
| decl | TYPE | TYPE, ID, IF, RETURN, RCURLY |
| stmt | ID, IF, RETURN | ID, IF, RETURN, RCURLY |
| exp | ID, INT | SEMI, RPAREN |
Snapshot 1:
| current stack |
stmtList RCURLY EOF |
Snapshot 2:
partial parse tree
block
__/ || \__
_____/ __/ \__ \_____
/ / \ \
LCURLY declList stmtList RCURLY
/ \
/ \
decl declList
/ | \
/ | \
TYPE ID SEMI
Snapshot 3:
input: LCURLY RCURLY
| current stack |
stmtList RCURLY EOF |