• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 911
  • Last Modified:

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

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
needexpert
Asked:
needexpert
1 Solution
 
funnyveryfunnyCommented:
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
 
needexpertAuthor Commented:
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
 
mlmccCommented:
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
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

 
needexpertAuthor Commented:
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
 
needexpertAuthor Commented:
I have asked customer support to close the question with reduced points given I figured it out myself.
0
 
needexpertAuthor Commented:
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
 
mlmccCommented:
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
 
AnnieModCommented:
Question PAQ'd and 500 points refunded

AnnieMod
EE Admin
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.

Join & Write a Comment

Featured Post

Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now