3 ms·
This is a great article that I've recommended many times for learning about precedence-climbing, but I found it much more intuitive and concise to derive preced
by userbinator 11y ago
This is a great article that I've recommended many times for learning about precedence-climbing, but I found it much more intuitive and concise to derive precedence climbing as the refactoring of a recursive-descent parser in two steps. This is succintly describable as:
1. Notice how all the functions in an RD parser are almost the same: call the next-higher-level, then loop with that call while the current token is at this level. The topmost level is for consuming a terminal or a parenthesised subexpression. That can easily be turned into one parameterised function and a table lookup for the tokens.
2. The first set of recursive calls always goes "to the top", so why not call that directly. This is the 'P' function in the article. The second set of recursive calls are nothing more than finding the right level to process the current token, so jump directly to that level by calling the function directly with that level number instead of repeatedly descending via recursive calls until the current level matches the token. With the current token being of level n, the parameterised RD parser calls expr(1) -> expr(2) -> expr(3) -> ... expr(n) when it could just call expr(n).
I think this is such an elegantly simple algorithm that anyone learning computer science should have implemented at least once along with the usual study of recursive data structures. It's also a very good step towards understanding how a compiler works.