
COP 4020 Programming Assignment 4: Calculator
Parser
Educational Objectives: After completing this assignment, the student should be able to do the following:
•Draw parse trees for legal expressions
•Given an LL(1) grammar, implement a recursive descent parser as a Java class:
i. Define functions (methods) for each non-terminal in the grammar
ii. Use sequencing and recursion as defined in the productions of the grammar
•Explain how legal expressions are parsed by the code
•Explain why non-legal expressions are not fully parsed and where the parser detects the non-legality
Operational Objectives: Implement a recursive descent parser in Java for a calculator language based on a
BNF grammar.
Deliverables: One file Parser4.java
1. Arithmetic operators in a programming language are typically left associative with the notable
exception of exponentiation (^) which is right associative. (However, this rule of thumb is not
universal.)
Associativity can be captured in a grammar. For a left associative binary operator lop we can have a
production of the form:
<expr> -> <term>
| <expr> lop <term>
For example, a+b+c is evaluated from the left to the right by summing a and b first. Assuming that
<term> represents identifiers, the parse tree of a+b+c with the grammar above is:
<expr>
/ | \
<expr> + <term>
/ | \ |
<expr> + <term> c
| |
<term> b
|
a
As you can see, the left subtree represents a+b which is a subsexpression of a+b+c, because a+b+c
is parsed as (a+b)+c.
Note that the production for a left associative operator is left recursive. To eliminate left recursion, we
can rewrite the grammar into:
<expr> -> <term> <term_tail>
<term_tail> -> lop <term> <term_tail>
| empty
This (part of the) grammar is LL(1) and therefore suitable for recursive descent parsing. However, the
parse tree structure does not capture the left-associativity of the lop operator.