Solved

Create Parser with ANTLR? .g file and main.java

Posted on 2004-03-28
9
860 Views
Last Modified: 2013-11-18
I have the following grammar:
<Expr> ---> (<operator><oplist>)
<oplist> ---> <operand><oplist>
<operand> ---> <Expr> | INT
<operator> ---> + | - | * | /

some sentences in the above grammar are:
(+6 8)                                 //meaning 6+8=14
(* (+ 2 4) (/ 8 2))                //meaning (2+4)*(8/2) = (6)*(4) = 24
(+ 8 2 3 5)                          //meaning 8+2+3+5 = 18

I have read everything on the ANTLR and have created the sample parsers, etc. but I am having a problem getting my above grammar into the proper format ( .g file) so that I can run
java antlr.Tool aboveGrammar.g

Also, do I have to have some sort of unique code in my main.java to make sure that the parser generated from ANTLR works properly for the type of sentences listed above?

I will increase the points on this question to whomever actually walks me through this process as I have spent 2 days or more already trying to figure it out. Thanks!
0
Comment
Question by:needexpert
9 Comments
 
LVL 4

Expert Comment

by:funnyveryfunny
ID: 10700659
Hi,

Just read an introduction on it and it sounds interesting, could you please post all of your codes here? See if I can do anything with it.


0
 

Author Comment

by:needexpert
ID: 10701612
Check out this site.
http://www.antlr.org/doc/getting-started.html

I have read it from top to bottom and successfully work all of the examples but am having a problem with the actual grammar. There is no code. If the grammar is correct then the ANTLR will generate the parser for you and all of the code. That is what it does.
0
 
LVL 100

Expert Comment

by:mlmcc
ID: 10705968
Before I provide a full sample, let me verify Is this a homework assignment?  If so experts cannot do your homework for you.  We can help with problems.  If it is homework, please post your current effort and I will try to help you correct it.

To help you get started

class ExprParser extends Parser;

expr:   LPAREN operator oplist RPAREN

class ExprLexer extends Lexer;

options {
    k=2; // needed for newline junk
    charVocabulary='\u0000'..'\u007F'; // allow ascii
}

LPAREN: '(' ;
RPAREN: ')' ;}
 ;    

mlmcc
0
 

Author Comment

by:needexpert
ID: 10711492
No, this is not a homework assignment. I have an interest in knowing what makes a computer understand what it is being told to do and how all the pieces fit. I ran across the ANTLR site and read up on it and found it interesting so I have loaded and tested a lot of the examples from the pdf that are available on the antlr.com site and they have worked but when I tried to test some variations of my own with what I expect my output to be I get errors. It seems however that converting from one grammar style into another is not as straight forward and that is where I was running into difficulty.

So far with the help of JGuru forum, I have the code below and it pretty much works except for (+8 2 3 5) which should result in calculating 8+2+3+5=18. However it is looking for a rparen and not another INT and throws an error. I am sure it is something easy that I am missing with allowing more than one INT back to back with ignoring WS but I haven't figured it out. Just a challenge.

The code mainly is from an ANTLR pdf tutorial with some variation that I have made with the help of JGuru is as follows:

class ExpressionParser extends Parser;
options { buildAST=true; }

expr: sumexpr SEMI!;
sumexpr: LPAREN! (PLUS^|MINUS^|STAR^|DIV^) operand operand RPAREN!;
operand: sumexpr | INT;
//sumExpr : prodExpr ((PLUS^|MINUS^) prodExpr)* ;
//prodExpr : atom ((STAR^|DIV^) atom)* ;
//powExpr : atom (POW^ atom)? ;
//atom : INT ;

class ExpressionLexer extends Lexer;
WS      :      (' '|'\t'|'\n'|'\r')
            { _ttype = Token.SKIP; };
LPAREN:      '(';
RPAREN:      ')';
PLUS : '+' ;
MINUS : '-' ;
STAR : '*' ;
DIV : '/' ;
MOD : '%' ;
POW : '^' ;
SEMI : ';' ;
protected DIGIT : '0'..'9' ;
INT : (DIGIT)+ ;
{import java.lang.Math;}
class ExpressionTreeWalker extends TreeParser;
expr returns [double r]
{ double a,b; r=0; }
: #(PLUS a=expr b=expr) { r=a+b; }
| #(MINUS a=expr b=expr) { r=a-b; }
| #(STAR a=expr b=expr) { r=a*b; }
| #(DIV a=expr b=expr) { r=a/b; }
| #(MOD a=expr b=expr) { r=a%b; }
| #(POW a=expr b=expr) { r=Math.pow(a,b); }
| i:INT { r=(double)Integer.parseInt(i.getText()); }
;

My Main.java is from the tutorial:
import java.io.*;
import antlr.CommonAST;
import antlr.collections.AST;
import antlr.debug.misc.ASTFrame;

public class main{
public static void main(String args[]) {
  try{ DataInputStream input = new DataInputStream(System.in);
      ExpressionLexer lexer = new ExpressionLexer(input);
      ExpressionParser parser = new ExpressionParser(lexer);
      parser.expr();
      CommonAST parseTree = (CommonAST)parser.getAST();
      System.out.println(parseTree.toStringList());
      ASTFrame frame = new ASTFrame("The tree", parseTree);
      frame.setVisible(true);
      ExpressionTreeWalker walker = new ExpressionTreeWalker();
      double r = walker.expr(parseTree);
      System.out.println("Value: "+r);}
  catch(Exception e){ System.err.println("Exception: "+e); }
 }
}
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 

Author Comment

by:needexpert
ID: 10723607
I have asked customer support to close the question with reduced points given I figured it out myself.
0
 

Author Comment

by:needexpert
ID: 10727020
mlmcc:
I opened another question to award you 20 points and am requesting this 500+ question to be deleted since I have solved the issue myself. It has been 2 days since I posted all of my code, which you can see is pretty much working. I do however appreciate the time you took to initially communicate with me and have therefore awarded you 20 points in the following question. Thank you.  I trust that you will not object to my decision.


http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_20939196.html
0
 
LVL 100

Expert Comment

by:mlmcc
ID: 10728775
Not a problem.  I ask the homework question fairly often.  As an educator I tend to see certain types of question as education-related.  This includes ones like this where your interest is personal as well as educational.

I gave you some hints as a teacher would and was willing if you had come back quickly to work on a full blown language.  My specialty in school was programming languages and I have written several compilers so I enjoy helping with that.

Good luck
mlmcc
0
 

Accepted Solution

by:
AnnieMod earned 0 total points
ID: 10756280
Question PAQ'd and 500 points refunded

AnnieMod
EE Admin
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now