Parser Project

Implementing the Tea Grammar using JavaCC

Theo's solution

Although you wrote a grammar for assignment #1, we'd like you to use our grammar for uniformity. If you think changes need to be made to our grammar, please post your concerns.

(a) Write JavaCC code to create a parser for this subset of Tea . Add print statements after each production to print out the name of the nonterminal on the left-hand-side of the production.

(b) Run it on the assigned programs from the lexer assignment and a program of your choice.

(c) Using the printed output, create a parse tree by hand. (In the next assignment, we'll create internal abstract syntax trees.) If you have a lot of nodes for your example, you need not draw every node.

The following is a subset of Theo's solution to this project:


options {
  IGNORE_CASE = false;
  OPTIMIZE_TOKEN_MANAGER = true;
}

PARSER_BEGIN(tea)

import java.io.*;

public class tea {

  public static void main(String[] args) throws ParseException,
						FileNotFoundException
  {
   if ( args.length < 1 ) {
      System.out.println("Please pass in the filename for a parameter.");
      System.exit(1);
   }

   tea parser = new tea( new FileInputStream(args[0]) );

   parser.program();
   System.out.println("Parse completed.");
  }
}

PARSER_END(tea)

SKIP: /* Whitespace */
{
  "\t"
| "\n"
| "\r"
| " "
}

TOKEN: /* Most tokens */ 
{
  <IF: "if">
| <ELSE: "else">
| <TYPE: "void">

.....

TOKEN: /* Generic Name & Number */
{
  <NUMBER: (["0"-"9"])+>
| <NAME: ["a"-"z","A"-"Z"] (["a"-"z","A"-"Z","0"-"9","_"])*>
}

void program() :
{}
{
  method_declaration() <EOF>
}

void method_declaration() :
{}
{
  <TYPE> <NAME> <LPAREN> <RPAREN> <LBRACE> statement_block() <RBRACE>
   { System.out.println("method_declaration"); }
}

void statement_block() :
{}
{
  ( statement() )*
}

void statement() :
{}
{
  simplestatement() <SEMICOLON> {System.out.println("SimpleStatement");}
| compoundstatement() {System.out.println("CompoundStatement");}
| <LBRACE> statement_block() <RBRACE>
}

void assignmentstatement() :
{}
{
  <NAME> [<ASSIGNOP> expression()]
   { System.out.println("Assignment Statement"); }
}

Pass in: