[antlr-interest] Is there a basic source-level expression optimizer for ANTLR?
Matthew Ford
Matthew.Ford at forward.com.au
Tue Aug 5 13:14:24 PDT 2003
Yes I wrote one as apart of a Algorithmic Differentiation package for GAUSS.
Basically you walk the tree and when you find a + operator for example you
call
AST result = astPlus(AST lh, AST rh); to optimize it
Looking at my code
from the calc.g example (slightly modified)
: #(PLUS a:expr b:expr) {
## = astPlus(#a, #b); // process the +
}
You may not need to use scope for simple optimizations.
If you do I would suggest the anltraux package http://antlraux.sf.net
hope this helps
matthew
/**
* forms AST tree of lh + rh reducing zeros as it goes
* lh and rh are the expressions or constants
**/
public AST astPlus(AST lh, AST rh) {
// do dups here or things just bomb
AST lh_AST =
(AST)AST_Utils.astFactory.dupTree(lh.getType()==EXPRESSION?lh.getFirstChild(
):lh);
AST rh_AST =
(AST)AST_Utils.astFactory.dupTree(rh.getType()==EXPRESSION?rh.getFirstChild(
):rh);
AST rtnAST = ASTNULL;
if (lh_AST.getType() == ZERO) {
rtnAST = rh_AST;
} else if (rh_AST.getType() == ZERO) {
rtnAST = lh_AST;
} else {
// return original tree
// actually here I remake it for other reasons.
rtnAST = AST_Utils.ad_2_args(Prefixes.adStructPrefix +
Prefixes.DplusD, lh_AST, rh_AST);
}
return rtnAST;
}
/**
* makes two arg fn
**/
public static AST ad_2_args(String fnName, AST arg1, AST arg2) {
AST arg1_AST =
(AST)AST_Utils.astFactory.dupTree(arg1.getType()==EXPRESSION?arg1.getFirstCh
ild():arg1);
AST arg2_AST =
(AST)AST_Utils.astFactory.dupTree(arg2.getType()==EXPRESSION?arg2.getFirstCh
ild():arg2);
AST arg = (AST)astFactory.make(
(new ASTArray(3)).add( (AST)astFactory.create(ARG_LIST,"ARG_LIST") )
.add( makeExpression(arg1_AST ) )
.add( makeExpression(arg2_AST ) )
);
CommonASTWithScope returnAST = (CommonASTWithScope)astFactory.make(
(new ASTArray(2)).add( (AST)astFactory.create(FUNCTION_CALL,fnName) )
.add( arg )
);
return returnAST;
}
// make this AST an EXPRESSION AST
public static AST makeExpression(AST exp) {
if (exp.getType() == EXPRESSION) {
return astFactory.dupTree(exp); // already made
}
// else
return (AST)astFactory.make(
(new ASTArray(2)).add(
(AST)astFactory.create(EXPRESSION,"EXPRESSION") )
.add( astFactory.dupTree(exp) )
);
}
----- Original Message -----
From: "micheal_jor" <open.zone at virgin.net>
To: <antlr-interest at yahoogroups.com>
Sent: Wednesday, August 06, 2003 1:35 AM
Subject: [antlr-interest] Is there a basic source-level expression optimizer
for ANTLR?
> Hi,
>
> Has anyone written a source-level expression optimizer with ANTLR?.
> Even a basic one that optimizes boolean expressions only would be
> fine. The real objective is learning about TreeParser transformations.
>
> Cheers,
>
> Micheal
>
>
>
>
>
>
>
> Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/
>
>
Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/
More information about the antlr-interest
mailing list