The parser is the second part of the front end of a compiler.The parser analyzes the input program. and determines whether or not it constitutes a legal sentence, or sentences, in the source language. The input to the parser is a stream of tokens produced by the scanner. For a valid input program, the parser produces a parse tree or some other intermediate representation of the input program.
We can use the javacc as the parser generator to generate the parser for our compiler. In a .jj file we need to provide a context-free grammar for javacc to create the parser.




For generating the parser, we create the cal.jj file. and use it as the input file to the javacc. This file describes the BNF for the simple calculator garmmar.
The following is the new cal.jj file:

  options {
    IGNORE_CASE = false;
    OPTIMIZE_TOKEN_MANAGER = true;
  }

  PARSER_BEGIN(cal)

  import java.io.*;
  import java.util.*;

  public class cal {

    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);
        }

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

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



  PARSER_END(cal)

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

  TOKEN:
  {
    <LPAREN:    "(">
  | <RPAREN:    ")">
  | <ADD_OP:    "+" | "-">
  | <MULT_OP:   "*" | "/">
  | <NUMBER:    (["0"-"9"])+>
  }

   void calculator() :
   {}
   {
     expression() < EOF>
     {System.out.println("Calculator");}
   }

   void expression() :
   {}
   {
     term() (<ADD_OP> term())*
     { System.out.println("Expression");}

   }

   void term():
   {}
   {
     factor() (<MULT_OP> factor())*
     { System.out.println("Term");}

   }

   void factor():
   {}
   {
    (<LPAREN> expression() <RPAREN>
   |number())
   { System.out.println("Factor");}
   }

   void number() :
   {}
   {
   <NUMBER>
   { System.out.println("NUMBER");}
   }

  

If we run our generated parser on the test file:
test.txt
6*(11-7)/3+100

We will get the output of our parser like this:
NUMBER
Factor
NUMBER
Factor
Term
NUMBER
Factor
Term
Expression
Factor
NUMBER
Factor
Term
NUMBER
Factor
Term
Expression
Calculator
Parse completed.

Using this output we can draw a parse tree of our calculator expression as follows.