Augmenting Parser – Adding Java Code

Consider previous example where we learnt how to generate a Lexical Analyser and Parser with JavaCC. Today we are going to discuss, how to augment BNF productions with Java code? Later it will be included in the generated methods.

To do so we have to change Basic.jj specification file. To the BNF production Start we add some declarations and some java code.

  1. Change the return type of BNF production from void to int
  2. Specify, NumberFormatException can be thrown from generated method
  3. Declared three variable
    1. Variable t is of type Token, which is a generated class that represents tokens
    2. t.image field of the Token class records the string of characters matched
    3. t = when a token is matched, we can record Token to assign the reference to it
  4. Within braces in a BNF production, you can add any Java statements
  5. Start method now returns a value
  6. Now we can change our main method as follow

Here is our modified Basic.jj file. Have a look at it.

Watch video given below : Step by step changes

Thanks for reading my article. Leave your comment or suggestion in comment area. Have a nice day.