CSE4251/CSE5251: Assignment 4

Due: 9 February 2007.

Do the programming exercise "Parsing", from Appel, 2nd, page 81. Turn in phase03.jar containing your Java source code and parser written for JavaCC. You will need to consult the JavaCC documentation. Create an executable jar file named parse.jar. (See the project overview document.) This program parses source files according to the MiniJava grammar, and determines simply whether the source is syntactically legal or not. The last line out of output of the parser must have the file name and the number of errors discovered.

You must add error productions to handle error recovery, at least in so far as to prevent the parser from getting stuck and raising an exception. You may add error productions to guide the parser to finding as many syntax errors as possible. If the input has a syntax error your parser must write (at least) one error message to the standard error Error messages contain the file name, the line number, and the character position.

Program.java:149.23: Syntax Error:  expecting a '('
Program.java:171.18: Syntax Error:  beats me!

We will use JavaCC, an LL(k) parser generator for Java.

JavaCC input

In addition to token definitions and the Java code defining auxiliary functions (like error below), your JavaCC input will contain the rules definining the MiniJava grammar. For instance, it will contain the rule defining a program as a main class followed by any number of class declarations.
void Program() :
{}
{
                MainClass() ( ClassDecl() )* <EOF>
}
These rules may contain java code. So we may wish to gain control of parsing errors by introducing a Java exception handler.
void Program() :
{}
{
        try {

                MainClass() ( ClassDecl() )* <EOF>

        } catch (ParseException e) {
                error (e);
        }
}

Using the JavaCC parser

Running JavaCC creates the Java code for the parser. The name of the class file can be anything you like. In the example below it is MiniJavaParser. The example shows how to invoke the parser. Notice the initilization of the parser though the constructor. Then the whole stream is parsed with the invocation of the main grammar rule.
final MiniJavaParser parser  = new MiniJavaParser (new FileInputStream (filename));
if (verbose) parser.enable_tracing(); else parser.disable_tracing();
parser.Program();  // void Program()
Tracing/debugging output to the standard output stream can be enabled by calling the method enable_tracing().
Ryan Stansifer <ryan@cs.fit.edu>
Last modified: Sat Feb 9 16:41:43 EST 2008