-
Notifications
You must be signed in to change notification settings - Fork 27
/
parse.js
388 lines (369 loc) · 11.6 KB
/
parse.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
import {getLineInfo, TokContext, tokTypes as tt, Parser} from "acorn";
import defaultGlobals from "./globals.js";
import findReferences from "./references.js";
import findFeatures from "./features.js";
const SCOPE_FUNCTION = 2;
const SCOPE_ASYNC = 4;
const SCOPE_GENERATOR = 8;
export function parseCell(input, {tag, raw, globals, ...options} = {}) {
let cell;
// Parse empty input as JavaScript to keep ensure resulting ast
// is consistent for all empty input cases.
if (tag != null && input) {
cell = TemplateCellParser.parse(input, options);
const parsedTag = CellTagParser.parse(tag, options);
parseReferences(parsedTag, tag, globals);
parseFeatures(parsedTag, tag);
cell.tag = parsedTag;
cell.raw = !!raw;
} else {
cell = CellParser.parse(input, options);
}
parseReferences(cell, input, globals);
parseFeatures(cell, input);
return cell;
}
export class CellParser extends Parser {
constructor(options, ...args) {
super(Object.assign({ecmaVersion: 13}, options), ...args);
}
enterScope(flags) {
if (flags & SCOPE_FUNCTION) ++this.O_function;
return super.enterScope(flags);
}
exitScope() {
if (this.currentScope().flags & SCOPE_FUNCTION) --this.O_function;
return super.exitScope();
}
parseForIn(node, init) {
if (this.O_function === 1 && node.await) this.O_async = true;
return super.parseForIn(node, init);
}
parseAwait() {
if (this.O_function === 1) this.O_async = true;
return super.parseAwait();
}
parseYield(noIn) {
if (this.O_function === 1) this.O_generator = true;
return super.parseYield(noIn);
}
parseImport(node) {
this.next();
node.specifiers = this.parseImportSpecifiers();
if (this.type === tt._with) {
this.next();
node.injections = this.parseImportSpecifiers();
}
this.expectContextual("from");
node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected();
return this.finishNode(node, "ImportDeclaration");
}
parseImportSpecifiers() {
const nodes = [];
const identifiers = new Set;
let first = true;
this.expect(tt.braceL);
while (!this.eat(tt.braceR)) {
if (first) {
first = false;
} else {
this.expect(tt.comma);
if (this.afterTrailingComma(tt.braceR)) break;
}
const node = this.startNode();
node.view = this.eatContextual("viewof");
node.mutable = node.view ? false : this.eatContextual("mutable");
node.imported = this.parseIdent();
this.checkUnreserved(node.imported);
this.checkLocal(node.imported);
if (this.eatContextual("as")) {
node.local = this.parseIdent();
this.checkUnreserved(node.local);
this.checkLocal(node.local);
} else {
node.local = node.imported;
}
this.checkLValSimple(node.local, "let");
if (identifiers.has(node.local.name)) {
this.raise(node.local.start, `Identifier '${node.local.name}' has already been declared`);
}
identifiers.add(node.local.name);
nodes.push(this.finishNode(node, "ImportSpecifier"));
}
return nodes;
}
parseExprAtom(refDestructuringErrors) {
return (
this.parseMaybeKeywordExpression("viewof", "ViewExpression") ||
this.parseMaybeKeywordExpression("mutable", "MutableExpression") ||
super.parseExprAtom(refDestructuringErrors)
);
}
startCell() {
this.O_function = 0;
this.O_async = false;
this.O_generator = false;
this.strict = true;
this.enterScope(SCOPE_FUNCTION | SCOPE_ASYNC | SCOPE_GENERATOR);
}
finishCell(node, body, id) {
if (id) this.checkLocal(id);
node.id = id;
node.body = body;
node.async = this.O_async;
node.generator = this.O_generator;
this.exitScope();
return this.finishNode(node, "Cell");
}
parseCell(node, eof) {
const lookahead = new CellParser({}, this.input, this.start);
let token = lookahead.getToken();
let body = null;
let id = null;
this.startCell();
// An import?
if (token.type === tt._import && lookahead.getToken().type !== tt.parenL) {
body = this.parseImport(this.startNode());
}
// A non-empty cell?
else if (token.type !== tt.eof && token.type !== tt.semi) {
// A named cell?
if (token.type === tt.name) {
if (token.value === "viewof" || token.value === "mutable") {
token = lookahead.getToken();
if (token.type !== tt.name) {
lookahead.unexpected();
}
}
token = lookahead.getToken();
if (token.type === tt.eq) {
id =
this.parseMaybeKeywordExpression("viewof", "ViewExpression") ||
this.parseMaybeKeywordExpression("mutable", "MutableExpression") ||
this.parseIdent();
token = lookahead.getToken();
this.expect(tt.eq);
}
}
// A block?
if (token.type === tt.braceL) {
body = this.parseBlock();
}
// An expression?
// Possibly a function or class declaration?
else {
body = this.parseExpression();
if (
id === null &&
(body.type === "FunctionExpression" ||
body.type === "ClassExpression")
) {
id = body.id;
}
}
}
this.semicolon();
if (eof) this.expect(tt.eof); // TODO
return this.finishCell(node, body, id);
}
parseTopLevel(node) {
return this.parseCell(node, true);
}
toAssignable(node, isBinding, refDestructuringErrors) {
return node.type === "MutableExpression"
? node
: super.toAssignable(node, isBinding, refDestructuringErrors);
}
checkLocal(id) {
const node = id.id || id;
if (defaultGlobals.has(node.name) || node.name === "arguments") {
this.raise(node.start, `Identifier '${node.name}' is reserved`);
}
}
checkUnreserved(node) {
if (node.name === "viewof" || node.name === "mutable") {
this.raise(node.start, `Unexpected keyword '${node.name}'`);
}
return super.checkUnreserved(node);
}
checkLValSimple(expr, bindingType, checkClashes) {
return super.checkLValSimple(
expr.type === "MutableExpression" ? expr.id : expr,
bindingType,
checkClashes
);
}
unexpected(pos) {
this.raise(
pos != null ? pos : this.start,
this.type === tt.eof ? "Unexpected end of input" : "Unexpected token"
);
}
parseMaybeKeywordExpression(keyword, type) {
if (this.isContextual(keyword)) {
const node = this.startNode();
this.next();
node.id = this.parseIdent();
return this.finishNode(node, type);
}
}
}
// Based on acorn’s q_tmpl. We will use this to initialize the
// parser context so our `readTemplateToken` override is called.
// `readTemplateToken` is based on acorn's `readTmplToken` which
// is used inside template literals. Our version allows backQuotes.
const o_tmpl = new TokContext(
"`", // token
true, // isExpr
true, // preserveSpace
parser => readTemplateToken.call(parser) // override
);
export class TemplateCellParser extends CellParser {
constructor(...args) {
super(...args);
// Initialize the type so that we're inside a backQuote
this.type = tt.backQuote;
this.exprAllowed = false;
}
initialContext() {
// Provide our custom TokContext
return [o_tmpl];
}
parseCell(node) {
this.startCell();
// Fix for nextToken calling finishToken(tt.eof)
if (this.type === tt.eof) this.value = "";
// Based on acorn.Parser.parseTemplate
const isTagged = true;
const body = this.startNode();
body.expressions = [];
let curElt = this.parseTemplateElement({isTagged});
body.quasis = [curElt];
while (this.type !== tt.eof) {
this.expect(tt.dollarBraceL);
body.expressions.push(this.parseExpression());
this.expect(tt.braceR);
body.quasis.push(curElt = this.parseTemplateElement({isTagged}));
}
curElt.tail = true;
this.next();
this.finishNode(body, "TemplateLiteral");
this.expect(tt.eof);
return this.finishCell(node, body, null);
}
}
// This is our custom override for parsing a template that allows backticks.
// Based on acorn's readInvalidTemplateToken.
function readTemplateToken() {
out: for (; this.pos < this.input.length; this.pos++) {
switch (this.input.charCodeAt(this.pos)) {
case 92: { // slash
if (this.pos < this.input.length - 1) ++this.pos; // not a terminal slash
break;
}
case 36: { // dollar
if (this.input.charCodeAt(this.pos + 1) === 123) { // dollar curly
if (this.pos === this.start && this.type === tt.invalidTemplate) {
this.pos += 2;
return this.finishToken(tt.dollarBraceL);
}
break out;
}
break;
}
}
}
return this.finishToken(tt.invalidTemplate, this.input.slice(this.start, this.pos));
}
export class CellTagParser extends Parser {
constructor(options, ...args) {
super(Object.assign({ecmaVersion: 12}, options), ...args);
}
enterScope(flags) {
if (flags & SCOPE_FUNCTION) ++this.O_function;
return super.enterScope(flags);
}
exitScope() {
if (this.currentScope().flags & SCOPE_FUNCTION) --this.O_function;
return super.exitScope();
}
parseForIn(node, init) {
if (this.O_function === 1 && node.await) this.O_async = true;
return super.parseForIn(node, init);
}
parseAwait() {
if (this.O_function === 1) this.O_async = true;
return super.parseAwait();
}
parseYield(noIn) {
if (this.O_function === 1) this.O_generator = true;
return super.parseYield(noIn);
}
parseTopLevel(node) {
this.O_function = 0;
this.O_async = false;
this.O_generator = false;
this.strict = true;
this.enterScope(SCOPE_FUNCTION | SCOPE_ASYNC | SCOPE_GENERATOR);
node.body = this.parseExpression();
node.input = this.input;
node.async = this.O_async;
node.generator = this.O_generator;
this.exitScope();
return this.finishNode(node, "CellTag");
}
}
// Find references.
// Check for illegal references to arguments.
// Check for illegal assignments to global references.
function parseReferences(cell, input, globals = defaultGlobals) {
if (!cell.body) {
cell.references = [];
} else if (cell.body.type === "ImportDeclaration") {
cell.references = cell.body.injections
? cell.body.injections.map(i => i.imported)
: [];
} else {
try {
cell.references = findReferences(cell, globals);
} catch (error) {
if (error.node) {
const loc = getLineInfo(input, error.node.start);
error.message += ` (${loc.line}:${loc.column})`;
error.pos = error.node.start;
error.loc = loc;
delete error.node;
}
throw error;
}
}
return cell;
}
// Find features: file attachments, secrets, database clients.
// Check for illegal references to arguments.
// Check for illegal assignments to global references.
function parseFeatures(cell, input) {
if (cell.body && cell.body.type !== "ImportDeclaration") {
try {
cell.fileAttachments = findFeatures(cell, "FileAttachment");
cell.databaseClients = findFeatures(cell, "DatabaseClient");
cell.secrets = findFeatures(cell, "Secret");
cell.notificationClients = findFeatures(cell, "NotificationClient");
} catch (error) {
if (error.node) {
const loc = getLineInfo(input, error.node.start);
error.message += ` (${loc.line}:${loc.column})`;
error.pos = error.node.start;
error.loc = loc;
delete error.node;
}
throw error;
}
} else {
cell.fileAttachments = new Map();
cell.databaseClients = new Map();
cell.secrets = new Map();
cell.notificationClients = new Map();
}
return cell;
}