Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2004-03-28
9
Medium Priority
?
872 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 101

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
Build and deliver software with DevOps

A digital transformation requires faster time to market, shorter software development lifecycles, and the ability to adapt rapidly to changing customer demands. DevOps provides the solution.

 

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 101

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

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

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

How to remove superseded packages in windows w60 or w61 installation media (.wim) or online system to prevent unnecessary space. w60 means Windows Vista or Windows Server 2008. w61 means Windows 7 or Windows Server 2008 R2. There are various …
The purpose of this article is to demonstrate how we can use conditional statements using Python.
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
Suggested Courses

722 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