subscript
Version:
Modular expression parser & evaluator
40 lines (34 loc) • 1.21 kB
JavaScript
// Class declarations and expressions - parse half
// class A extends B { ... }
import { binary, unary, token, expr, next, parse, keyword, word, skip } from '../parse.js';
import { block } from './if.js';
const TOKEN = 200, PREFIX = 140, COMP = 90, STATIC = 175, CALL = 160;
const HERITAGE = CALL - .5;
// static member → ['static', member]
// STATIC > ACCESS (170) so `static m` doesn't pull `(` into the operand as a
// function call — leaves the `(` for the outer method-shorthand handler.
unary('static', STATIC);
// instanceof: object instanceof Constructor
binary('instanceof', COMP);
// #private fields: #x → '#x' (identifier starting with #)
token('#', TOKEN, a => {
if (a) return;
const id = next(parse.id);
return id ? '#' + id : void 0;
});
// class [Name] [extends Base] { body }
keyword('class', TOKEN, () => {
parse.space();
let name = next(parse.id) || null;
// 'extends' parsed as name? → anonymous class
if (name === 'extends') {
name = null;
parse.space();
} else {
parse.space();
if (!word('extends')) return ['class', name, null, block()];
skip(7); // skip 'extends'
parse.space();
}
return ['class', name, expr(HERITAGE), block()];
});