1

This article states that:

To write a grammar that correctly expresses operator associativity:

  • For left associativity, use left recursion.
  • For right associativity, use right recursion.

Am I right that left-recursive grammar is the only way to control associativity on the grammar level?

The other way which is mentioned here is Associativity and Precedence Declarations:

%left +
%left *

which as I understand are implemented on the actual parser level implementation.

However, LL parser cannot handle left-recursive grammar. So if I want to implement recursive-descent parser I'll need to somehow work around it in the implementation. Is it correct?

Here what an author implementing recursive-descent parser mentions:

A recursive descent parser can parse grammar that doesn’t contain left-recursion. However, the original ECMAScript grammar contains a bunch of left-recursions that’ll be troublesome for a recursive descent parser. Step one for beginning the parser is to convert the grammar by eliminating left-recursion as I have done so here.

It is interesting to note that the method for eliminating left-recursion also messes with operator associativity, but I’ll deal with it later.

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
  • 1
    Yes, that's correct. – Bergi Sep 04 '17 at 17:10
  • @Bergi, thanks for helping me learn the compiler! – Max Koretskyi Sep 04 '17 at 17:13
  • It's not particularly difficult to handle left-associative operators in a recursive descent grammar; see [this answer](https://stackoverflow.com/a/33333514/1566221). That technique involves (a) rewriting the tail-recursion as a loop, and (b) rewriting the parse tree on the fly (although the rewrite is hardly noticeable). However, there is really no need: LR parser generators are easily available and do all the work for you, letting concentrate on more interesting things (like semantic processing of the parsed input: compiling, static analysis, pretty printing, or whatever.). – rici Sep 04 '17 at 22:08
  • @rici, thanks, I'm trying to reverse-engineer TypeScript compiler that's why I'm focused on the top-down parsers – Max Koretskyi Sep 05 '17 at 07:10

0 Answers0