[antlr-interest] more on left-recursive rules
Alan Rooks
Alan.Rooks at onsemi.com
Wed Feb 23 14:19:57 PST 2011
Terence Parr wrote:
> Got these examples into unit tests. :) feeling good.
> Ter
>
> // simple, no AST
> a : a ID
> | ID ;
>
> -------------
>
> declarator
> : declarator '['^ e ']'!
> | declarator '['^ ']'!
> | declarator '('^ ')'!
> | '*'^ declarator
> | '('! declarator ')'!
> | ID
> ;
>
>
> declarator
> : declarator '[' e ']' -> ^('[' declarator e)
> | declarator '[' ']' -> ^('[' declarator)
> | declarator '(' ')' -> ^('(' declarator)
> | '*' declarator -> ^('*' declarator)
> | '(' declarator ')' -> declarator
> | ID -> ID
> ;
>
> String[] tests = {
> "a", "a",
> "*a", "(* a)",
> "**a", "(* (* a))",
> "a[3]", "([ a 3)",
> "b[]", "([ b)",
> "(a)", "a",
> "a[]()", "(( ([ a))",
> "a[][]", "([ ([ a))",
> "*a[]", "(* ([ a))",
> "(*a)[]", "([ (* a))",
> };
>
> ---------------
>
> e : e '.'^ ID
> | e '.'^ 'this'
> | '-'^ e
> | e '*'^ e
> | e ('+'^|'-'^) e
> | INT
> | ID
> ;
>
> String[] tests = {
> "a", "a",
> "1", "1",
> "a+1", "(+ a 1)",
> "a*1", "(* a 1)",
> "a.b", "(. a b)",
> "a.this", "(. a this)",
> "a+b*c", "(+ a (* b c))",
> "a.b+1", "(+ (. a b) 1)",
> "-a", "(- a)",
> "-a+b", "(+ (- a) b)",
> "-a.b", "(- (. a b))",
> };
What do you get for "a-b+c"?
I hope it's "(+ (- a b) c)" and not "(- a (+ b c)".
(The former being left associative and the latter being right. Most people
would expect a-b+c to be evaluated left, as in (a-b)+c. Right? :-)
Alan
--
Alan Rooks
Software Tools Development
ON Semiconductor
More information about the antlr-interest
mailing list