Solved

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

Posted on 2004-03-28
9
865 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
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 

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
 

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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
difference between sorce folder and folder in eclipise 3 29
swing controls 2 16
convert Systemjs to Webpack 3 37
What browser will run Java? 7 72
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
The viewer will learn how to implement Singleton Design Pattern in Java.
This video teaches viewers about errors in exception handling.

821 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