A Small Grammar Issue with Classes

Kevin Smith zenparsing at gmail.com
Tue Dec 16 13:15:52 PST 2014


Hi all!

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.

    class C {
      private _a;
    }

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:

    class C {
      private _a;
      function isC(x) { return _a.has(x); } // Hypothetical only
      static cast(x) {
        if (isC(x)) return x;
        else return new this(x);
      }
    }

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:

    class C {
      function <next_token>

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:

    class C {
      async function <...more input...>

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.)

Thanks!
Kevin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20141216/9ae9cc8f/attachment.html>


More information about the es-discuss mailing list