[antlr-interest] New article on StringTemplates and Treewalke rs
Andy Tripp
antlr at jazillian.com
Wed Jan 11 07:49:13 PST 2006
>>/ --------------------------------------------------------------------------------------
>/>/ // certain places in Java require a boolean type, where C allows "int" type:
>/>/ // * for condition: for (int i=0; b; i++)
>/>/ // * while: while (b)
>/>/ // * do-while: do { } while (b);
>/>/ // * if: if (b)
>/>/
>/>/ public class ForceToBooleanRule extends Rule {
>/>/ private String newexpr;
>/>/ private Token startToken = null;
>/>/ private Token endToken = null;
>/>/
>/>/ // if we see one of the patterns listed above, set startToken and
>/>/ endToken and return true.
>/>/ public boolean match(Source source) {
>/>/ String current = source.currentToken.getText();
>/>/ if (current.equals("for")) {
>/
>Is there some reason you just didn't do
>if (source.currentToken.getType()==Parser.FOR)...? :)
>
>
Only a very small reason: I find it easier to remember that this token
has text "for" than to remember that the lexer type is Parser.FOR.
Not a big deal, and half the time I do use "Parser.FOR". But not as
trivial as
you might think considering that "<" is Parser.LTE in the C grammar and it's
"LE" in the Java grammar, and it's not clear whether this rule working on C
code, Java code, or (most likely) a mix of the two :)
>>/ // here is where the expression is parsed and changed to be
>/>/ boolean type:
>/>/ newexpr = ExpressionUtils.forceToBoolean(expr, source);
>/>/ return !expr.equals(newexpr);
>/>/ }
>/
>forceToBoolean must be... err... interesting :)
>
It's actually quite straightforward: parse the expression into an AST,
and recursively process it.
When we hit a "0" node, replace it with a "false", any other "int" node,
replace it with "true".
Most boolean operators are replaced with "!=", and we do some special
stuff for type casts.
When we find variables and function calls, we've got to look up the type
in a symbol table.
Andy
More information about the antlr-interest
mailing list