[antlr-interest] Using Own classes to recolect or parse the data withing the grammar
Victor Giordano
power_giordo at yahoo.com.ar
Wed Aug 11 22:10:19 PDT 2010
Hi all!. Hope good again!! (And not tired... of me xD)
Above a paste and example of what i am looking towards to parse.
A linear Expression. That is simply a succession of linear terms.
A linear terms is something like : Constants Var | Var.
Based on the example of _the definitive guide to ANTLR_ with math
expression, a procced to re adapt this to capture the data into my own
expression of the program.
So basically, for now, i only wanted to put all the linear terms in and
list (specifically: an Arraylist) and have it in that strcuture because
later i throw it in a simplex resolver to compute answer to linear
optimization problems.
So... the thing, is that i do this (pasted above).
If you want, just copy and paste and debug this example with: 2x + 3y + 4z
You will see some output like this: 2.0 * x + 3.0 * y + 4.0 * z (The
resutl of invoke the toString over my custom class inner of the parser).
The question is: How i can do this, without definig the class inside the
@menbers section. That class, in fact, is one of my program.. so i only
want to reuse that.
Jim Idle say to me, days before, that for this kind of things are not
simple and required the help of maven.... but i really hope someone know
some easier way to archieve this.
Thanks!!.
------------------------------------------------------------------------
grammar LinearExpression;
options
{
output=AST;
}
tokens
{
PLUS = '+';
MINUS = '-';
MUL = '*';
DIV = '/';
}
@members
{
public static class LinearExpr
{
ArrayList<LinearTerm> terms;
public LinearExpr()
{
terms = new ArrayList<LinearTerm>();
}
public void add(LinearTerm lt)
{
terms.add(lt);
}
@Override
public String toString()
{
StringBuilder res = new StringBuilder(50);
for (LinearTerm lt : terms)
{
res.append(lt.toString()).append(" + ");
}
return res.substring(0,res.lastIndexOf("+"));
}
}
public static class LinearTerm
{
String var;
float cofactor;
public LinearTerm()
{
this.var = "";
this.cofactor = 1;
}
@Override
public String toString()
{
return this.cofactor + " * " + this.var;
}
}
}
expr returns [LinearExpr ret]
@init
{
$ret = new LinearExpr();
}
@after
{
System.out.println ($ret);
}
: e=term {$ret.add($e.ret);}
( PLUS e=term {$ret.add($e.ret);}
| MINUS e=term {$ret.add($e.ret);}
)*;
term returns [LinearTerm ret]
@init
{
$ret = new LinearTerm ();
}
:
(FLOAT {$ret.cofactor = Float.parseFloat($FLOAT.text);}
|INT {$ret.cofactor = Integer.parseInt($INT.text);}
)?
ID {$ret.var = $ID.text;};
ID : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*;
INT : '0'..'9'+ ;
FLOAT
: ('0'..'9')+ '.' ('0'..'9')* EXPONENT?
| '.' ('0'..'9')+ EXPONENT?
| ('0'..'9')+ EXPONENT
;
fragment EXPONENT : ('e'|'E') ('+'|'-')? ('0'..'9')+ ;
More information about the antlr-interest
mailing list