JavaCC Grammar

Hi,

I am totally new to JavaCC and I have been looking on the web to find some good document on learning JavaCC. Till now no luck. Can somebody help me in use javacc to write a parser for the following grammar?

Start         ::= 'begin' StatementList 'end'

What exactly does writing a grammar means? Please advise.

Thanks,
Mohammed
msalam65Asked:
Who is Participating?
 
aozarovConnect With a Mentor Commented:
As I can't provide you with a complete answer I wrote something that can get you started which includes comments about the JavaCC concepts.
The examples parse only the first parts of your syntax (doesn't do TERM or Factor).

To Run it:
%JAVACC_HOME%\javacc.bat my-parser.jj   (this will taks javacc input and output javafiles)
javac *.java (compiile it)
java MyParser (run it)
begin id=10+5; id=10-5; end (input example)
[15, 5] (output example)

my-parser.jj
---------------
PARSER_BEGIN(MyParser)

import java.util.*;

public class MyParser
{
      public static void main( String[] args )
            throws ParseException, TokenMgrError, NumberFormatException
      {
            MyParser parser = new MyParser(System.in) ;
           // The method will return a list of results
           // The method will throw ParseException if input is invalid
            List results = parser.Start() ;
            System.out.println(results);
      }
 }

PARSER_END(MyParser)

SKIP :
{
    " "
|   "\r"
|   "\t"
}

TOKEN:
{
    < INTEGER: (<DIGIT>)+ >
|   < DIGIT: ["0"-"9"] >
}

List Start():
{
// In this part you can add regular java declaration
// <EOF> is built in (no need to define)
List result; // you can assign the value of a statement (as seen below)
}
{
      "begin" result=StatementList() "end" (<EOF>  | "\n")
      {
            // After each JavaCC GRAMMER you can add javacode (inside brackets)
        return result;
    }    
}

List StatementList():
{
int result;
List results = new LinkedList();
}
{
      (result=Statement()
    {
       results.add(new Integer(result));
    })+
      {
        return results;
      }
}

int Statement():
{
int result;
}
{
   "id" "=" result=Expr() ";"
    {
        return result;
    }
}

int Expr():
{
int value;
int negative = 1;
Token value1; // you can assign the value of a token (as seen below)
Token value2;
}
{
      value1=<INTEGER> ("+" | "-" {negative = -1;}) value2=<INTEGER>
    {
            
        value = Integer.parseInt(value1.toString()) + negative * Integer.parseInt(value2.toString());
        return value;
    }
}



0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

 
msalam65Author Commented:
Thanks for the link objects. But how do I write the following grammer?

Start         ::= 'begin' StatementList 'end'

Is it a java code like this.

class Start() {

begin..

I am confused on what actually I need to write. Please help.

Thanks,
Mohammed
0
 
aozarovCommented:
This is now the new home for Javacc: https://javacc.dev.java.net/
From there you can download the utility as well as read their documents (which are pretty good).
see:
https://javacc.dev.java.net/doc/javaccgrm.html
Also the zip file contains examples which are easy to follow.

>> What exactly does writing a grammar means?
It means that you define a language that describe both set of keywords(syntax) and their relation.
I find myself using JavaCC anytime I need to deal with complex syntax(input) which can not be parsed
by using String/StreamTokenizer or RegExp.

If you give more details about the syntax you need I can help writing down the (javacc) .jj file.
Basically I need you to define your syntax (using BNF is a great way for doing it) and the action[s]/return type that you need (assuming
you don't want only to validate the input but also want to get some info from it).
0
 
aozarovCommented:
>> Start         ::= 'begin' StatementList 'end'
I get that 'begin' and 'end' are keywords, but what is StatementList?
Also, is there something you need returned from the evaluation or is just valid/invalid syntax?

>>Is it a java code like this.
>> class Start() {
Its a mix of both JavaCode and JavaCC grammer definitions.
0
 
msalam65Author Commented:
Thanks aozarov. Following is the thing that I am working on which I need help in.

1.      Use javacc to write a parser for the following grammar:

Start         ::= 'begin' StatementList 'end'
StatementList ::= Statement { Statement }
Statement     ::= 'id' '=' Expr ';'
Expr          ::= Term { ( '+' | '-' ) Term }
Term          ::= Factor { ( '*' | '/' ) Factor }
Factor        ::= 'id' | 'integer' | '(' Expr ')'

Any help is greatly appreciated.

Thanks,
Mohammed
0
 
aozarovCommented:
Just to verify.
1. is it homework?
2. should the parser return true/false for validating the input?
0
 
msalam65Author Commented:
1) Yes this is an assignment for my class that I need help on.
2) The thing that I am having problem is in understanding how to write a parser. My professor hasn't explained much about this assignment and this is the first time I am trying to write a parser in javacc.

Thanks,
Mohammed
0
 
objectsCommented:
> 1. is it homework?

same rules actually apply whether its homework or not, talk to the page editor if you need more details.
0
 
msalam65Author Commented:
Thanks aozarov. This helps a lot. Thanks again for your quick help. I really appreciate it.

Thanks,
Mohammed
0
 
aozarovCommented:
NP. :-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.