Ok, Kay Roepke is in town and we've been discussing the faster expression parsing, among other things. Look for another entry on default StringTemplate generation or a parsing and tree parsing.
Found a ref to Keith Clarke's original recursive-descent precedence work
More on precedence climbing
ANTLR v3.2 will allow special rules for specifying expressions that are particularly efficient both in speed and space. Special rules will define either unary suffix operators, binary operators, or trinary operators by virtue of how they recurse. Precedence of operators is specified by the order in which the alternatives appear in the special rule. Left associativity is assumed. Right associativity is done with a token level option, TOKEN<associativity=right>
. The alternatives that are not specifying operators or that specify unary operators are grouped into a new rule. A special rule is rewritten into one that does not have left recursion. Semantic predicates are used to recurse more or less depending on the precedence of the next operator (first symbol of lookahead). Here is the special rule:
...
The backtrack option is specified in case it is needed, which is in this case because of the cast versus parenthesized expression in primary. Ooops. Just realized that the order of the alternatives is wrong. The primary will match the parenthesized expression before trying to cast. we need a way to figure this out.
The suffix rule has left recursive references to e
sell those must be removed. The parse_expr rule invokes a suffix after having matched e
already:
...
No Format |
---|
parse_expr[int p]
: primary
( {prec[input.LA(1)]>=p}?=> bop r= parse_expr[nextp(p)]
{
switch ( $bop.start.getType() ) {
case '+' :
case '-' :
action-for-this-alt
break;
...
case '=' :
action-for-this-alt
break;
default : // no action
}
}
| {postprec[input.LA(1)]>=p}?=> suffix[$e.tree]
)*
;
|
Trees for the binary operators could also be automatically done using the standard ANTLR mechanisms.
...
No Format |
---|
suffix[CommonTree lhs] : t='[' expre ']' -> ^(INDEX[$t] {$lhs} expre) | t='(' (expre (',' expre)*)? ')' -> ^(CALL[$t] {$lhs} expre*) | t='++' -> ^(POSTINC[$t] {$lhs}) ; |
...