[antlr-interest] Re: Change operator precedence in a AST
Pete Forman
pete.forman at westerngeco.com
Mon Sep 27 02:44:03 PDT 2004
At 2004-09-27 08:04 +0000, lgcraymer wrote:
>You still can use the AST to generate code--just insert parentheses in
>the appropriate spots.
Here's a code extract showing a set of rules applied and part of the
tree processing code implementing those rules.
// _____ ___________ _______
//____operator U+ U- * / % + - <> =!
//____operand L R L R L R L R L R L R L R
// unary+ . . . . . . . . . . . . . . . .
//___ unary- . . . . . . . . . . . . . . . .
// * O O . . . O . O . . . . . . . .
// / O O . O . O . O . . . . . . . .
//___ % O O . O . O . O . . . . . . . .
// + O O O O O O O O . . . O . . . .
//___ - O O O O O O O O . . . O . . . .
//___ <> O O O O O O O O O O O O . O . .
// =! O O O O O O O O O O O O O O . O
// primit . . . . . . . . . . . . . . . .
// O means that the operand should be parenthesized
// . means that the operand should be printed as is
// =! stands for = or !=
// <> stands for < or > or <= or >=
additive_expression returns [String s]
{ s = "";
StringBuffer buf = new StringBuffer();
String s1, s2;
}
: #(PLUS s1=e1:subexpression s2=e2:subexpression)
{ switch (e1.getType()) {
case LESS_THAN:
case LESS_THAN_OR_EQUAL:
case GREATER_THAN:
case GREATER_THAN_OR_EQUAL:
case EQUAL:
case NOT_EQUAL:
case AND:
case OR:
buf.append("(").append(s1).append(") + ");
break;
default:
buf.append(s1).append(" + ");
}
switch (e2.getType()) {
case LESS_THAN:
case LESS_THAN_OR_EQUAL:
case GREATER_THAN:
case GREATER_THAN_OR_EQUAL:
case EQUAL:
case NOT_EQUAL:
case AND:
case OR:
buf.append("(").append(s2).append(")");
break;
default:
buf.append(s2);
}
s = buf.toString();
}
;
--
Pete Forman -./\.- Disclaimer: This post is originated
WesternGeco -./\.- by myself and does not represent
pete.forman at westerngeco.com -./\.- opinion of Schlumberger, Baker
http://petef.port5.com -./\.- Hughes or their divisions.
Yahoo! Groups Links
<*> To visit your group on the web, go to:
http://groups.yahoo.com/group/antlr-interest/
<*> To unsubscribe from this group, send an email to:
antlr-interest-unsubscribe at yahoogroups.com
<*> Your use of Yahoo! Groups is subject to:
http://docs.yahoo.com/info/terms/
More information about the antlr-interest
mailing list