Solved

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

Posted on 2004-03-28
9
863 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
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 

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

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Programatically extract date from website 8 77
servlet example 17 32
hibernate example using maven 12 42
Chrome and Firefox Java 5 33
If you haven’t already, I encourage you to read the first article (http://www.experts-exchange.com/articles/18680/An-Introduction-to-R-Programming-and-R-Studio.html) in my series to gain a basic foundation of R and R Studio.  You will also find the …
Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

810 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