A Small Grammar Issue with Classes
# C. Scott Ananian (10 years ago)
On Tue, Dec 16, 2014 at 4:15 PM, Kevin Smith <zenparsing at gmail.com> wrote:
We cannot tell with just two tokens of lookahead whether we need to parse a concise method or a function declaration.
[...]
Otherwise, are there any other parsing tricks which might help out? (I'm not 100% sure what our constraints are with respect to lookahead or rewind.)
Um, use three tokens of lookahead?
It doesn't seem like this is actually an ambiguous grammar, but maybe I'm missing something.
I can recommend both ANTLR and peg.js as robust solutions that can handle arbitrary lookahead.
While doing exploratory work on high-integrity classes and private field syntax I've run up against a parsing issue with classes that I thought might be good to bring to the list, even though it's probably too late to do anything about it now.
For private field syntax, it turns out that we want the declaration of the field to be located within the class body. E.g.
For refactoring purposes, it is desirable to allow the creation of helper functions which have access to the private field, but aren't properties of either the prototype or the constructor. To take a somewhat contrived example:
This leads us toward the idea of allowing declarations nested within the class body.
Grammatically, there is no problem extending ES6 class syntax to make this possible. We simply use lookahead to determine whether to parse a declaration or a concise method. Given this stream:
if
next_token
is not "(", then we know that it cannot be a method definition and therefore must be a function declaration.The trouble arises with the introduction of async functions. Given this stream:
We cannot tell with just two tokens of lookahead whether we need to parse a concise method or a function declaration.
In retrospect, for this reason I think it might have been a good idea to disallow "function" as a concise method identifier within class bodies. I regret that I wasn't able to see this issue sooner, but I appreciate that it may be too late to address it now.
Otherwise, are there any other parsing tricks which might help out? (I'm not 100% sure what our constraints are with respect to lookahead or rewind.)