LARA

Exercises 03

Important update

There was a bug in the stub .jj file that caused the keywords if, while, etc. to be recognized as identifiers rather than the proper tokens. It is now fixed. Make sure you use the latest version (that is, you should have <IF> in the productions, not “if”, for instance).

Conversion to LL(1)

Convert the following grammar for the while language to LL(1):

program ::= statement*
statement ::= print | assign | if | while | block
print ::= "println" "(" STRLIT "," var ")" ";"
assign ::= var "=" expr ";"
if ::= "if" "(" exp ")" block ("else" statement)?
while ::= "while" "(" expr ")" statement
block ::= "{" statement* "}"
expr ::= var | INTLIT | expr binOp expr | unOp expr | "(" expr ")"
unOp ::= "!" | "-"
binOp ::= "+" | "-" | "*" | "/" | "%" | "==" | ">" | "<" | "&&" | "||"

Note that we modified it from the original: the rule for if statements now says that the “then” branch must be a block rather than just a statement.

Write your grammar such that the derivation trees properly encode the priority of operators. We will use the same precedence rules as in Java (or MiniJava+, for that matter). From the most “tightly-binding” to the less, we have: { - (unary), ! } then { *, /, % } then { +, - } then { <, ==, > } then { &&, || }. This means that - 5 * 4 + 2 == 1 || 0 < 4 should parse as ((((-5) * 4) + 2) == 1) || (0 < 4), for instance.

JavaCC

Write your LL(1) grammar in the JavaCC format and use javacc to automatically produce a parser. You can use a stub, whilelang.jj, to speed things up. Note that this grammar is simply a transcription of the non-LL(1) grammar in JavaCC format (and therefore won't compile with JavaCC without errors).

To use JavaCC:

  • Download it.
  • Run javacc on your .jj file. Pay attention to the errors and warnings. You really shouldn't have any.
  • If the previous step was successful, run javac *.java to compile the generated Java source files.
  • You can then try java WhileParser < collatz.while, for instance. A silent run means the parsing was successful, you get exceptions otherwise.

Additional question

Why did we make that change to the grammar? Explain what would have happened otherwise.

Deliverable

For this exercise you will not hand in any hand-written assignment. Instead, submit your modified whilelang.jj file through Moddle. Include the answer to the Question as a comment in the uploaded file (comments in JavaCC use the same format as in Java).