My knowledge on formal language and compiler theory is limited. So I am learning by the book The Definitive ANTLR 4 Reference
by Terence Parr.
In the book, it says:
Now, with v4, you can match expressions with rules that look like this:
expr : expr '*' expr // match subexpressions joined with '*' operator | expr '+' expr // match subexpressions joined with '+' operator | INT // matches simple integer atom ;
Self-referential rules like expr are recursive and, in particular, left recursive because at least one of its alternatives immediately refers to itself.
But I think the bold part is incorrect. Accroding to here, the production is left-recursive if the leftmost symbol on the right side is the same as the non terminal on the left side. For example,
expr → expr + term.
So back to the Terence's book's sample, it is neither left recursive nor right recursive. It's merely recursive.
Am I right? Or did I misunderstand the author?
ADD 1
Thanks for the replies so far. Sorry I didn't make myself clear enough.
My understanding is: being left-recursive
means the left-most
part of the right-side is the same as the non-terminal on the left side. AND the remaining part of the right-side is ONLY suffix which is NOT the left-side.
In the Parr's book sample, the reamining part of the right-side is not a suffix, it's another same expr
, so I don't think it strictly fits the rule of being left-recursive.
expr
, and (the leftmost) on right side isexpr
so what's your rationale behind claiming that the rule stated in "according to here" is not satisfied? Is it the nonrecursive third part of the alternative (| INT
) that makes you think so? – quetzalcoatlexpr → expr + term
is left-recursive,expr → term + expr
is right-recursive, andexpr → expr + expr
is simply both left- and right- recursive at the same time.. <strike>Theterm
means "anything"</strike> (uh oh.. strike-through doesnt work in comments..) – quetzalcoatlThe production is left-recursive if the leftmost symbol on the right side is the same as the non terminal on the left side. For example, expr → expr + term.
uses a phrase "for example", which, actually, doesn't say that this is the only valid example. This example doesn't indicate thatexpr -> expr*expr
is invalid. I'd consider this article an overview rather than strict definitions. – quetzalcoatl