@tylix/compiler 0.5.2 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/package.json +30 -2
- package/src/ast/nodes.js +219 -16
- package/src/ast/substituteCapabilityRefs.js +185 -61
- package/src/codegen/emitStatementLines.js +98 -54
- package/src/codegen/generateExpression.js +339 -36
- package/src/codegen/generateMethod.js +5 -3
- package/src/codegen/generatePage.js +74 -44
- package/src/codegen/generateStatement.js +169 -20
- package/src/codegen/generateTemplate.js +183 -101
- package/src/codegen/generateTemplateExpression.js +102 -59
- package/src/codegen/jsGlobals.js +211 -0
- package/src/compileComponent.js +39 -8
- package/src/imports/extractImports.js +112 -26
- package/src/imports/resolveImports.js +186 -0
- package/src/index.js +3 -2
- package/src/lexer/Lexer.js +430 -235
- package/src/lexer/tokenTypes.js +32 -7
- package/src/parser/Parser.js +2176 -325
- package/src/parser/languageOptions.js +16 -0
- package/src/parser/parseExpressionString.js +23 -7
- package/src/parser/parsePageFile.js +139 -58
- package/src/parser/parseTemplate.js +350 -62
- package/src/renderPageDocument.js +338 -56
- package/src/runtime/capability.js +39 -17
- package/src/runtime/loadingIndicator.js +91 -29
- package/src/runtime/reactive.js +362 -64
- package/src/runtime/useApi.js +74 -13
- package/src/runtime/useChannel.js +27 -6
- package/src/typecheck/buildVirtualTs.js +23 -12
- package/src/typecheck/tylix-globals.d.ts +23 -4
- package/src/typecheck/typedTemplateExpr.js +195 -53
- package/src/typecheckPage.js +28 -4
- package/src/codegen/generateExpression.array.test.js +0 -13
- package/src/codegen/generateExpression.callexpr.test.js +0 -19
- package/src/codegen/generateExpression.test.js +0 -59
- package/src/codegen/generateMethod.asyncawait.test.js +0 -37
- package/src/codegen/generateMethod.ifstatement.test.js +0 -20
- package/src/codegen/generateMethod.test.js +0 -81
- package/src/codegen/generatePage.onmount.test.js +0 -46
- package/src/codegen/generatePage.test.js +0 -138
- package/src/codegen/generateStatement.test.js +0 -31
- package/src/codegen/generateTemplate.ifeach.test.js +0 -138
- package/src/codegen/generateTemplate.test.js +0 -149
- package/src/codegen/generateTemplateExpression.test.js +0 -34
- package/src/compileComponent.test.js +0 -121
- package/src/imports/resolvePackageComponents.js +0 -41
- package/src/lexer/Lexer.test.js +0 -151
- package/src/parser/Parser.array.test.js +0 -37
- package/src/parser/Parser.asyncawait.test.js +0 -33
- package/src/parser/Parser.ifstatement.test.js +0 -20
- package/src/parser/Parser.onmount.test.js +0 -18
- package/src/parser/Parser.test.js +0 -315
- package/src/parser/parseComponent.test.js +0 -53
- package/src/parser/parsePageFile.test.js +0 -101
- package/src/parser/parseTemplate.ifeach.test.js +0 -33
- package/src/parser/parseTemplate.pre.test.js +0 -39
- package/src/parser/parseTemplate.test.js +0 -112
- package/src/renderPageDocument.test.js +0 -125
- package/src/runtime/reactive.test.js +0 -106
- package/test/dashboard-syntax.test.js +0 -116
package/src/parser/Parser.js
CHANGED
|
@@ -7,19 +7,30 @@ import {
|
|
|
7
7
|
AssignmentExpr,
|
|
8
8
|
BinaryExpr,
|
|
9
9
|
UnaryExpr,
|
|
10
|
+
UpdateExpr,
|
|
11
|
+
TypeDeclaration,
|
|
12
|
+
EnumDeclaration,
|
|
10
13
|
TernaryExpr,
|
|
11
14
|
NullishCoalescingExpr,
|
|
12
15
|
ArrowFunctionExpr,
|
|
16
|
+
FunctionExpr,
|
|
17
|
+
FunctionDeclaration,
|
|
13
18
|
TemplateLiteralExpr,
|
|
19
|
+
TaggedTemplateExpr,
|
|
14
20
|
SpreadElement,
|
|
21
|
+
SequenceExpr,
|
|
22
|
+
YieldExpr,
|
|
15
23
|
Identifier,
|
|
16
24
|
MemberExpr,
|
|
17
25
|
Literal,
|
|
18
26
|
ReturnStatement,
|
|
19
27
|
ExpressionStatement,
|
|
28
|
+
EmptyStatement,
|
|
20
29
|
CallExpr,
|
|
21
30
|
NewExpr,
|
|
22
31
|
AwaitExpr,
|
|
32
|
+
AsExpr,
|
|
33
|
+
NonNullExpr,
|
|
23
34
|
VariableDeclaration,
|
|
24
35
|
ObjectExpr,
|
|
25
36
|
ArrayExpr,
|
|
@@ -28,18 +39,26 @@ import {
|
|
|
28
39
|
TryStatement,
|
|
29
40
|
IfStatement,
|
|
30
41
|
ForInStatement,
|
|
42
|
+
ForKeysStatement,
|
|
43
|
+
ForStatement,
|
|
31
44
|
ForRangeStatement,
|
|
32
45
|
RepeatStatement,
|
|
33
46
|
BreakStatement,
|
|
34
47
|
ContinueStatement,
|
|
48
|
+
LabeledStatement,
|
|
49
|
+
DebuggerStatement,
|
|
50
|
+
ClassDeclaration,
|
|
51
|
+
ClassExpr,
|
|
35
52
|
CapabilityRefNode,
|
|
36
53
|
MetaEntryNode,
|
|
37
54
|
BlockStatement,
|
|
38
55
|
ThrowStatement,
|
|
39
56
|
WhileStatement,
|
|
57
|
+
DoWhileStatement,
|
|
40
58
|
SwitchStatement,
|
|
41
59
|
} from '../ast/nodes.js'
|
|
42
60
|
import { parseExpressionString } from './parseExpressionString.js'
|
|
61
|
+
import { generateExpression } from '../codegen/generateExpression.js'
|
|
43
62
|
|
|
44
63
|
const COMPARISON_SYMBOLS = {
|
|
45
64
|
[TokenType.GT]: '>',
|
|
@@ -47,6 +66,7 @@ const COMPARISON_SYMBOLS = {
|
|
|
47
66
|
[TokenType.GTE]: '>=',
|
|
48
67
|
[TokenType.LTE]: '<=',
|
|
49
68
|
[TokenType.INSTANCEOF]: 'instanceof',
|
|
69
|
+
[TokenType.IN]: 'in',
|
|
50
70
|
}
|
|
51
71
|
|
|
52
72
|
const ADDITIVE_SYMBOLS = {
|
|
@@ -67,49 +87,190 @@ const KEYWORD_TOKEN_TYPES = new Set(Object.values(KEYWORDS))
|
|
|
67
87
|
// `this.count += 1` becomes exactly the same AST as if the dev had
|
|
68
88
|
// written `this.count = this.count + 1`, so no codegen changes are
|
|
69
89
|
// needed at all; generateExpression already knows how to emit both
|
|
70
|
-
// node types.
|
|
90
|
+
// node types. (`||=` / `&&=` / `??=` and the shift forms are handled
|
|
91
|
+
// separately in parseAssignment.)
|
|
71
92
|
const COMPOUND_ASSIGNMENT_OPS = {
|
|
72
93
|
[TokenType.PLUS_EQUALS]: '+',
|
|
73
94
|
[TokenType.MINUS_EQUALS]: '-',
|
|
74
95
|
[TokenType.STAR_EQUALS]: '*',
|
|
75
96
|
[TokenType.SLASH_EQUALS]: '/',
|
|
76
97
|
[TokenType.PERCENT_EQUALS]: '%',
|
|
98
|
+
[TokenType.STAR_STAR_EQUALS]: '**',
|
|
99
|
+
[TokenType.AMP_EQUALS]: '&',
|
|
100
|
+
[TokenType.PIPE_EQUALS]: '|',
|
|
101
|
+
[TokenType.CARET_EQUALS]: '^',
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Renders a destructuring pattern back to source text. Arrow and
|
|
105
|
+
// function params are stored as plain strings, so `([k, v]) => ...`
|
|
106
|
+
// and `({ id, name }) => ...` are kept as "[k, v]" / "{ id, name }"
|
|
107
|
+
// and emitted verbatim by the codegen.
|
|
108
|
+
function bindingToSource(t) {
|
|
109
|
+
if (typeof t === 'string') return t
|
|
110
|
+
const withDefault = (src, def) =>
|
|
111
|
+
def ? `${src} = ${generateExpression(def)}` : src
|
|
112
|
+
if (t.type === 'ObjectPattern') {
|
|
113
|
+
const parts = t.properties.map((p) => {
|
|
114
|
+
const plain = typeof p.binding === 'string' && p.binding === p.key
|
|
115
|
+
const lhs = plain ? p.key : `${p.key}: ${bindingToSource(p.binding)}`
|
|
116
|
+
return withDefault(lhs, p.defaultValue)
|
|
117
|
+
})
|
|
118
|
+
if (t.rest) parts.push(`...${t.rest}`)
|
|
119
|
+
return `{ ${parts.join(', ')} }`
|
|
120
|
+
}
|
|
121
|
+
const parts = t.elements.map((el) =>
|
|
122
|
+
el === null ? '' : withDefault(bindingToSource(el.binding), el.defaultValue),
|
|
123
|
+
)
|
|
124
|
+
if (t.rest) parts.push(`...${t.rest}`)
|
|
125
|
+
return `[${parts.join(', ')}]`
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Optional extras on function nodes, attached only when present so
|
|
129
|
+
// existing AST shapes stay unchanged.
|
|
130
|
+
const PARAM_MODIFIERS = new Set(['public', 'private', 'protected', 'readonly', 'override'])
|
|
131
|
+
|
|
132
|
+
function signatureExtras(fn) {
|
|
133
|
+
const extra = {}
|
|
134
|
+
if (fn.typeParams) extra.typeParams = fn.typeParams
|
|
135
|
+
if (fn.returnType) extra.returnType = fn.returnType
|
|
136
|
+
return extra
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Tokens that start a statement. After `if (cond)` one of these means
|
|
140
|
+
// the parens were just the condition and a braceless body follows.
|
|
141
|
+
const STATEMENT_START_TOKENS = new Set([
|
|
142
|
+
TokenType.RETURN, TokenType.THROW, TokenType.BREAK, TokenType.CONTINUE,
|
|
143
|
+
TokenType.IF, TokenType.WHILE, TokenType.DO, TokenType.SWITCH,
|
|
144
|
+
TokenType.FOR, TokenType.REPEAT, TokenType.TRY, TokenType.CONST,
|
|
145
|
+
TokenType.LET, TokenType.FUNCTION, TokenType.ASYNC, TokenType.AWAIT,
|
|
146
|
+
TokenType.NEW, TokenType.TYPEOF, TokenType.DELETE, TokenType.VOID,
|
|
147
|
+
TokenType.PLUS_PLUS, TokenType.MINUS_MINUS, TokenType.SEMICOLON,
|
|
148
|
+
])
|
|
149
|
+
|
|
150
|
+
// True when token `b` starts exactly where token `a` ends -- i.e. the
|
|
151
|
+
// two were written with no whitespace between them.
|
|
152
|
+
function adjacent(a, b) {
|
|
153
|
+
return !!a && !!b && b.start === a.start + String(a.value).length
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// True when evaluating `node` would run an assignment, ++/--, await
|
|
157
|
+
// or yield. Compound assignment (`a[i++] += 1`) and ++/-- duplicate
|
|
158
|
+
// their target in the desugared AST, so such a target would be
|
|
159
|
+
// evaluated twice. Nested function bodies don't run when the target
|
|
160
|
+
// is evaluated, so they are skipped.
|
|
161
|
+
function containsMutation(node) {
|
|
162
|
+
if (!node || typeof node !== 'object') return false
|
|
163
|
+
if (Array.isArray(node)) return node.some(containsMutation)
|
|
164
|
+
if (node instanceof RegExp) return false
|
|
165
|
+
if (
|
|
166
|
+
node.type === 'AssignmentExpression' ||
|
|
167
|
+
node.type === 'UpdateExpression' ||
|
|
168
|
+
node.type === 'AwaitExpression' ||
|
|
169
|
+
node.type === 'YieldExpression'
|
|
170
|
+
) {
|
|
171
|
+
return true
|
|
172
|
+
}
|
|
173
|
+
if (
|
|
174
|
+
node.type === 'ArrowFunctionExpression' ||
|
|
175
|
+
node.type === 'FunctionExpression'
|
|
176
|
+
) {
|
|
177
|
+
return false
|
|
178
|
+
}
|
|
179
|
+
return Object.values(node).some(
|
|
180
|
+
(v) => v && typeof v === 'object' && containsMutation(v),
|
|
181
|
+
)
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// `a has b` works for arrays and strings (includes) AND Sets/Maps
|
|
185
|
+
// (has). Built from ordinary nodes, so every generator (script,
|
|
186
|
+
// template, virtual .ts) handles it with no new node type:
|
|
187
|
+
// ((__c, __v) => typeof __c.has === "function"
|
|
188
|
+
// ? __c.has(__v) : __c.includes(__v))(a, b)
|
|
189
|
+
function hasExpr(collection, value) {
|
|
190
|
+
const c = Identifier('__c')
|
|
191
|
+
const v = Identifier('__v')
|
|
192
|
+
const test = BinaryExpr(
|
|
193
|
+
'===',
|
|
194
|
+
UnaryExpr('typeof', MemberExpr(c, 'has')),
|
|
195
|
+
Literal('function'),
|
|
196
|
+
)
|
|
197
|
+
const body = TernaryExpr(
|
|
198
|
+
test,
|
|
199
|
+
CallExpr(MemberExpr(c, 'has'), [v]),
|
|
200
|
+
CallExpr(MemberExpr(c, 'includes'), [v]),
|
|
201
|
+
)
|
|
202
|
+
const fn = ArrowFunctionExpr(
|
|
203
|
+
['__c', '__v'],
|
|
204
|
+
body,
|
|
205
|
+
[null, null],
|
|
206
|
+
false,
|
|
207
|
+
[null, null],
|
|
208
|
+
)
|
|
209
|
+
return CallExpr(fn, [collection, value])
|
|
77
210
|
}
|
|
78
211
|
|
|
79
212
|
/**
|
|
80
213
|
* Parses the token stream from the Lexer into a Page AST.
|
|
81
214
|
*
|
|
82
215
|
* Expressions are parsed with real precedence-climbing, low to high:
|
|
83
|
-
* arrow function (x => expr, (a, b) => expr,
|
|
216
|
+
* arrow function (x => expr, (a, b = 1) => expr, destructured and
|
|
217
|
+
* rest params, optional params, return types, block bodies
|
|
84
218
|
* x => { ... }, and the async forms of all of these) -- tried
|
|
85
|
-
* first, with backtracking
|
|
86
|
-
*
|
|
87
|
-
* assignment (= += -= *= /= %= ??=)
|
|
219
|
+
* first, with backtracking
|
|
220
|
+
* yield / yield* (inside generators)
|
|
221
|
+
* assignment (= += -= *= /= %= **= ??= ||= &&= &= |= ^= <<= >>= >>>=)
|
|
88
222
|
* ternary (?:)
|
|
89
223
|
* nullish (??)
|
|
90
|
-
* logical or (or)
|
|
91
|
-
* logical and (and)
|
|
92
|
-
*
|
|
93
|
-
*
|
|
224
|
+
* logical or (or, ||)
|
|
225
|
+
* logical and (and, &&)
|
|
226
|
+
* bitwise or (|)
|
|
227
|
+
* bitwise xor (^)
|
|
228
|
+
* bitwise and (&)
|
|
229
|
+
* equality (is / is not, also ===, !==, ==, !=)
|
|
230
|
+
* comparison (> < >= <= instanceof in, and the `as` / `satisfies` casts)
|
|
94
231
|
* predicate (has / exists / missing)
|
|
232
|
+
* shift (<< >> >>>)
|
|
95
233
|
* additive (+ -)
|
|
96
234
|
* multiplicative (* / %)
|
|
97
235
|
* exponent (**, right-associative)
|
|
98
|
-
* unary (not, -, await, typeof, prefix ++/--)
|
|
236
|
+
* unary (not, !, ~, -, +, await, typeof, delete, void, prefix ++/--)
|
|
99
237
|
* postfix (x++, x--)
|
|
100
|
-
* member/call (a.b, a(), a?.b, a?.())
|
|
101
|
-
* primary (literals,
|
|
102
|
-
* template literals
|
|
238
|
+
* member/call (a.b, a(), a?.b, a?.(), tag`text`, and the non-null `x!`)
|
|
239
|
+
* primary (literals, regex, bigint, identifiers, grouping and the
|
|
240
|
+
* comma operator, arrays, objects, template literals,
|
|
241
|
+
* function and class expressions, new.target)
|
|
103
242
|
*
|
|
104
243
|
* `x++` / `++x` desugar to `x = x + 1` (same trick as compound
|
|
105
244
|
* assignment), so the expression's value is the NEW value in both
|
|
106
|
-
* forms, unlike JS where postfix yields the old one.
|
|
107
|
-
*
|
|
245
|
+
* forms, unlike JS where postfix yields the old one.
|
|
246
|
+
*
|
|
247
|
+
* Shifts are recombined from adjacent LT/GT tokens (see
|
|
248
|
+
* shiftOperatorAt) because the Lexer never emits << or >> as single
|
|
249
|
+
* tokens -- that keeps `Array<Array<T>>` parseable as a type.
|
|
250
|
+
*
|
|
251
|
+
* Contextual words (`static`, `get`, `set`, `as`, `satisfies`,
|
|
252
|
+
* `yield`, `class`, `extends`, `debugger`) are ordinary identifier
|
|
253
|
+
* tokens; the parser recognises them by position.
|
|
108
254
|
*/
|
|
109
255
|
export class Parser {
|
|
110
|
-
constructor(tokens) {
|
|
256
|
+
constructor(tokens, options = {}) {
|
|
111
257
|
this.tokens = tokens
|
|
112
258
|
this.pos = 0
|
|
259
|
+
this.options = options
|
|
260
|
+
this.looseNot = options.not === 'loose'
|
|
261
|
+
// True while parsing the body of a generator, where `yield` is an
|
|
262
|
+
// operator instead of an ordinary name.
|
|
263
|
+
this.inGenerator = false
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
withGenerator(flag, fn) {
|
|
267
|
+
const previous = this.inGenerator
|
|
268
|
+
this.inGenerator = flag
|
|
269
|
+
try {
|
|
270
|
+
return fn()
|
|
271
|
+
} finally {
|
|
272
|
+
this.inGenerator = previous
|
|
273
|
+
}
|
|
113
274
|
}
|
|
114
275
|
|
|
115
276
|
parse() {
|
|
@@ -119,6 +280,7 @@ export class Parser {
|
|
|
119
280
|
computed: [],
|
|
120
281
|
actions: [],
|
|
121
282
|
uses: [],
|
|
283
|
+
helpers: [],
|
|
122
284
|
onMount: null,
|
|
123
285
|
}
|
|
124
286
|
|
|
@@ -161,6 +323,8 @@ export class Parser {
|
|
|
161
323
|
)
|
|
162
324
|
} else if (this.match(TokenType.META)) {
|
|
163
325
|
page.meta = this.parseSectionBlock(this.parseMetaEntry.bind(this))
|
|
326
|
+
} else if (this.isModuleDeclarationAhead()) {
|
|
327
|
+
page.helpers.push(this.parseStatement())
|
|
164
328
|
} else {
|
|
165
329
|
throw new Error(
|
|
166
330
|
`Unexpected token ${this.peek().type} at line ${this.peek().line}`,
|
|
@@ -236,9 +400,10 @@ export class Parser {
|
|
|
236
400
|
)
|
|
237
401
|
}
|
|
238
402
|
|
|
239
|
-
|
|
403
|
+
isAtSectionBoundary(allowDeclarations = false) {
|
|
240
404
|
const type = this.peek().type
|
|
241
405
|
if (this.isSectionKeyword(type)) return true
|
|
406
|
+
if (allowDeclarations && this.isModuleDeclarationAhead()) return true
|
|
242
407
|
if (this.isAmbiguousSectionKeyword(type)) {
|
|
243
408
|
const next = this.tokens[this.pos + 1]
|
|
244
409
|
// Followed by ':' or '(' means it's a field/prop/method name in
|
|
@@ -254,7 +419,7 @@ export class Parser {
|
|
|
254
419
|
|
|
255
420
|
parseBareBlock(parseEntry) {
|
|
256
421
|
const entries = []
|
|
257
|
-
while (!this.isAtSectionBoundary()) {
|
|
422
|
+
while (!this.isAtSectionBoundary(true)) {
|
|
258
423
|
entries.push(parseEntry())
|
|
259
424
|
this.match(TokenType.COMMA)
|
|
260
425
|
}
|
|
@@ -362,63 +527,85 @@ export class Parser {
|
|
|
362
527
|
}
|
|
363
528
|
|
|
364
529
|
this.expect(TokenType.COLON, "Expected ':' after state name")
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
530
|
+
|
|
531
|
+
// A full assignment-level expression, so initializers like
|
|
532
|
+
// `new Date().toLocaleDateString()`, `Date.now()`, `60 * 60`,
|
|
533
|
+
// `ready ? 1 : 2`, `[...]` / `{...}` and arrow functions
|
|
534
|
+
// (`onSave: () => 1`) all parse. Entries always start with a name,
|
|
535
|
+
// so no operator can be the start of the next entry.
|
|
536
|
+
let value = this.parseAssignment()
|
|
537
|
+
|
|
538
|
+
// Keep `-5` as a plain negative Literal, as before.
|
|
539
|
+
if (
|
|
540
|
+
value.type === 'UnaryExpression' &&
|
|
541
|
+
value.operator === '-' &&
|
|
542
|
+
value.argument.type === 'Literal' &&
|
|
543
|
+
typeof value.argument.value === 'number'
|
|
544
|
+
) {
|
|
545
|
+
value = Literal(-value.argument.value)
|
|
374
546
|
}
|
|
375
|
-
|
|
547
|
+
|
|
376
548
|
return { ...StateNode(name, value, typeAnnotation), line: startLine }
|
|
377
549
|
}
|
|
378
550
|
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
551
|
+
// Parses a parameter list. The opening '(' must already be
|
|
552
|
+
// consumed; this consumes the closing ')'. Supports types
|
|
553
|
+
// (`a: number`), optional (`a?: number`), defaults (`a = 1`), rest
|
|
554
|
+
// (`...args`) and destructured params (`{ id, name }`, `[a, b]`).
|
|
555
|
+
parseParamList() {
|
|
385
556
|
const params = []
|
|
386
557
|
while (!this.check(TokenType.RPAREN)) {
|
|
387
|
-
|
|
388
|
-
|
|
558
|
+
// Constructor parameter properties: `constructor(private readonly x: T)`.
|
|
559
|
+
// A modifier word counts only when another name follows it, so a
|
|
560
|
+
// parameter that is itself called `readonly` still parses.
|
|
561
|
+
let accessibility = null
|
|
562
|
+
let isReadonly = false
|
|
563
|
+
let isOverride = false
|
|
564
|
+
while (
|
|
565
|
+
this.peek().type === TokenType.IDENTIFIER &&
|
|
566
|
+
PARAM_MODIFIERS.has(this.peek().value) &&
|
|
567
|
+
this.isNameToken(this.tokens[this.pos + 1])
|
|
568
|
+
) {
|
|
569
|
+
const word = this.advance().value
|
|
570
|
+
if (word === 'readonly') isReadonly = true
|
|
571
|
+
else if (word === 'override') isOverride = true
|
|
572
|
+
else accessibility = word
|
|
573
|
+
}
|
|
574
|
+
const rest = this.match(TokenType.SPREAD)
|
|
575
|
+
let name
|
|
576
|
+
if (this.check(TokenType.LBRACE) || this.check(TokenType.LBRACKET)) {
|
|
577
|
+
name = bindingToSource(this.parseBindingTarget())
|
|
578
|
+
} else {
|
|
579
|
+
name = this.parseNameToken('Expected parameter name')
|
|
580
|
+
}
|
|
581
|
+
const optional = this.match(TokenType.QUESTION)
|
|
582
|
+
let typeAnnotation = null
|
|
389
583
|
if (this.match(TokenType.COLON)) {
|
|
390
|
-
|
|
584
|
+
typeAnnotation = this.parseTypeExpression()
|
|
391
585
|
}
|
|
392
|
-
|
|
586
|
+
let defaultValue = null
|
|
587
|
+
if (this.match(TokenType.EQUALS)) {
|
|
588
|
+
defaultValue = this.parseAssignment()
|
|
589
|
+
}
|
|
590
|
+
const param = { name, typeAnnotation, defaultValue, rest, optional }
|
|
591
|
+
if (accessibility || isReadonly || isOverride) {
|
|
592
|
+
Object.assign(param, { accessibility, isReadonly, isOverride, isProperty: true })
|
|
593
|
+
}
|
|
594
|
+
params.push(param)
|
|
393
595
|
this.match(TokenType.COMMA)
|
|
394
596
|
}
|
|
395
597
|
this.expect(TokenType.RPAREN, "Expected ')' after parameters")
|
|
598
|
+
return params
|
|
599
|
+
}
|
|
396
600
|
|
|
397
|
-
let returnType = null
|
|
398
|
-
if (this.match(TokenType.COLON)) {
|
|
399
|
-
returnType = this.parseTypeExpression()
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
this.expect(TokenType.LBRACE, "Expected '{' to start method body")
|
|
403
|
-
const body = []
|
|
404
|
-
while (!this.check(TokenType.RBRACE)) {
|
|
405
|
-
body.push(this.parseStatement())
|
|
406
|
-
}
|
|
407
|
-
this.expect(TokenType.RBRACE, "Expected '}' to close method body")
|
|
408
601
|
|
|
409
|
-
return {
|
|
410
|
-
...MethodNode(name, params, body, returnType),
|
|
411
|
-
isAsync,
|
|
412
|
-
line: startLine,
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
602
|
|
|
416
603
|
// A binding target is anywhere a name is bound to a value: a plain
|
|
417
604
|
// identifier, or -- for destructuring -- a nested object/array
|
|
418
605
|
// pattern. Shared by top-level const/let targets, object pattern
|
|
419
|
-
// property values,
|
|
420
|
-
// = x` and `const [[a, b]] = x` both fall out
|
|
421
|
-
// needing separate
|
|
606
|
+
// property values, array pattern elements and catch clauses, so
|
|
607
|
+
// `const { a: { b } } = x` and `const [[a, b]] = x` both fall out
|
|
608
|
+
// for free instead of needing separate parsing logic in each place.
|
|
422
609
|
parseBindingTarget() {
|
|
423
610
|
if (this.check(TokenType.LBRACE)) return this.parseObjectPattern()
|
|
424
611
|
if (this.check(TokenType.LBRACKET)) return this.parseArrayPattern()
|
|
@@ -552,8 +739,8 @@ export class Parser {
|
|
|
552
739
|
}
|
|
553
740
|
|
|
554
741
|
// `{ stmt stmt ... }` -- shared by the newer statement forms
|
|
555
|
-
// (while, switch clauses, block-bodied arrows).
|
|
556
|
-
// the error messages.
|
|
742
|
+
// (while, switch clauses, block-bodied arrows, functions, loops).
|
|
743
|
+
// `what` only feeds the error messages.
|
|
557
744
|
parseBlockStatements(what) {
|
|
558
745
|
this.expect(TokenType.LBRACE, `Expected '{' to start ${what}`)
|
|
559
746
|
const body = []
|
|
@@ -564,107 +751,163 @@ export class Parser {
|
|
|
564
751
|
return body
|
|
565
752
|
}
|
|
566
753
|
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
754
|
+
|
|
755
|
+
isFunctionKeywordAhead() {
|
|
756
|
+
return (
|
|
757
|
+
this.check(TokenType.FUNCTION) ||
|
|
758
|
+
(this.check(TokenType.ASYNC) &&
|
|
759
|
+
this.tokens[this.pos + 1]?.type === TokenType.FUNCTION)
|
|
760
|
+
)
|
|
761
|
+
}
|
|
575
762
|
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
763
|
+
// `name:` at the start of a statement is a label (`outer: for ...`).
|
|
764
|
+
isLabelAhead() {
|
|
765
|
+
return (
|
|
766
|
+
this.check(TokenType.IDENTIFIER) &&
|
|
767
|
+
this.tokens[this.pos + 1]?.type === TokenType.COLON
|
|
768
|
+
)
|
|
769
|
+
}
|
|
581
770
|
|
|
582
|
-
|
|
583
|
-
|
|
771
|
+
// The optional label of `break outer` / `continue outer`: an
|
|
772
|
+
// identifier on the SAME line as the keyword.
|
|
773
|
+
optionalLabel(keywordToken) {
|
|
774
|
+
const next = this.peek()
|
|
775
|
+
if (next.type === TokenType.IDENTIFIER && next.line === keywordToken.line) {
|
|
776
|
+
this.advance()
|
|
777
|
+
return next.value
|
|
584
778
|
}
|
|
779
|
+
return null
|
|
780
|
+
}
|
|
585
781
|
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
782
|
+
// Constructs that exist in JavaScript but not in .tyx scripts. Most
|
|
783
|
+
// of them lex as plain identifiers, so without this check they
|
|
784
|
+
// would parse as a bare name and fail later with a confusing
|
|
785
|
+
// generated-JS error.
|
|
786
|
+
rejectUnsupportedKeyword() {
|
|
787
|
+
const tok = this.peek()
|
|
788
|
+
const next = this.tokens[this.pos + 1]
|
|
789
|
+
if (!next) return
|
|
589
790
|
|
|
590
|
-
if (
|
|
591
|
-
|
|
791
|
+
if (
|
|
792
|
+
tok.type === TokenType.AWAIT &&
|
|
793
|
+
next.type === TokenType.IDENTIFIER &&
|
|
794
|
+
next.value === 'using' &&
|
|
795
|
+
next.line === tok.line &&
|
|
796
|
+
this.tokens[this.pos + 2]?.type === TokenType.IDENTIFIER
|
|
797
|
+
) {
|
|
798
|
+
throw new Error(
|
|
799
|
+
`'await using' (resource management) is not supported; use try / finally (line ${tok.line})`,
|
|
800
|
+
)
|
|
592
801
|
}
|
|
593
802
|
|
|
594
|
-
if (
|
|
595
|
-
return this.parseForStatement()
|
|
596
|
-
}
|
|
803
|
+
if (tok.type !== TokenType.IDENTIFIER) return
|
|
597
804
|
|
|
598
|
-
if (
|
|
599
|
-
|
|
805
|
+
if (
|
|
806
|
+
tok.value === 'var' &&
|
|
807
|
+
(next.type === TokenType.IDENTIFIER ||
|
|
808
|
+
next.type === TokenType.LBRACE ||
|
|
809
|
+
next.type === TokenType.LBRACKET)
|
|
810
|
+
) {
|
|
811
|
+
throw new Error(
|
|
812
|
+
`'var' is not supported; use 'const' or 'let' (line ${tok.line})`,
|
|
813
|
+
)
|
|
600
814
|
}
|
|
601
815
|
|
|
602
|
-
if (
|
|
603
|
-
|
|
816
|
+
if (
|
|
817
|
+
tok.value === 'using' &&
|
|
818
|
+
next.type === TokenType.IDENTIFIER &&
|
|
819
|
+
next.line === tok.line
|
|
820
|
+
) {
|
|
821
|
+
throw new Error(
|
|
822
|
+
`'using' (resource management) is not supported; use try / finally (line ${tok.line})`,
|
|
823
|
+
)
|
|
604
824
|
}
|
|
605
825
|
|
|
606
|
-
if (
|
|
607
|
-
|
|
608
|
-
|
|
826
|
+
if (tok.value === 'import' && next.type !== TokenType.LPAREN) {
|
|
827
|
+
throw new Error(
|
|
828
|
+
`'import' statements and import.meta are not supported inside scripts; put Tylix imports above the template, or use dynamic import("...") (line ${tok.line})`,
|
|
829
|
+
)
|
|
609
830
|
}
|
|
610
831
|
|
|
611
|
-
if (
|
|
612
|
-
|
|
613
|
-
|
|
832
|
+
if (
|
|
833
|
+
tok.value === 'export' &&
|
|
834
|
+
(next.type === TokenType.CONST ||
|
|
835
|
+
next.type === TokenType.LET ||
|
|
836
|
+
next.type === TokenType.FUNCTION ||
|
|
837
|
+
next.type === TokenType.ASYNC ||
|
|
838
|
+
next.type === TokenType.DEFAULT ||
|
|
839
|
+
next.type === TokenType.LBRACE ||
|
|
840
|
+
next.type === TokenType.STAR ||
|
|
841
|
+
(next.type === TokenType.IDENTIFIER && next.value === 'class'))
|
|
842
|
+
) {
|
|
843
|
+
throw new Error(
|
|
844
|
+
`'export' is not supported inside scripts; a .tyx file is its own module (line ${tok.line})`,
|
|
845
|
+
)
|
|
614
846
|
}
|
|
615
847
|
|
|
616
|
-
if (
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
848
|
+
if (tok.value === 'with' && next.type === TokenType.LPAREN) {
|
|
849
|
+
let depth = 0
|
|
850
|
+
let i = this.pos + 1
|
|
851
|
+
for (; i < this.tokens.length; i++) {
|
|
852
|
+
const t = this.tokens[i]
|
|
853
|
+
if (t.type === TokenType.LPAREN) depth++
|
|
854
|
+
else if (t.type === TokenType.RPAREN) {
|
|
855
|
+
depth--
|
|
856
|
+
if (depth === 0) break
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
if (this.tokens[i + 1]?.type === TokenType.LBRACE) {
|
|
860
|
+
throw new Error(`'with' statements are not supported (line ${tok.line})`)
|
|
861
|
+
}
|
|
623
862
|
}
|
|
863
|
+
}
|
|
624
864
|
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
865
|
+
|
|
866
|
+
|
|
867
|
+
// `: Type` after a binding name, or null when there is none.
|
|
868
|
+
parseOptionalTypeAnnotation() {
|
|
869
|
+
return this.match(TokenType.COLON) ? this.parseTypeExpression() : null
|
|
628
870
|
}
|
|
629
871
|
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
this.
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
872
|
+
// `target [: Type] [= init] [, target [: Type] [= init] ...]` after
|
|
873
|
+
// const/let. `let x` (no initializer) is allowed; `const x` requires one.
|
|
874
|
+
parseDeclarators(kind) {
|
|
875
|
+
const target = this.parseBindingTarget()
|
|
876
|
+
const typeAnnotation = this.parseOptionalTypeAnnotation()
|
|
877
|
+
let init = null
|
|
878
|
+
if (this.match(TokenType.EQUALS)) {
|
|
879
|
+
init = this.parseExpression()
|
|
880
|
+
} else if (kind === 'const') {
|
|
881
|
+
throw new Error(
|
|
882
|
+
`Missing initializer in const declaration at line ${this.peek().line}`,
|
|
883
|
+
)
|
|
640
884
|
}
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
} else {
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
alternate.push(this.parseStatement())
|
|
653
|
-
}
|
|
654
|
-
this.expect(TokenType.RBRACE, "Expected '}' to close else body")
|
|
885
|
+
const more = []
|
|
886
|
+
while (this.match(TokenType.COMMA)) {
|
|
887
|
+
const name = this.parseBindingTarget()
|
|
888
|
+
const moreType = this.parseOptionalTypeAnnotation()
|
|
889
|
+
let moreInit = null
|
|
890
|
+
if (this.match(TokenType.EQUALS)) {
|
|
891
|
+
moreInit = this.parseExpression()
|
|
892
|
+
} else if (kind === 'const') {
|
|
893
|
+
throw new Error(
|
|
894
|
+
`Missing initializer in const declaration at line ${this.peek().line}`,
|
|
895
|
+
)
|
|
655
896
|
}
|
|
897
|
+
more.push({ name, init: moreInit, typeAnnotation: moreType })
|
|
656
898
|
}
|
|
657
|
-
|
|
658
|
-
return IfStatement(condition, consequent, alternate)
|
|
899
|
+
return VariableDeclaration(kind, target, init, more, typeAnnotation)
|
|
659
900
|
}
|
|
660
901
|
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
//
|
|
664
|
-
|
|
902
|
+
|
|
903
|
+
|
|
904
|
+
// `do { ... } while cond` (parentheses optional, trailing ; optional)
|
|
905
|
+
parseDoWhileStatement() {
|
|
906
|
+
const body = this.parseBlockStatements('do body')
|
|
907
|
+
this.expect(TokenType.WHILE, "Expected 'while' after the do body")
|
|
665
908
|
const condition = this.parseExpression()
|
|
666
|
-
|
|
667
|
-
return
|
|
909
|
+
this.match(TokenType.SEMICOLON)
|
|
910
|
+
return DoWhileStatement(body, condition)
|
|
668
911
|
}
|
|
669
912
|
|
|
670
913
|
// Tylix-style switch: braces for every clause, no fallthrough, and
|
|
@@ -687,6 +930,7 @@ export class Parser {
|
|
|
687
930
|
while (this.match(TokenType.COMMA)) {
|
|
688
931
|
tests.push(this.parseExpression())
|
|
689
932
|
}
|
|
933
|
+
this.rejectSwitchColon()
|
|
690
934
|
cases.push({ tests, body: this.parseBlockStatements('case body') })
|
|
691
935
|
} else if (this.check(TokenType.DEFAULT)) {
|
|
692
936
|
const line = this.advance().line
|
|
@@ -694,6 +938,7 @@ export class Parser {
|
|
|
694
938
|
throw new Error(`Duplicate 'default' in switch at line ${line}`)
|
|
695
939
|
}
|
|
696
940
|
hasDefault = true
|
|
941
|
+
this.rejectSwitchColon()
|
|
697
942
|
cases.push({
|
|
698
943
|
tests: null,
|
|
699
944
|
body: this.parseBlockStatements('default body'),
|
|
@@ -709,52 +954,151 @@ export class Parser {
|
|
|
709
954
|
return SwitchStatement(discriminant, cases)
|
|
710
955
|
}
|
|
711
956
|
|
|
957
|
+
rejectSwitchColon() {
|
|
958
|
+
if (this.check(TokenType.COLON)) {
|
|
959
|
+
throw new Error(
|
|
960
|
+
`Switch cases use braces, not a colon: case a, b { ... } (no fallthrough), at line ${this.peek().line}`,
|
|
961
|
+
)
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
// All the `for` forms:
|
|
966
|
+
// for x in arr { } for x of arr { }
|
|
967
|
+
// for [k, v] of Object.entries(o) for const x of arr { }
|
|
968
|
+
// for i from 0 to n { }
|
|
969
|
+
// for (const x of arr) { } for (const k in obj) { } (keys)
|
|
970
|
+
// for (let i = 0, n = a.length; i < n; i++) { }
|
|
971
|
+
// for await (const x of stream) { } for await x of stream { }
|
|
712
972
|
parseForStatement() {
|
|
713
|
-
const
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
973
|
+
const isAwait = this.match(TokenType.AWAIT)
|
|
974
|
+
|
|
975
|
+
if (this.check(TokenType.LPAREN)) {
|
|
976
|
+
return this.parseParenFor(isAwait)
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
let declKind = 'const'
|
|
980
|
+
if (this.check(TokenType.CONST) || this.check(TokenType.LET)) {
|
|
981
|
+
declKind = this.advance().type === TokenType.CONST ? 'const' : 'let'
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
let varName
|
|
985
|
+
if (this.check(TokenType.LBRACKET) || this.check(TokenType.LBRACE)) {
|
|
986
|
+
varName = this.parseBindingTarget()
|
|
987
|
+
} else {
|
|
988
|
+
varName = this.expect(
|
|
989
|
+
TokenType.IDENTIFIER,
|
|
990
|
+
"Expected a loop variable name after 'for'",
|
|
991
|
+
).value
|
|
992
|
+
}
|
|
717
993
|
|
|
718
|
-
if (this.match(TokenType.IN)) {
|
|
994
|
+
if (this.match(TokenType.IN) || this.match(TokenType.OF)) {
|
|
719
995
|
const iterable = this.parseExpression()
|
|
720
|
-
this.
|
|
721
|
-
|
|
722
|
-
while (!this.check(TokenType.RBRACE)) {
|
|
723
|
-
body.push(this.parseStatement())
|
|
724
|
-
}
|
|
725
|
-
this.expect(TokenType.RBRACE, "Expected '}' to close the loop body")
|
|
726
|
-
return ForInStatement(varName, iterable, body)
|
|
996
|
+
const body = this.parseBody('loop body')
|
|
997
|
+
return ForInStatement(varName, iterable, body, declKind, isAwait)
|
|
727
998
|
}
|
|
728
999
|
|
|
729
1000
|
if (this.match(TokenType.FROM)) {
|
|
1001
|
+
if (isAwait) {
|
|
1002
|
+
throw new Error(
|
|
1003
|
+
`'for await' needs 'in' or 'of', not 'from ... to' (line ${this.peek().line})`,
|
|
1004
|
+
)
|
|
1005
|
+
}
|
|
1006
|
+
if (typeof varName !== 'string') {
|
|
1007
|
+
throw new Error(
|
|
1008
|
+
`'for ... from ... to' needs a plain loop variable at line ${this.peek().line}`,
|
|
1009
|
+
)
|
|
1010
|
+
}
|
|
730
1011
|
const start = this.parseExpression()
|
|
731
1012
|
this.expect(TokenType.TO, "Expected 'to' after the loop's starting value")
|
|
732
1013
|
const end = this.parseExpression()
|
|
733
|
-
this.
|
|
734
|
-
const body = []
|
|
735
|
-
while (!this.check(TokenType.RBRACE)) {
|
|
736
|
-
body.push(this.parseStatement())
|
|
737
|
-
}
|
|
738
|
-
this.expect(TokenType.RBRACE, "Expected '}' to close the loop body")
|
|
1014
|
+
const body = this.parseBody('loop body')
|
|
739
1015
|
return ForRangeStatement(varName, start, end, body)
|
|
740
1016
|
}
|
|
741
1017
|
|
|
742
1018
|
throw new Error(
|
|
743
|
-
`Expected 'in' or 'from' after 'for ${varName}' at line ${this.peek().line}`,
|
|
1019
|
+
`Expected 'in', 'of' or 'from' after 'for ${typeof varName === 'string' ? varName : '...'}' at line ${this.peek().line}`,
|
|
744
1020
|
)
|
|
745
1021
|
}
|
|
746
1022
|
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
1023
|
+
parseParenFor(isAwait = false) {
|
|
1024
|
+
this.expect(TokenType.LPAREN, "Expected '(' after 'for'")
|
|
1025
|
+
|
|
1026
|
+
let init = null
|
|
1027
|
+
if (this.check(TokenType.SEMICOLON)) {
|
|
1028
|
+
// no init
|
|
1029
|
+
} else if (this.check(TokenType.CONST) || this.check(TokenType.LET)) {
|
|
1030
|
+
const kind = this.advance().type === TokenType.CONST ? 'const' : 'let'
|
|
1031
|
+
const target = this.parseBindingTarget()
|
|
1032
|
+
|
|
1033
|
+
if (this.check(TokenType.OF) || this.check(TokenType.IN)) {
|
|
1034
|
+
const isOf = this.advance().type === TokenType.OF
|
|
1035
|
+
if (isAwait && !isOf) {
|
|
1036
|
+
throw new Error(
|
|
1037
|
+
`'for await' needs 'of', not 'in' (line ${this.peek().line})`,
|
|
1038
|
+
)
|
|
1039
|
+
}
|
|
1040
|
+
const iterable = this.parseExpression()
|
|
1041
|
+
this.expect(TokenType.RPAREN, "Expected ')' after the for header")
|
|
1042
|
+
const body = this.parseBody('loop body')
|
|
1043
|
+
return isOf
|
|
1044
|
+
? ForInStatement(target, iterable, body, kind, isAwait)
|
|
1045
|
+
: ForKeysStatement(target, iterable, body, kind)
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
// C-style declaration: re-enter declarator parsing with the
|
|
1049
|
+
// target we already consumed.
|
|
1050
|
+
const typeAnnotation = this.parseOptionalTypeAnnotation()
|
|
1051
|
+
let first = null
|
|
1052
|
+
if (this.match(TokenType.EQUALS)) {
|
|
1053
|
+
first = this.parseExpression()
|
|
1054
|
+
} else if (kind === 'const') {
|
|
1055
|
+
throw new Error(
|
|
1056
|
+
`Missing initializer in const declaration at line ${this.peek().line}`,
|
|
1057
|
+
)
|
|
1058
|
+
}
|
|
1059
|
+
const more = []
|
|
1060
|
+
while (this.match(TokenType.COMMA)) {
|
|
1061
|
+
const name = this.parseBindingTarget()
|
|
1062
|
+
const moreType = this.parseOptionalTypeAnnotation()
|
|
1063
|
+
let moreInit = null
|
|
1064
|
+
if (this.match(TokenType.EQUALS)) moreInit = this.parseExpression()
|
|
1065
|
+
more.push({ name, init: moreInit, typeAnnotation: moreType })
|
|
1066
|
+
}
|
|
1067
|
+
init = VariableDeclaration(kind, target, first, more, typeAnnotation)
|
|
1068
|
+
} else {
|
|
1069
|
+
const expressions = [this.parseExpression()]
|
|
1070
|
+
while (this.match(TokenType.COMMA)) {
|
|
1071
|
+
expressions.push(this.parseExpression())
|
|
1072
|
+
}
|
|
1073
|
+
init = { type: 'ExpressionList', expressions }
|
|
753
1074
|
}
|
|
754
|
-
|
|
755
|
-
|
|
1075
|
+
|
|
1076
|
+
if (isAwait) {
|
|
1077
|
+
throw new Error(
|
|
1078
|
+
`'for await' needs the form for await (const x of iterable) (line ${this.peek().line})`,
|
|
1079
|
+
)
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
this.expect(TokenType.SEMICOLON, "Expected ';' after the for-loop init")
|
|
1083
|
+
const test = this.check(TokenType.SEMICOLON) ? null : this.parseExpression()
|
|
1084
|
+
this.expect(TokenType.SEMICOLON, "Expected ';' after the for-loop condition")
|
|
1085
|
+
|
|
1086
|
+
const update = []
|
|
1087
|
+
if (!this.check(TokenType.RPAREN)) {
|
|
1088
|
+
update.push(this.parseExpression())
|
|
1089
|
+
while (this.match(TokenType.COMMA)) {
|
|
1090
|
+
update.push(this.parseExpression())
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
this.expect(TokenType.RPAREN, "Expected ')' to close the for header")
|
|
1094
|
+
|
|
1095
|
+
const body = this.parseBody('loop body')
|
|
1096
|
+
return ForStatement(init, test, update, body)
|
|
756
1097
|
}
|
|
757
1098
|
|
|
1099
|
+
|
|
1100
|
+
// `catch (e)`, `catch (e: unknown)`, `catch ({ message })`,
|
|
1101
|
+
// `catch ([first])` and the optional-binding `catch { }`.
|
|
758
1102
|
parseTryStatement() {
|
|
759
1103
|
this.expect(TokenType.LBRACE, "Expected '{' to start try block")
|
|
760
1104
|
const tryBlock = []
|
|
@@ -764,13 +1108,14 @@ export class Parser {
|
|
|
764
1108
|
this.expect(TokenType.RBRACE, "Expected '}' to close try block")
|
|
765
1109
|
|
|
766
1110
|
let catchParam = null
|
|
1111
|
+
let catchType = null
|
|
767
1112
|
let catchBlock = null
|
|
768
1113
|
if (this.match(TokenType.CATCH)) {
|
|
769
1114
|
if (this.match(TokenType.LPAREN)) {
|
|
770
|
-
catchParam = this.
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
1115
|
+
catchParam = this.parseBindingTarget()
|
|
1116
|
+
if (this.match(TokenType.COLON)) {
|
|
1117
|
+
catchType = this.parseTypeExpression()
|
|
1118
|
+
}
|
|
774
1119
|
this.expect(TokenType.RPAREN, "Expected ')' after catch parameter")
|
|
775
1120
|
}
|
|
776
1121
|
this.expect(TokenType.LBRACE, "Expected '{' to start catch block")
|
|
@@ -791,69 +1136,481 @@ export class Parser {
|
|
|
791
1136
|
this.expect(TokenType.RBRACE, "Expected '}' to close finally block")
|
|
792
1137
|
}
|
|
793
1138
|
|
|
794
|
-
return TryStatement(tryBlock, catchParam, catchBlock, finallyBlock)
|
|
1139
|
+
return TryStatement(tryBlock, catchParam, catchBlock, finallyBlock, catchType)
|
|
795
1140
|
}
|
|
796
1141
|
|
|
797
|
-
|
|
798
|
-
|
|
1142
|
+
// ---- classes ----
|
|
1143
|
+
|
|
1144
|
+
// `class Name {` / `class Name extends X {` as a declaration, or
|
|
1145
|
+
// (isExpression) also the anonymous `class {` / `class extends X {`.
|
|
1146
|
+
isClassAhead(isExpression) {
|
|
1147
|
+
// `abstract class X` (statement form only)
|
|
1148
|
+
if (!isExpression && this.isWord('abstract')) {
|
|
1149
|
+
const after = this.tokens[this.pos + 1]
|
|
1150
|
+
if (after?.type !== TokenType.IDENTIFIER || after.value !== 'class') return false
|
|
1151
|
+
if (after.line !== this.peek().line) return false
|
|
1152
|
+
const saved = this.pos
|
|
1153
|
+
this.pos++
|
|
1154
|
+
const ok = this.isClassAhead(false)
|
|
1155
|
+
this.pos = saved
|
|
1156
|
+
return ok
|
|
1157
|
+
}
|
|
1158
|
+
const tok = this.peek()
|
|
1159
|
+
const next = this.tokens[this.pos + 1]
|
|
1160
|
+
if (tok.type !== TokenType.IDENTIFIER || tok.value !== 'class' || !next) {
|
|
1161
|
+
return false
|
|
1162
|
+
}
|
|
1163
|
+
if (isExpression) {
|
|
1164
|
+
return next.type === TokenType.LBRACE || next.type === TokenType.IDENTIFIER
|
|
1165
|
+
}
|
|
1166
|
+
return next.type === TokenType.IDENTIFIER && next.value !== 'extends'
|
|
799
1167
|
}
|
|
800
1168
|
|
|
801
|
-
|
|
802
|
-
const
|
|
803
|
-
|
|
1169
|
+
isWord(word) {
|
|
1170
|
+
const tok = this.peek()
|
|
1171
|
+
return tok.type === TokenType.IDENTIFIER && tok.value === word
|
|
1172
|
+
}
|
|
804
1173
|
|
|
805
|
-
|
|
1174
|
+
isNameToken(tok) {
|
|
1175
|
+
return (
|
|
1176
|
+
!!tok &&
|
|
1177
|
+
(tok.type === TokenType.IDENTIFIER || KEYWORD_TOKEN_TYPES.has(tok.type))
|
|
1178
|
+
)
|
|
1179
|
+
}
|
|
806
1180
|
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
1181
|
+
// Body of if/else/while/for/repeat: a `{ ... }` block or ONE statement.
|
|
1182
|
+
parseBody(what) {
|
|
1183
|
+
if (this.check(TokenType.LBRACE)) return this.parseBlockStatements(what)
|
|
1184
|
+
return [this.parseStatement()]
|
|
1185
|
+
}
|
|
811
1186
|
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
1187
|
+
matchingParen(openIndex) {
|
|
1188
|
+
let depth = 0
|
|
1189
|
+
for (let i = openIndex; i < this.tokens.length; i++) {
|
|
1190
|
+
const t = this.tokens[i].type
|
|
1191
|
+
if (t === TokenType.LPAREN) depth++
|
|
1192
|
+
else if (t === TokenType.RPAREN) {
|
|
1193
|
+
depth--
|
|
1194
|
+
if (depth === 0) return i
|
|
1195
|
+
}
|
|
815
1196
|
}
|
|
1197
|
+
return -1
|
|
1198
|
+
}
|
|
816
1199
|
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
this.advance()
|
|
821
|
-
const value = this.parseAssignment()
|
|
822
|
-
return AssignmentExpr(left, BinaryExpr(compoundOp, left, value))
|
|
1200
|
+
startsBody(tok) {
|
|
1201
|
+
if (tok.type === TokenType.IDENTIFIER) {
|
|
1202
|
+
return tok.value !== 'as' && tok.value !== 'satisfies'
|
|
823
1203
|
}
|
|
1204
|
+
return STATEMENT_START_TOKENS.has(tok.type)
|
|
1205
|
+
}
|
|
824
1206
|
|
|
825
|
-
|
|
1207
|
+
// Condition of if/while/repeat. `if (a) stmt` (JS style): when a
|
|
1208
|
+
// statement starts right after the closing paren, the parens are just
|
|
1209
|
+
// the condition. Otherwise it is a normal expression, so
|
|
1210
|
+
// `while (a) and (b) { }` and `if (a) { }` behave exactly as before.
|
|
1211
|
+
parseCondition() {
|
|
1212
|
+
if (this.check(TokenType.LPAREN)) {
|
|
1213
|
+
const close = this.matchingParen(this.pos)
|
|
1214
|
+
const after = close === -1 ? null : this.tokens[close + 1]
|
|
1215
|
+
if (after && this.startsBody(after)) {
|
|
1216
|
+
this.advance()
|
|
1217
|
+
const condition = this.parseExpression()
|
|
1218
|
+
this.expect(TokenType.RPAREN, "Expected ')' after the condition")
|
|
1219
|
+
return condition
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
return this.parseExpression()
|
|
826
1223
|
}
|
|
827
1224
|
|
|
828
|
-
//
|
|
829
|
-
// restored
|
|
830
|
-
//
|
|
831
|
-
|
|
832
|
-
|
|
1225
|
+
// `<A, B>` in a call or `new`. Speculative: returns the type text, or
|
|
1226
|
+
// null (position restored) when it is really a comparison. `followers`
|
|
1227
|
+
// are the token types allowed right after the closing `>`.
|
|
1228
|
+
tryParseTypeArguments(followers) {
|
|
1229
|
+
if (!this.check(TokenType.LT)) return null
|
|
833
1230
|
const savedPos = this.pos
|
|
834
1231
|
try {
|
|
835
|
-
|
|
1232
|
+
this.advance()
|
|
1233
|
+
const args = [this.parseTypeExpression()]
|
|
1234
|
+
while (this.match(TokenType.COMMA)) args.push(this.parseTypeExpression())
|
|
1235
|
+
this.expect(TokenType.GT, "Expected '>' to close type arguments")
|
|
1236
|
+
if (!followers.includes(this.peek().type)) {
|
|
1237
|
+
this.pos = savedPos
|
|
1238
|
+
return null
|
|
1239
|
+
}
|
|
1240
|
+
return args.join(', ')
|
|
836
1241
|
} catch {
|
|
837
1242
|
this.pos = savedPos
|
|
838
1243
|
return null
|
|
839
1244
|
}
|
|
840
1245
|
}
|
|
841
1246
|
|
|
842
|
-
//
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
1247
|
+
// `<T, U extends X = Y>` or '' when absent.
|
|
1248
|
+
parseOptionalTypeParams() {
|
|
1249
|
+
if (!this.match(TokenType.LT)) return ''
|
|
1250
|
+
const parts = []
|
|
1251
|
+
do {
|
|
1252
|
+
let p = this.parseNameToken('Expected a type parameter name')
|
|
1253
|
+
if (this.isWord('extends')) {
|
|
1254
|
+
this.advance()
|
|
1255
|
+
p += ` extends ${this.parseTypeExpression()}`
|
|
1256
|
+
}
|
|
1257
|
+
if (this.match(TokenType.EQUALS)) {
|
|
1258
|
+
p += ` = ${this.parseTypeExpression()}`
|
|
1259
|
+
}
|
|
1260
|
+
parts.push(p)
|
|
1261
|
+
} while (this.match(TokenType.COMMA) && !this.check(TokenType.GT)) // allows `<T,>`
|
|
1262
|
+
this.expect(TokenType.GT, "Expected '>' to close type parameters")
|
|
1263
|
+
return `<${parts.join(', ')}>`
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
// A return type, which may be a type predicate: `x is T`,
|
|
1267
|
+
// `asserts x`, `asserts x is T`. (`is` is a keyword token here.)
|
|
1268
|
+
parseReturnType() {
|
|
1269
|
+
const tok = this.peek()
|
|
1270
|
+
const next = this.tokens[this.pos + 1]
|
|
1271
|
+
if (
|
|
1272
|
+
tok.type === TokenType.IDENTIFIER &&
|
|
1273
|
+
tok.value === 'asserts' &&
|
|
1274
|
+
this.isNameToken(next) &&
|
|
1275
|
+
next.line === tok.line
|
|
1276
|
+
) {
|
|
1277
|
+
this.advance()
|
|
1278
|
+
const name = this.advance().value
|
|
1279
|
+
return this.match(TokenType.IS)
|
|
1280
|
+
? `asserts ${name} is ${this.parseTypeExpression()}`
|
|
1281
|
+
: `asserts ${name}`
|
|
1282
|
+
}
|
|
1283
|
+
if (this.isNameToken(tok) && next && next.type === TokenType.IS) {
|
|
1284
|
+
const name = this.advance().value
|
|
1285
|
+
this.advance() // 'is'
|
|
1286
|
+
return `${name} is ${this.parseTypeExpression()}`
|
|
1287
|
+
}
|
|
1288
|
+
return this.parseTypeExpression()
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
tryParseReturnType() {
|
|
1292
|
+
const savedPos = this.pos
|
|
1293
|
+
try {
|
|
1294
|
+
return this.parseReturnType()
|
|
1295
|
+
} catch {
|
|
1296
|
+
this.pos = savedPos
|
|
1297
|
+
return null
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
// Backtracking variant of parseTypeExpression, for speculative parses
|
|
1302
|
+
// (arrow params) where a failed type means "not an arrow after all".
|
|
1303
|
+
tryParseTypeExpression() {
|
|
1304
|
+
const savedPos = this.pos
|
|
1305
|
+
try {
|
|
1306
|
+
return this.parseTypeExpression()
|
|
1307
|
+
} catch {
|
|
1308
|
+
this.pos = savedPos
|
|
1309
|
+
return null
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
// ---- type declarations and enums ----
|
|
1314
|
+
|
|
1315
|
+
isTypeDeclarationAhead() {
|
|
1316
|
+
const tok = this.peek()
|
|
1317
|
+
const next = this.tokens[this.pos + 1]
|
|
1318
|
+
const third = this.tokens[this.pos + 2]
|
|
1319
|
+
if (!this.isNameToken(tok) || !next || next.line !== tok.line) return false
|
|
1320
|
+
if (next.type !== TokenType.IDENTIFIER || !third) return false
|
|
1321
|
+
if (tok.value === 'type') {
|
|
1322
|
+
return third.type === TokenType.EQUALS || third.type === TokenType.LT
|
|
1323
|
+
}
|
|
1324
|
+
if (tok.value === 'interface') {
|
|
1325
|
+
return (
|
|
1326
|
+
third.type === TokenType.LBRACE ||
|
|
1327
|
+
third.type === TokenType.LT ||
|
|
1328
|
+
(third.type === TokenType.IDENTIFIER && third.value === 'extends')
|
|
1329
|
+
)
|
|
1330
|
+
}
|
|
1331
|
+
return false
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1334
|
+
parseTypeDeclaration() {
|
|
1335
|
+
const keyword = this.advance().value
|
|
1336
|
+
const name = this.advance().value
|
|
1337
|
+
const generics = this.parseOptionalTypeParams()
|
|
1338
|
+
if (keyword === 'type') {
|
|
1339
|
+
this.expect(TokenType.EQUALS, "Expected '=' in the type declaration")
|
|
1340
|
+
const body = this.parseTypeExpression()
|
|
1341
|
+
this.match(TokenType.SEMICOLON)
|
|
1342
|
+
return TypeDeclaration('type', name, `type ${name}${generics} = ${body};`)
|
|
1343
|
+
}
|
|
1344
|
+
let ext = ''
|
|
1345
|
+
if (this.isWord('extends')) {
|
|
1346
|
+
this.advance()
|
|
1347
|
+
const list = [this.parseTypeExpression()]
|
|
1348
|
+
while (this.match(TokenType.COMMA)) list.push(this.parseTypeExpression())
|
|
1349
|
+
ext = ` extends ${list.join(', ')}`
|
|
1350
|
+
}
|
|
1351
|
+
const body = this.parseObjectTypeLiteral()
|
|
1352
|
+
return TypeDeclaration(
|
|
1353
|
+
'interface',
|
|
1354
|
+
name,
|
|
1355
|
+
`interface ${name}${generics}${ext} ${body}`,
|
|
1356
|
+
)
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1359
|
+
isEnumAhead() {
|
|
1360
|
+
const tok = this.peek()
|
|
1361
|
+
const next = this.tokens[this.pos + 1]
|
|
1362
|
+
const third = this.tokens[this.pos + 2]
|
|
1363
|
+
return (
|
|
1364
|
+
tok.type === TokenType.IDENTIFIER &&
|
|
1365
|
+
tok.value === 'enum' &&
|
|
1366
|
+
next?.type === TokenType.IDENTIFIER &&
|
|
1367
|
+
third?.type === TokenType.LBRACE
|
|
1368
|
+
)
|
|
1369
|
+
}
|
|
1370
|
+
|
|
1371
|
+
parseEnum() {
|
|
1372
|
+
this.advance() // 'enum'
|
|
1373
|
+
const name = this.advance().value
|
|
1374
|
+
this.expect(TokenType.LBRACE, "Expected '{' to start the enum body")
|
|
1375
|
+
const members = []
|
|
1376
|
+
while (!this.check(TokenType.RBRACE)) {
|
|
1377
|
+
const memberName = this.check(TokenType.STRING)
|
|
1378
|
+
? this.advance().value
|
|
1379
|
+
: this.parseNameToken('Expected an enum member name')
|
|
1380
|
+
const init = this.match(TokenType.EQUALS) ? this.parseAssignment() : null
|
|
1381
|
+
members.push({ name: memberName, init })
|
|
1382
|
+
this.match(TokenType.COMMA)
|
|
1383
|
+
}
|
|
1384
|
+
this.expect(TokenType.RBRACE, "Expected '}' to close the enum body")
|
|
1385
|
+
return EnumDeclaration(name, members)
|
|
1386
|
+
}
|
|
1387
|
+
|
|
1388
|
+
// Page-level declarations that become module helpers (see `helpers`
|
|
1389
|
+
// on the page node).
|
|
1390
|
+
isModuleDeclarationAhead() {
|
|
1391
|
+
const t = this.peek()
|
|
1392
|
+
const n = this.tokens[this.pos + 1]
|
|
1393
|
+
if (
|
|
1394
|
+
(t.type === TokenType.CONST ||
|
|
1395
|
+
t.type === TokenType.LET ||
|
|
1396
|
+
t.type === TokenType.FUNCTION) &&
|
|
1397
|
+
n?.type !== TokenType.COLON
|
|
1398
|
+
) {
|
|
1399
|
+
return true
|
|
1400
|
+
}
|
|
1401
|
+
if (t.type === TokenType.ASYNC && n?.type === TokenType.FUNCTION) return true
|
|
1402
|
+
return (
|
|
1403
|
+
this.isClassAhead(false) ||
|
|
1404
|
+
this.isTypeDeclarationAhead() ||
|
|
1405
|
+
this.isEnumAhead()
|
|
1406
|
+
)
|
|
1407
|
+
}
|
|
1408
|
+
|
|
1409
|
+
isMemberKeyStart(tok) {
|
|
1410
|
+
return (
|
|
1411
|
+
!!tok &&
|
|
1412
|
+
(tok.type === TokenType.IDENTIFIER ||
|
|
1413
|
+
KEYWORD_TOKEN_TYPES.has(tok.type) ||
|
|
1414
|
+
tok.type === TokenType.STRING ||
|
|
1415
|
+
tok.type === TokenType.NUMBER ||
|
|
1416
|
+
tok.type === TokenType.LBRACKET ||
|
|
1417
|
+
tok.type === TokenType.STAR)
|
|
1418
|
+
)
|
|
1419
|
+
}
|
|
1420
|
+
|
|
1421
|
+
// True when the current token is the contextual modifier `word`
|
|
1422
|
+
// (static / async / get / set) rather than a member NAME: a name
|
|
1423
|
+
// would be followed by `(`, `=`, `;` or `}`, a modifier by the key.
|
|
1424
|
+
modifierAhead(word) {
|
|
1425
|
+
const tok = this.peek()
|
|
1426
|
+
const next = this.tokens[this.pos + 1]
|
|
1427
|
+
return (
|
|
1428
|
+
(tok.type === TokenType.IDENTIFIER ||
|
|
1429
|
+
KEYWORD_TOKEN_TYPES.has(tok.type)) &&
|
|
1430
|
+
tok.value === word &&
|
|
1431
|
+
this.isMemberKeyStart(next) &&
|
|
1432
|
+
next.line === tok.line
|
|
1433
|
+
)
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
|
|
1437
|
+
|
|
1438
|
+
// ---- expressions ----
|
|
1439
|
+
|
|
1440
|
+
parseExpression() {
|
|
1441
|
+
return this.parseAssignment()
|
|
1442
|
+
}
|
|
1443
|
+
|
|
1444
|
+
// `<<=` is LT + LTE, `>>=` is GT + GTE, `>>>=` is GT + GT + GTE, all
|
|
1445
|
+
// written with no whitespace between them. Returns { op, len } (len =
|
|
1446
|
+
// number of tokens) or null.
|
|
1447
|
+
compoundShiftAt() {
|
|
1448
|
+
const a = this.tokens[this.pos]
|
|
1449
|
+
const b = this.tokens[this.pos + 1]
|
|
1450
|
+
const c = this.tokens[this.pos + 2]
|
|
1451
|
+
if (!a || !b) return null
|
|
1452
|
+
if (a.type === TokenType.LT && b.type === TokenType.LTE && adjacent(a, b)) {
|
|
1453
|
+
return { op: '<<', len: 2 }
|
|
1454
|
+
}
|
|
1455
|
+
if (a.type === TokenType.GT && b.type === TokenType.GTE && adjacent(a, b)) {
|
|
1456
|
+
return { op: '>>', len: 2 }
|
|
1457
|
+
}
|
|
1458
|
+
if (
|
|
1459
|
+
a.type === TokenType.GT &&
|
|
1460
|
+
b.type === TokenType.GT &&
|
|
1461
|
+
c &&
|
|
1462
|
+
c.type === TokenType.GTE &&
|
|
1463
|
+
adjacent(a, b) &&
|
|
1464
|
+
adjacent(b, c)
|
|
1465
|
+
) {
|
|
1466
|
+
return { op: '>>>', len: 3 }
|
|
1467
|
+
}
|
|
1468
|
+
return null
|
|
1469
|
+
}
|
|
1470
|
+
|
|
1471
|
+
// `<<` is LT LT, `>>` is GT GT, `>>>` is GT GT GT, adjacent. Refuses
|
|
1472
|
+
// anything that is really a compound assignment (`>>>=` also starts
|
|
1473
|
+
// with GT GT).
|
|
1474
|
+
shiftOperatorAt() {
|
|
1475
|
+
const a = this.tokens[this.pos]
|
|
1476
|
+
const b = this.tokens[this.pos + 1]
|
|
1477
|
+
const c = this.tokens[this.pos + 2]
|
|
1478
|
+
if (!a || !b) return null
|
|
1479
|
+
if (a.type === TokenType.LT && b.type === TokenType.LT && adjacent(a, b)) {
|
|
1480
|
+
return { op: '<<', len: 2 }
|
|
1481
|
+
}
|
|
1482
|
+
if (a.type === TokenType.GT && b.type === TokenType.GT && adjacent(a, b)) {
|
|
1483
|
+
if (c && c.type === TokenType.GTE && adjacent(b, c)) return null // >>>=
|
|
1484
|
+
if (c && c.type === TokenType.GT && adjacent(b, c)) {
|
|
1485
|
+
return { op: '>>>', len: 3 }
|
|
1486
|
+
}
|
|
1487
|
+
return { op: '>>', len: 2 }
|
|
1488
|
+
}
|
|
1489
|
+
return null
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
// Compound assignment and ++/-- repeat their target in the desugared
|
|
1493
|
+
// AST, so a target that mutates or awaits (`a[i++] += 1`) would run
|
|
1494
|
+
// twice. Refuse it instead of silently doing the wrong thing.
|
|
1495
|
+
assertTargetRunsOnce(target) {
|
|
1496
|
+
if (containsMutation(target)) {
|
|
1497
|
+
throw new Error(
|
|
1498
|
+
`This assignment target contains ++, --, = or await, which would run twice; split it into two statements (line ${this.peek().line})`,
|
|
1499
|
+
)
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
|
|
1503
|
+
// `yield` is only an operator inside a generator body.
|
|
1504
|
+
isYieldAhead() {
|
|
1505
|
+
const tok = this.peek()
|
|
1506
|
+
return tok.type === TokenType.IDENTIFIER && tok.value === 'yield'
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
parseYield() {
|
|
1510
|
+
const tok = this.advance() // 'yield'
|
|
1511
|
+
const delegate = this.match(TokenType.STAR)
|
|
1512
|
+
const next = this.peek()
|
|
1513
|
+
const endsHere =
|
|
1514
|
+
next.line !== tok.line ||
|
|
1515
|
+
next.type === TokenType.RPAREN ||
|
|
1516
|
+
next.type === TokenType.RBRACKET ||
|
|
1517
|
+
next.type === TokenType.RBRACE ||
|
|
1518
|
+
next.type === TokenType.COMMA ||
|
|
1519
|
+
next.type === TokenType.SEMICOLON ||
|
|
1520
|
+
next.type === TokenType.COLON ||
|
|
1521
|
+
next.type === TokenType.EOF
|
|
1522
|
+
const argument = delegate || !endsHere ? this.parseAssignment() : null
|
|
1523
|
+
return YieldExpr(argument, delegate)
|
|
1524
|
+
}
|
|
1525
|
+
|
|
1526
|
+
parseAssignment() {
|
|
1527
|
+
if (this.inGenerator && this.isYieldAhead()) {
|
|
1528
|
+
return this.parseYield()
|
|
1529
|
+
}
|
|
1530
|
+
|
|
1531
|
+
const arrow = this.tryParseArrowFunction()
|
|
1532
|
+
if (arrow) return arrow
|
|
1533
|
+
|
|
1534
|
+
const left = this.parseTernary()
|
|
1535
|
+
|
|
1536
|
+
if (this.match(TokenType.EQUALS)) {
|
|
1537
|
+
const value = this.parseAssignment()
|
|
1538
|
+
return AssignmentExpr(left, value)
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
if (this.match(TokenType.NULLISH_EQUALS)) {
|
|
1542
|
+
this.assertTargetRunsOnce(left)
|
|
1543
|
+
const value = this.parseAssignment()
|
|
1544
|
+
return AssignmentExpr(left, NullishCoalescingExpr(left, value))
|
|
1545
|
+
}
|
|
1546
|
+
|
|
1547
|
+
if (this.match(TokenType.OR_EQUALS)) {
|
|
1548
|
+
this.assertTargetRunsOnce(left)
|
|
1549
|
+
const value = this.parseAssignment()
|
|
1550
|
+
return AssignmentExpr(left, BinaryExpr('||', left, value))
|
|
1551
|
+
}
|
|
1552
|
+
|
|
1553
|
+
if (this.match(TokenType.AND_EQUALS)) {
|
|
1554
|
+
this.assertTargetRunsOnce(left)
|
|
1555
|
+
const value = this.parseAssignment()
|
|
1556
|
+
return AssignmentExpr(left, BinaryExpr('&&', left, value))
|
|
1557
|
+
}
|
|
1558
|
+
|
|
1559
|
+
const compoundOp = COMPOUND_ASSIGNMENT_OPS[this.peek().type]
|
|
1560
|
+
|
|
1561
|
+
if (compoundOp) {
|
|
1562
|
+
this.assertTargetRunsOnce(left)
|
|
1563
|
+
this.advance()
|
|
1564
|
+
const value = this.parseAssignment()
|
|
1565
|
+
return AssignmentExpr(left, BinaryExpr(compoundOp, left, value))
|
|
1566
|
+
}
|
|
1567
|
+
|
|
1568
|
+
const shiftAssign = this.compoundShiftAt()
|
|
1569
|
+
if (shiftAssign) {
|
|
1570
|
+
this.assertTargetRunsOnce(left)
|
|
1571
|
+
this.pos += shiftAssign.len
|
|
1572
|
+
const value = this.parseAssignment()
|
|
1573
|
+
return AssignmentExpr(left, BinaryExpr(shiftAssign.op, left, value))
|
|
1574
|
+
}
|
|
1575
|
+
|
|
1576
|
+
return left
|
|
1577
|
+
}
|
|
1578
|
+
|
|
1579
|
+
|
|
1580
|
+
|
|
1581
|
+
// Speculatively parses a destructuring pattern used as an arrow
|
|
1582
|
+
// parameter and returns its source text ("[k, v]", "{ id, name }"),
|
|
1583
|
+
// or null (position restored) if it isn't a valid param pattern.
|
|
1584
|
+
tryParseDestructuredParam() {
|
|
1585
|
+
const savedPos = this.pos
|
|
1586
|
+
try {
|
|
1587
|
+
return bindingToSource(this.parseBindingTarget())
|
|
1588
|
+
} catch {
|
|
1589
|
+
this.pos = savedPos
|
|
1590
|
+
return null
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1593
|
+
|
|
1594
|
+
// After `=>`: either a block body or a single expression.
|
|
1595
|
+
//
|
|
1596
|
+
// A `{` after `=>` is a BLOCK (JS semantics), except when the
|
|
1597
|
+
// tokens right after it make that impossible -- `{ ...x }`,
|
|
846
1598
|
// `{ key: value }`, `{ a, b }` -- in which case it's an object
|
|
847
1599
|
// literal, so the older `x => { id: x }` style keeps working. A
|
|
848
1600
|
// block can't legally start with `name :` (no labels) or `name ,`
|
|
849
|
-
// (no comma operator), so the lookahead is unambiguous. The
|
|
850
|
-
//
|
|
851
|
-
//
|
|
1601
|
+
// (no comma operator), so the lookahead is unambiguous. The cases it
|
|
1602
|
+
// can't resolve are `{}`, `{ name }`, `{ [key]: v }` and
|
|
1603
|
+
// `{ method() {} }`; those are blocks, exactly as in JS. Wrap an
|
|
1604
|
+
// object literal in parentheses: `x => ({ ... })`.
|
|
1605
|
+
//
|
|
1606
|
+
// `yield` is never an operator inside an arrow body.
|
|
852
1607
|
parseArrowBody() {
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
1608
|
+
return this.withGenerator(false, () => {
|
|
1609
|
+
if (this.check(TokenType.LBRACE) && !this.looksLikeObjectLiteral()) {
|
|
1610
|
+
return BlockStatement(this.parseBlockStatements('arrow function body'))
|
|
1611
|
+
}
|
|
1612
|
+
return this.parseAssignment()
|
|
1613
|
+
})
|
|
857
1614
|
}
|
|
858
1615
|
|
|
859
1616
|
looksLikeObjectLiteral() {
|
|
@@ -863,6 +1620,7 @@ export class Parser {
|
|
|
863
1620
|
if (first.type === TokenType.SPREAD) return true
|
|
864
1621
|
const isKey =
|
|
865
1622
|
first.type === TokenType.STRING ||
|
|
1623
|
+
first.type === TokenType.NUMBER ||
|
|
866
1624
|
first.type === TokenType.IDENTIFIER ||
|
|
867
1625
|
KEYWORD_TOKEN_TYPES.has(first.type)
|
|
868
1626
|
return (
|
|
@@ -872,36 +1630,6 @@ export class Parser {
|
|
|
872
1630
|
)
|
|
873
1631
|
}
|
|
874
1632
|
|
|
875
|
-
// Entry point for arrow functions, including the async forms:
|
|
876
|
-
// async x => ... async (a, b) => ...
|
|
877
|
-
// async x: Type => ... async (a: Type) => ...
|
|
878
|
-
//
|
|
879
|
-
// `async` is a keyword token but also a legal identifier name, so
|
|
880
|
-
// it is only treated as the async modifier when what follows could
|
|
881
|
-
// start an arrow's parameter list (an identifier/keyword name or
|
|
882
|
-
// '('). `async => 1` (a param literally named async) still goes
|
|
883
|
-
// down the normal path, and so does `async(x)` as a plain call,
|
|
884
|
-
// because the speculative parse below backs out and restores the
|
|
885
|
-
// position when no `=>` follows.
|
|
886
|
-
tryParseArrowFunction() {
|
|
887
|
-
if (this.check(TokenType.ASYNC)) {
|
|
888
|
-
const next = this.tokens[this.pos + 1]
|
|
889
|
-
const startsParams =
|
|
890
|
-
next &&
|
|
891
|
-
(next.type === TokenType.LPAREN ||
|
|
892
|
-
next.type === TokenType.IDENTIFIER ||
|
|
893
|
-
(next.type !== TokenType.ARROW && KEYWORD_TOKEN_TYPES.has(next.type)))
|
|
894
|
-
if (startsParams) {
|
|
895
|
-
const savedPos = this.pos
|
|
896
|
-
this.advance() // consume 'async'
|
|
897
|
-
const arrow = this.tryParseSyncArrow()
|
|
898
|
-
if (arrow) return { ...arrow, isAsync: true }
|
|
899
|
-
this.pos = savedPos
|
|
900
|
-
return null
|
|
901
|
-
}
|
|
902
|
-
}
|
|
903
|
-
return this.tryParseSyncArrow()
|
|
904
|
-
}
|
|
905
1633
|
|
|
906
1634
|
// Arrow functions are tried with backtracking before falling
|
|
907
1635
|
// through to the normal ternary/assignment chain, since both forms
|
|
@@ -910,6 +1638,11 @@ export class Parser {
|
|
|
910
1638
|
// expression. The body is an expression or, via parseArrowBody, a
|
|
911
1639
|
// `{ ... }` statement block (script code only -- templates reject
|
|
912
1640
|
// BlockStatement in their expression generators).
|
|
1641
|
+
//
|
|
1642
|
+
// Parenthesized params may be plain names, destructuring patterns
|
|
1643
|
+
// ([k, v], { id, name }), rest params (...args), typed (a: number),
|
|
1644
|
+
// optional (a?: number) and have defaults (a = 1). A return type may
|
|
1645
|
+
// follow the closing paren: `(a: number): number => a * 2`.
|
|
913
1646
|
tryParseSyncArrow() {
|
|
914
1647
|
// single-param form: x => expr or x: Type => expr
|
|
915
1648
|
if (
|
|
@@ -921,7 +1654,7 @@ export class Parser {
|
|
|
921
1654
|
const param = this.advance().value
|
|
922
1655
|
this.advance() // consume '=>'
|
|
923
1656
|
const body = this.parseArrowBody()
|
|
924
|
-
return ArrowFunctionExpr([param], body, [null])
|
|
1657
|
+
return ArrowFunctionExpr([param], body, [null], false, [null])
|
|
925
1658
|
}
|
|
926
1659
|
if (next && next.type === TokenType.COLON) {
|
|
927
1660
|
const savedPos = this.pos
|
|
@@ -931,7 +1664,7 @@ export class Parser {
|
|
|
931
1664
|
if (paramType !== null && this.check(TokenType.ARROW)) {
|
|
932
1665
|
this.advance()
|
|
933
1666
|
const body = this.parseArrowBody()
|
|
934
|
-
return ArrowFunctionExpr([param], body, [paramType])
|
|
1667
|
+
return ArrowFunctionExpr([param], body, [paramType], false, [null])
|
|
935
1668
|
}
|
|
936
1669
|
// wasn't actually a typed arrow param (e.g. the `x : y` part
|
|
937
1670
|
// of a ternary) -- back out
|
|
@@ -940,25 +1673,51 @@ export class Parser {
|
|
|
940
1673
|
return null
|
|
941
1674
|
}
|
|
942
1675
|
|
|
943
|
-
// (a, b) => expr or (a: Type, b
|
|
1676
|
+
// (a, b) => expr or (a: Type, b?: T, c = 1, ...rest) => expr
|
|
1677
|
+
// also ([k, v]) => expr, ({ id }) => expr
|
|
944
1678
|
if (this.check(TokenType.LPAREN)) {
|
|
945
1679
|
const savedPos = this.pos
|
|
946
1680
|
this.pos++
|
|
947
1681
|
|
|
948
1682
|
const params = []
|
|
949
1683
|
const paramTypes = []
|
|
1684
|
+
const paramDefaults = []
|
|
1685
|
+
const paramOptional = []
|
|
950
1686
|
let isValidParamList = true
|
|
951
1687
|
|
|
952
1688
|
if (!this.check(TokenType.RPAREN)) {
|
|
953
1689
|
while (true) {
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
!
|
|
1690
|
+
let name
|
|
1691
|
+
if (this.match(TokenType.SPREAD)) {
|
|
1692
|
+
if (!this.check(TokenType.IDENTIFIER)) {
|
|
1693
|
+
isValidParamList = false
|
|
1694
|
+
break
|
|
1695
|
+
}
|
|
1696
|
+
name = `...${this.advance().value}`
|
|
1697
|
+
} else if (
|
|
1698
|
+
this.check(TokenType.LBRACKET) ||
|
|
1699
|
+
this.check(TokenType.LBRACE)
|
|
1700
|
+
) {
|
|
1701
|
+
name = this.tryParseDestructuredParam()
|
|
1702
|
+
if (name === null) {
|
|
1703
|
+
isValidParamList = false
|
|
1704
|
+
break
|
|
1705
|
+
}
|
|
1706
|
+
} else if (
|
|
1707
|
+
this.check(TokenType.IDENTIFIER) ||
|
|
1708
|
+
KEYWORD_TOKEN_TYPES.has(this.peek().type)
|
|
957
1709
|
) {
|
|
1710
|
+
name = this.advance().value
|
|
1711
|
+
} else {
|
|
958
1712
|
isValidParamList = false
|
|
959
1713
|
break
|
|
960
1714
|
}
|
|
961
|
-
params.push(
|
|
1715
|
+
params.push(name)
|
|
1716
|
+
|
|
1717
|
+
// `(a ? b : c)` also reaches here, but then `b` is neither
|
|
1718
|
+
// `:`, `,` nor `)`, so the list is rejected below and the
|
|
1719
|
+
// whole attempt backs out to a grouped expression.
|
|
1720
|
+
paramOptional.push(this.match(TokenType.QUESTION))
|
|
962
1721
|
|
|
963
1722
|
let paramType = null
|
|
964
1723
|
if (this.match(TokenType.COLON)) {
|
|
@@ -970,6 +1729,17 @@ export class Parser {
|
|
|
970
1729
|
}
|
|
971
1730
|
paramTypes.push(paramType)
|
|
972
1731
|
|
|
1732
|
+
let defaultValue = null
|
|
1733
|
+
if (this.match(TokenType.EQUALS)) {
|
|
1734
|
+
try {
|
|
1735
|
+
defaultValue = this.parseAssignment()
|
|
1736
|
+
} catch {
|
|
1737
|
+
isValidParamList = false
|
|
1738
|
+
break
|
|
1739
|
+
}
|
|
1740
|
+
}
|
|
1741
|
+
paramDefaults.push(defaultValue)
|
|
1742
|
+
|
|
973
1743
|
if (this.match(TokenType.COMMA)) continue
|
|
974
1744
|
break
|
|
975
1745
|
}
|
|
@@ -977,10 +1747,32 @@ export class Parser {
|
|
|
977
1747
|
|
|
978
1748
|
if (isValidParamList && this.check(TokenType.RPAREN)) {
|
|
979
1749
|
this.pos++
|
|
1750
|
+
|
|
1751
|
+
// Optional return type: `(x): number => ...`. In a ternary
|
|
1752
|
+
// (`c ? (x) : y`) the type parses but no `=>` follows, so the
|
|
1753
|
+
// whole attempt backs out.
|
|
1754
|
+
let returnType = null
|
|
1755
|
+
if (this.check(TokenType.COLON)) {
|
|
1756
|
+
this.pos++
|
|
1757
|
+
returnType = this.tryParseReturnType()
|
|
1758
|
+
if (returnType === null || !this.check(TokenType.ARROW)) {
|
|
1759
|
+
this.pos = savedPos
|
|
1760
|
+
return null
|
|
1761
|
+
}
|
|
1762
|
+
}
|
|
1763
|
+
|
|
980
1764
|
if (this.check(TokenType.ARROW)) {
|
|
981
1765
|
this.pos++
|
|
982
1766
|
const body = this.parseArrowBody()
|
|
983
|
-
return ArrowFunctionExpr(
|
|
1767
|
+
return ArrowFunctionExpr(
|
|
1768
|
+
params,
|
|
1769
|
+
body,
|
|
1770
|
+
paramTypes,
|
|
1771
|
+
false,
|
|
1772
|
+
paramDefaults,
|
|
1773
|
+
paramOptional,
|
|
1774
|
+
returnType,
|
|
1775
|
+
)
|
|
984
1776
|
}
|
|
985
1777
|
}
|
|
986
1778
|
|
|
@@ -1020,14 +1812,56 @@ export class Parser {
|
|
|
1020
1812
|
}
|
|
1021
1813
|
|
|
1022
1814
|
parseLogicalAnd() {
|
|
1023
|
-
let left = this.
|
|
1815
|
+
let left = this.parseNotOperand()
|
|
1024
1816
|
while (this.match(TokenType.AND)) {
|
|
1025
|
-
const right = this.
|
|
1817
|
+
const right = this.parseNotOperand()
|
|
1026
1818
|
left = BinaryExpr('&&', left, right)
|
|
1027
1819
|
}
|
|
1028
1820
|
return left
|
|
1029
1821
|
}
|
|
1030
1822
|
|
|
1823
|
+
// Loose mode only: the WORD `not` (value 'not') sits above is/has/
|
|
1824
|
+
// exists. In tight mode, or for the symbol `!`, this falls straight
|
|
1825
|
+
// through and parseUnary handles it as before.
|
|
1826
|
+
parseNotOperand() {
|
|
1827
|
+
if (
|
|
1828
|
+
this.looseNot &&
|
|
1829
|
+
this.check(TokenType.NOT) &&
|
|
1830
|
+
this.peek().value === 'not'
|
|
1831
|
+
) {
|
|
1832
|
+
this.advance()
|
|
1833
|
+
return UnaryExpr('!', this.parseNotOperand())
|
|
1834
|
+
}
|
|
1835
|
+
return this.parseBitwiseOr()
|
|
1836
|
+
}
|
|
1837
|
+
|
|
1838
|
+
parseBitwiseOr() {
|
|
1839
|
+
let left = this.parseBitwiseXor()
|
|
1840
|
+
while (this.match(TokenType.PIPE)) {
|
|
1841
|
+
const right = this.parseBitwiseXor()
|
|
1842
|
+
left = BinaryExpr('|', left, right)
|
|
1843
|
+
}
|
|
1844
|
+
return left
|
|
1845
|
+
}
|
|
1846
|
+
|
|
1847
|
+
parseBitwiseXor() {
|
|
1848
|
+
let left = this.parseBitwiseAnd()
|
|
1849
|
+
while (this.match(TokenType.CARET)) {
|
|
1850
|
+
const right = this.parseBitwiseAnd()
|
|
1851
|
+
left = BinaryExpr('^', left, right)
|
|
1852
|
+
}
|
|
1853
|
+
return left
|
|
1854
|
+
}
|
|
1855
|
+
|
|
1856
|
+
parseBitwiseAnd() {
|
|
1857
|
+
let left = this.parseEquality()
|
|
1858
|
+
while (this.match(TokenType.AMP)) {
|
|
1859
|
+
const right = this.parseEquality()
|
|
1860
|
+
left = BinaryExpr('&', left, right)
|
|
1861
|
+
}
|
|
1862
|
+
return left
|
|
1863
|
+
}
|
|
1864
|
+
|
|
1031
1865
|
parseEquality() {
|
|
1032
1866
|
let left = this.parseComparison()
|
|
1033
1867
|
while (this.check(TokenType.IS)) {
|
|
@@ -1039,18 +1873,64 @@ export class Parser {
|
|
|
1039
1873
|
return left
|
|
1040
1874
|
}
|
|
1041
1875
|
|
|
1876
|
+
// `as` / `satisfies` lex as plain identifiers, so they only count as
|
|
1877
|
+
// a cast when they sit on the same line as the end of the previous
|
|
1878
|
+
// token and a type can follow. That keeps them usable as ordinary
|
|
1879
|
+
// names on a line of their own.
|
|
1880
|
+
isAsCast() {
|
|
1881
|
+
const tok = this.peek()
|
|
1882
|
+
if (
|
|
1883
|
+
tok.type !== TokenType.IDENTIFIER ||
|
|
1884
|
+
(tok.value !== 'as' && tok.value !== 'satisfies')
|
|
1885
|
+
) {
|
|
1886
|
+
return false
|
|
1887
|
+
}
|
|
1888
|
+
const prev = this.tokens[this.pos - 1]
|
|
1889
|
+
const next = this.tokens[this.pos + 1]
|
|
1890
|
+
if (!prev || !next || prev.line !== tok.line) return false
|
|
1891
|
+
return (
|
|
1892
|
+
next.type === TokenType.IDENTIFIER ||
|
|
1893
|
+
next.type === TokenType.CONST ||
|
|
1894
|
+
next.type === TokenType.LBRACE ||
|
|
1895
|
+
next.type === TokenType.LBRACKET ||
|
|
1896
|
+
next.type === TokenType.LPAREN ||
|
|
1897
|
+
next.type === TokenType.STRING ||
|
|
1898
|
+
next.type === TokenType.NUMBER ||
|
|
1899
|
+
next.type === TokenType.TYPEOF ||
|
|
1900
|
+
next.type === TokenType.VOID ||
|
|
1901
|
+
next.type === TokenType.MINUS
|
|
1902
|
+
)
|
|
1903
|
+
}
|
|
1904
|
+
|
|
1042
1905
|
parseComparison() {
|
|
1043
1906
|
let left = this.parsePredicate()
|
|
1044
|
-
while (
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1907
|
+
while (true) {
|
|
1908
|
+
if (this.isAsCast()) {
|
|
1909
|
+
const keyword = this.advance().value // 'as' | 'satisfies'
|
|
1910
|
+
let type
|
|
1911
|
+
if (keyword === 'as' && this.match(TokenType.CONST)) {
|
|
1912
|
+
type = 'const'
|
|
1913
|
+
} else {
|
|
1914
|
+
type = this.parseTypeExpression()
|
|
1915
|
+
}
|
|
1916
|
+
left = AsExpr(left, type, keyword)
|
|
1917
|
+
continue
|
|
1918
|
+
}
|
|
1919
|
+
// `>>=` / `<<=` start with a GT/LT token; those belong to
|
|
1920
|
+
// parseAssignment, not to a comparison.
|
|
1921
|
+
if (COMPARISON_SYMBOLS[this.peek().type] && !this.compoundShiftAt()) {
|
|
1922
|
+
const operator = COMPARISON_SYMBOLS[this.advance().type]
|
|
1923
|
+
const right = this.parsePredicate()
|
|
1924
|
+
left = BinaryExpr(operator, left, right)
|
|
1925
|
+
continue
|
|
1926
|
+
}
|
|
1927
|
+
break
|
|
1048
1928
|
}
|
|
1049
1929
|
return left
|
|
1050
1930
|
}
|
|
1051
1931
|
|
|
1052
1932
|
parsePredicate() {
|
|
1053
|
-
const left = this.
|
|
1933
|
+
const left = this.parseShift()
|
|
1054
1934
|
|
|
1055
1935
|
if (this.match(TokenType.EXISTS)) {
|
|
1056
1936
|
return BinaryExpr('!=', left, Literal(null))
|
|
@@ -1059,13 +1939,24 @@ export class Parser {
|
|
|
1059
1939
|
return BinaryExpr('==', left, Literal(null))
|
|
1060
1940
|
}
|
|
1061
1941
|
if (this.match(TokenType.HAS)) {
|
|
1062
|
-
const right = this.
|
|
1063
|
-
return
|
|
1942
|
+
const right = this.parseShift()
|
|
1943
|
+
return hasExpr(left, right)
|
|
1064
1944
|
}
|
|
1065
1945
|
|
|
1066
1946
|
return left
|
|
1067
1947
|
}
|
|
1068
1948
|
|
|
1949
|
+
parseShift() {
|
|
1950
|
+
let left = this.parseAdditive()
|
|
1951
|
+
let shift
|
|
1952
|
+
while ((shift = this.shiftOperatorAt())) {
|
|
1953
|
+
this.pos += shift.len
|
|
1954
|
+
const right = this.parseAdditive()
|
|
1955
|
+
left = BinaryExpr(shift.op, left, right)
|
|
1956
|
+
}
|
|
1957
|
+
return left
|
|
1958
|
+
}
|
|
1959
|
+
|
|
1069
1960
|
parseAdditive() {
|
|
1070
1961
|
let left = this.parseMultiplicative()
|
|
1071
1962
|
while (ADDITIVE_SYMBOLS[this.peek().type]) {
|
|
@@ -1105,34 +1996,85 @@ export class Parser {
|
|
|
1105
1996
|
if (this.match(TokenType.NOT)) {
|
|
1106
1997
|
return UnaryExpr('!', this.parseUnary())
|
|
1107
1998
|
}
|
|
1999
|
+
if (this.match(TokenType.TILDE)) {
|
|
2000
|
+
return UnaryExpr('~', this.parseUnary())
|
|
2001
|
+
}
|
|
1108
2002
|
if (this.match(TokenType.MINUS)) {
|
|
1109
2003
|
return UnaryExpr('-', this.parseUnary())
|
|
1110
2004
|
}
|
|
2005
|
+
if (this.match(TokenType.PLUS)) {
|
|
2006
|
+
return UnaryExpr('+', this.parseUnary())
|
|
2007
|
+
}
|
|
1111
2008
|
if (this.match(TokenType.TYPEOF)) {
|
|
1112
2009
|
return UnaryExpr('typeof', this.parseUnary())
|
|
1113
2010
|
}
|
|
2011
|
+
if (this.match(TokenType.DELETE)) {
|
|
2012
|
+
return UnaryExpr('delete', this.parseUnary())
|
|
2013
|
+
}
|
|
2014
|
+
if (this.match(TokenType.VOID)) {
|
|
2015
|
+
return UnaryExpr('void', this.parseUnary())
|
|
2016
|
+
}
|
|
1114
2017
|
if (this.match(TokenType.PLUS_PLUS)) {
|
|
1115
|
-
|
|
1116
|
-
return AssignmentExpr(target, BinaryExpr('+', target, Literal(1)))
|
|
2018
|
+
return UpdateExpr('++', this.parseUnary(), true)
|
|
1117
2019
|
}
|
|
1118
2020
|
if (this.match(TokenType.MINUS_MINUS)) {
|
|
1119
|
-
|
|
1120
|
-
return AssignmentExpr(target, BinaryExpr('-', target, Literal(1)))
|
|
2021
|
+
return UpdateExpr('--', this.parseUnary(), true)
|
|
1121
2022
|
}
|
|
1122
2023
|
|
|
1123
2024
|
const expr = this.parseMemberExpression()
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
2025
|
+
// Postfix must sit on the same line (`a\n++b` is `a; ++b`).
|
|
2026
|
+
const prev = this.tokens[this.pos - 1]
|
|
2027
|
+
if (prev && this.peek().line === prev.line) {
|
|
2028
|
+
if (this.match(TokenType.PLUS_PLUS)) return UpdateExpr('++', expr, false)
|
|
2029
|
+
if (this.match(TokenType.MINUS_MINUS)) return UpdateExpr('--', expr, false)
|
|
1129
2030
|
}
|
|
1130
2031
|
return expr
|
|
1131
2032
|
}
|
|
1132
2033
|
|
|
2034
|
+
// The parts of a lexed template literal, with each ${...} span
|
|
2035
|
+
// parsed as an expression. Text parts keep both `value` (cooked)
|
|
2036
|
+
// and `raw`.
|
|
2037
|
+
templateLiteralFromParts(rawParts) {
|
|
2038
|
+
return TemplateLiteralExpr(
|
|
2039
|
+
rawParts.map((p) =>
|
|
2040
|
+
p.type === 'text'
|
|
2041
|
+
? p
|
|
2042
|
+
: {
|
|
2043
|
+
type: 'expr',
|
|
2044
|
+
// Same language options as the enclosing parser, so
|
|
2045
|
+
// `${ not items has x }` follows the project's `not` mode.
|
|
2046
|
+
expression: parseExpressionString(p.source, this.options),
|
|
2047
|
+
},
|
|
2048
|
+
),
|
|
2049
|
+
)
|
|
2050
|
+
}
|
|
2051
|
+
|
|
1133
2052
|
parseMemberExpression() {
|
|
1134
2053
|
let expr = this.parsePrimary()
|
|
1135
2054
|
while (true) {
|
|
2055
|
+
// Non-null assertion `x!` / `x!.y`: only when the `!` is written
|
|
2056
|
+
// directly against the previous token, so a prefix `!` or a
|
|
2057
|
+
// `not` on the next line is never taken for it.
|
|
2058
|
+
if (
|
|
2059
|
+
this.check(TokenType.NOT) &&
|
|
2060
|
+
this.peek().value === '!' &&
|
|
2061
|
+
adjacent(this.tokens[this.pos - 1], this.peek())
|
|
2062
|
+
) {
|
|
2063
|
+
this.advance()
|
|
2064
|
+
expr = NonNullExpr(expr)
|
|
2065
|
+
continue
|
|
2066
|
+
}
|
|
2067
|
+
// Tagged template: tag`text ${x}`. Must start on the same line
|
|
2068
|
+
// as the tag, so a template literal on its own line is never
|
|
2069
|
+
// glued to the previous statement.
|
|
2070
|
+
if (this.check(TokenType.TEMPLATE_LITERAL)) {
|
|
2071
|
+
const prev = this.tokens[this.pos - 1]
|
|
2072
|
+
if (prev && prev.line === this.peek().line) {
|
|
2073
|
+
const quasi = this.templateLiteralFromParts(this.advance().value)
|
|
2074
|
+
expr = TaggedTemplateExpr(expr, quasi)
|
|
2075
|
+
continue
|
|
2076
|
+
}
|
|
2077
|
+
}
|
|
1136
2078
|
if (this.match(TokenType.DOT)) {
|
|
1137
2079
|
const property = this.parsePropertyName("after '.'")
|
|
1138
2080
|
expr = MemberExpr(expr, property)
|
|
@@ -1147,7 +2089,17 @@ export class Parser {
|
|
|
1147
2089
|
expr = MemberExpr(expr, property, true)
|
|
1148
2090
|
continue
|
|
1149
2091
|
}
|
|
1150
|
-
|
|
2092
|
+
|
|
2093
|
+
// Generic call: f<T>(x). Speculative, so `a < b` is untouched.
|
|
2094
|
+
if (this.check(TokenType.LT)) {
|
|
2095
|
+
const typeArgs = this.tryParseTypeArguments([TokenType.LPAREN])
|
|
2096
|
+
if (typeArgs !== null) {
|
|
2097
|
+
expr = { ...CallExpr(expr, this.parseCallArguments()), typeArgs }
|
|
2098
|
+
continue
|
|
2099
|
+
}
|
|
2100
|
+
}
|
|
2101
|
+
|
|
2102
|
+
if (this.check(TokenType.LPAREN)) {
|
|
1151
2103
|
expr = CallExpr(expr, this.parseCallArguments())
|
|
1152
2104
|
continue
|
|
1153
2105
|
}
|
|
@@ -1194,19 +2146,71 @@ export class Parser {
|
|
|
1194
2146
|
|
|
1195
2147
|
parsePrimary() {
|
|
1196
2148
|
if (this.match(TokenType.NEW)) {
|
|
2149
|
+
// new.target
|
|
2150
|
+
if (this.check(TokenType.DOT)) {
|
|
2151
|
+
this.advance()
|
|
2152
|
+
const prop = this.parsePropertyName("after 'new.'")
|
|
2153
|
+
if (prop !== 'target') {
|
|
2154
|
+
throw new Error(
|
|
2155
|
+
`Expected 'new.target' at line ${this.peek().line}, got 'new.${prop}'`,
|
|
2156
|
+
)
|
|
2157
|
+
}
|
|
2158
|
+
return Identifier('new.target')
|
|
2159
|
+
}
|
|
1197
2160
|
let callee = this.parsePrimary()
|
|
1198
2161
|
while (this.match(TokenType.DOT)) {
|
|
1199
|
-
const property = this.
|
|
1200
|
-
TokenType.IDENTIFIER,
|
|
1201
|
-
"Expected a property name after '.'",
|
|
1202
|
-
).value
|
|
2162
|
+
const property = this.parsePropertyName("after '.'")
|
|
1203
2163
|
callee = MemberExpr(callee, property)
|
|
1204
2164
|
}
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
2165
|
+
const typeArgs = this.tryParseTypeArguments([TokenType.LPAREN])
|
|
2166
|
+
let args = []
|
|
2167
|
+
if (this.check(TokenType.LPAREN)) {
|
|
2168
|
+
args = this.parseCallArguments()
|
|
2169
|
+
}
|
|
2170
|
+
return typeArgs
|
|
2171
|
+
? { ...NewExpr(callee, args), typeArgs }
|
|
2172
|
+
: NewExpr(callee, args)
|
|
2173
|
+
}
|
|
2174
|
+
|
|
2175
|
+
// function (a, b) { ... } / async function* name(a) { ... }
|
|
2176
|
+
if (this.isFunctionKeywordAhead()) {
|
|
2177
|
+
const isAsync = this.match(TokenType.ASYNC)
|
|
2178
|
+
const fn = this.parseFunctionRest(isAsync)
|
|
2179
|
+
if (!fn.body) {
|
|
2180
|
+
throw new Error(
|
|
2181
|
+
`Expected '{' to start function body at line ${this.peek().line}`,
|
|
2182
|
+
)
|
|
2183
|
+
}
|
|
2184
|
+
return {
|
|
2185
|
+
...FunctionExpr(fn.params, fn.body, fn.isAsync, fn.name, fn.isGenerator),
|
|
2186
|
+
...signatureExtras(fn),
|
|
2187
|
+
}
|
|
2188
|
+
}
|
|
2189
|
+
|
|
2190
|
+
// class { ... } / class Name extends Base { ... } as an expression
|
|
2191
|
+
if (this.isClassAhead(true)) {
|
|
2192
|
+
return this.parseClass(true)
|
|
2193
|
+
}
|
|
2194
|
+
|
|
2195
|
+
// Regex literal. String(regex) yields "/pattern/flags", which
|
|
2196
|
+
// every generator already emits for Literal nodes, so no codegen
|
|
2197
|
+
// changes are needed.
|
|
2198
|
+
if (this.check(TokenType.REGEX)) {
|
|
2199
|
+
const tok = this.advance()
|
|
2200
|
+
try {
|
|
2201
|
+
return Literal(new RegExp(tok.value.pattern, tok.value.flags))
|
|
2202
|
+
} catch (err) {
|
|
2203
|
+
throw new Error(
|
|
2204
|
+
`Invalid regular expression at line ${tok.line}: ${err.message}`,
|
|
2205
|
+
)
|
|
1208
2206
|
}
|
|
1209
|
-
|
|
2207
|
+
}
|
|
2208
|
+
|
|
2209
|
+
// 10n -> BigInt("10"), so every generator handles it as a normal
|
|
2210
|
+
// call to the BigInt global.
|
|
2211
|
+
if (this.check(TokenType.BIGINT)) {
|
|
2212
|
+
const text = this.advance().value
|
|
2213
|
+
return CallExpr(Identifier('BigInt'), [Literal(text)])
|
|
1210
2214
|
}
|
|
1211
2215
|
|
|
1212
2216
|
if (this.check(TokenType.NUMBER) || this.check(TokenType.STRING)) {
|
|
@@ -1214,13 +2218,7 @@ export class Parser {
|
|
|
1214
2218
|
}
|
|
1215
2219
|
|
|
1216
2220
|
if (this.check(TokenType.TEMPLATE_LITERAL)) {
|
|
1217
|
-
|
|
1218
|
-
const parts = rawParts.map((p) =>
|
|
1219
|
-
p.type === 'text'
|
|
1220
|
-
? p
|
|
1221
|
-
: { type: 'expr', expression: parseExpressionString(p.source) },
|
|
1222
|
-
)
|
|
1223
|
-
return TemplateLiteralExpr(parts)
|
|
2221
|
+
return this.templateLiteralFromParts(this.advance().value)
|
|
1224
2222
|
}
|
|
1225
2223
|
|
|
1226
2224
|
if (
|
|
@@ -1232,11 +2230,7 @@ export class Parser {
|
|
|
1232
2230
|
// tokens (there's no separate keyword TokenType for them), but
|
|
1233
2231
|
// they're JS keyword literals, not variable/state references.
|
|
1234
2232
|
// Emitting them as Literal here -- instead of Identifier -- means
|
|
1235
|
-
// every downstream consumer
|
|
1236
|
-
// generateTemplateExpression, and anything added later) treats
|
|
1237
|
-
// them correctly by construction, rather than each one needing its
|
|
1238
|
-
// own special-case list of magic strings to avoid prefixing them
|
|
1239
|
-
// with "instance.".
|
|
2233
|
+
// every downstream consumer treats them correctly by construction.
|
|
1240
2234
|
if (name === 'null') return Literal(null)
|
|
1241
2235
|
if (name === 'undefined') return Literal(undefined)
|
|
1242
2236
|
if (name === 'true') return Literal(true)
|
|
@@ -1244,8 +2238,16 @@ export class Parser {
|
|
|
1244
2238
|
return Identifier(name)
|
|
1245
2239
|
}
|
|
1246
2240
|
|
|
2241
|
+
// Grouping, and the comma operator: (a, b, c)
|
|
1247
2242
|
if (this.match(TokenType.LPAREN)) {
|
|
1248
|
-
|
|
2243
|
+
let expr = this.parseExpression()
|
|
2244
|
+
if (this.check(TokenType.COMMA)) {
|
|
2245
|
+
const expressions = [expr]
|
|
2246
|
+
while (this.match(TokenType.COMMA)) {
|
|
2247
|
+
expressions.push(this.parseExpression())
|
|
2248
|
+
}
|
|
2249
|
+
expr = SequenceExpr(expressions)
|
|
2250
|
+
}
|
|
1249
2251
|
this.expect(
|
|
1250
2252
|
TokenType.RPAREN,
|
|
1251
2253
|
"Expected ')' to close a grouped expression",
|
|
@@ -1267,43 +2269,134 @@ export class Parser {
|
|
|
1267
2269
|
// AST -- Tylix's own codegen never interprets them, it only needs
|
|
1268
2270
|
// the exact TS source text to paste into the virtual .ts file handed
|
|
1269
2271
|
// to the TypeScript compiler API.
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
2272
|
+
//
|
|
2273
|
+
// Supported: names (Foo, Foo.Bar), generics (Map<string, Post[]>),
|
|
2274
|
+
// unions and intersections, arrays and indexed access (T[], T[K]),
|
|
2275
|
+
// string/number literal types ("asc" | "desc", 1 | 2), tuples
|
|
2276
|
+
// ([string, number]), object types (with index signatures and method
|
|
2277
|
+
// signatures), function types ((id: number) => void), grouped types,
|
|
2278
|
+
// keyof / typeof / readonly prefixes, void/null/undefined.
|
|
2279
|
+
// (The entry point, parseTypeExpression, is defined further down: it
|
|
2280
|
+
// adds conditional types on top of parseUnionType.)
|
|
2281
|
+
|
|
2282
|
+
parseIntersectionType() {
|
|
2283
|
+
this.match(TokenType.AMP) // leading "&"
|
|
2284
|
+
let left = this.parseTypeOperand()
|
|
2285
|
+
while (this.match(TokenType.AMP)) {
|
|
2286
|
+
left = `${left} & ${this.parseTypeOperand()}`
|
|
1276
2287
|
}
|
|
1277
2288
|
return left
|
|
1278
2289
|
}
|
|
1279
2290
|
|
|
1280
|
-
|
|
1281
|
-
|
|
2291
|
+
parseTypeOperand() {
|
|
2292
|
+
const tok = this.peek()
|
|
2293
|
+
|
|
2294
|
+
if (tok.type === TokenType.TYPEOF) {
|
|
2295
|
+
this.advance()
|
|
2296
|
+
let name = this.parseNameToken("Expected a name after 'typeof'")
|
|
2297
|
+
while (this.match(TokenType.DOT)) {
|
|
2298
|
+
name += `.${this.parsePropertyName("after '.'")}`
|
|
2299
|
+
}
|
|
2300
|
+
return this.parseTypeSuffixes(`typeof ${name}`)
|
|
2301
|
+
}
|
|
2302
|
+
|
|
2303
|
+
let prefix = ''
|
|
2304
|
+
if (
|
|
2305
|
+
tok.type === TokenType.IDENTIFIER &&
|
|
2306
|
+
(tok.value === 'keyof' || tok.value === 'readonly' || tok.value === 'infer')
|
|
2307
|
+
) {
|
|
2308
|
+
const next = this.tokens[this.pos + 1]
|
|
2309
|
+
if (
|
|
2310
|
+
next &&
|
|
2311
|
+
(next.type === TokenType.IDENTIFIER ||
|
|
2312
|
+
next.type === TokenType.LBRACE ||
|
|
2313
|
+
next.type === TokenType.LPAREN ||
|
|
2314
|
+
next.type === TokenType.LBRACKET ||
|
|
2315
|
+
next.type === TokenType.TYPEOF)
|
|
2316
|
+
) {
|
|
2317
|
+
this.advance()
|
|
2318
|
+
prefix = `${tok.value} `
|
|
2319
|
+
}
|
|
2320
|
+
}
|
|
2321
|
+
|
|
2322
|
+
return this.parseTypeSuffixes(prefix + this.parsePrimaryType())
|
|
2323
|
+
}
|
|
2324
|
+
|
|
2325
|
+
// `T[]` and indexed access `T[K]`
|
|
2326
|
+
parseTypeSuffixes(type) {
|
|
1282
2327
|
while (this.check(TokenType.LBRACKET)) {
|
|
1283
2328
|
this.advance()
|
|
1284
|
-
this.
|
|
1285
|
-
|
|
2329
|
+
if (this.match(TokenType.RBRACKET)) {
|
|
2330
|
+
type = `${type}[]`
|
|
2331
|
+
} else {
|
|
2332
|
+
const index = this.parseTypeExpression()
|
|
2333
|
+
this.expect(
|
|
2334
|
+
TokenType.RBRACKET,
|
|
2335
|
+
"Expected ']' to close indexed access type",
|
|
2336
|
+
)
|
|
2337
|
+
type = `${type}[${index}]`
|
|
2338
|
+
}
|
|
1286
2339
|
}
|
|
1287
2340
|
return type
|
|
1288
2341
|
}
|
|
1289
2342
|
|
|
1290
2343
|
parsePrimaryType() {
|
|
1291
|
-
|
|
1292
|
-
|
|
2344
|
+
const tok = this.peek()
|
|
2345
|
+
|
|
2346
|
+
if (tok.type === TokenType.STRING) {
|
|
2347
|
+
this.advance()
|
|
2348
|
+
return JSON.stringify(tok.value)
|
|
1293
2349
|
}
|
|
1294
|
-
if (
|
|
2350
|
+
if (tok.type === TokenType.NUMBER) {
|
|
2351
|
+
this.advance()
|
|
2352
|
+
return String(tok.value)
|
|
2353
|
+
}
|
|
2354
|
+
if (
|
|
2355
|
+
tok.type === TokenType.MINUS &&
|
|
2356
|
+
this.tokens[this.pos + 1]?.type === TokenType.NUMBER
|
|
2357
|
+
) {
|
|
2358
|
+
this.advance()
|
|
2359
|
+
return `-${this.advance().value}`
|
|
2360
|
+
}
|
|
2361
|
+
if (tok.type === TokenType.TEMPLATE_LITERAL) {
|
|
2362
|
+
this.advance()
|
|
2363
|
+
const inner = tok.value
|
|
2364
|
+
.map((p) => (p.type === 'text' ? p.raw : `\${${p.source}}`))
|
|
2365
|
+
.join('')
|
|
2366
|
+
return `\`${inner}\``
|
|
2367
|
+
}
|
|
2368
|
+
if (tok.type === TokenType.LT) {
|
|
2369
|
+
const fn = this.tryParseFunctionType()
|
|
2370
|
+
if (fn !== null) return fn
|
|
2371
|
+
throw new Error(`Expected a type name at line ${tok.line}, got ${tok.type}`)
|
|
2372
|
+
}
|
|
2373
|
+
if (tok.type === TokenType.LBRACE) {
|
|
2374
|
+
return this.parseObjectTypeLiteral()
|
|
2375
|
+
}
|
|
2376
|
+
if (tok.type === TokenType.LBRACKET) {
|
|
2377
|
+
return this.parseTupleType()
|
|
2378
|
+
}
|
|
2379
|
+
if (tok.type === TokenType.LPAREN) {
|
|
2380
|
+
// `(a: T) => R` is a function type; anything else in parens is
|
|
2381
|
+
// a grouped type like `(A | B)[]`.
|
|
2382
|
+
const fn = this.tryParseFunctionType()
|
|
2383
|
+
if (fn !== null) return fn
|
|
2384
|
+
this.advance()
|
|
1295
2385
|
const inner = this.parseTypeExpression()
|
|
1296
2386
|
this.expect(TokenType.RPAREN, "Expected ')' to close grouped type")
|
|
1297
2387
|
return `(${inner})`
|
|
1298
2388
|
}
|
|
1299
2389
|
|
|
1300
|
-
|
|
2390
|
+
// `void` is a keyword token but a perfectly good type name.
|
|
2391
|
+
if (tok.type !== TokenType.IDENTIFIER && tok.type !== TokenType.VOID) {
|
|
2392
|
+
throw new Error(
|
|
2393
|
+
`Expected a type name at line ${tok.line}, got ${tok.type}`,
|
|
2394
|
+
)
|
|
2395
|
+
}
|
|
2396
|
+
this.advance()
|
|
2397
|
+
let name = tok.value
|
|
1301
2398
|
while (this.match(TokenType.DOT)) {
|
|
1302
|
-
|
|
1303
|
-
TokenType.IDENTIFIER,
|
|
1304
|
-
"Expected a property name after '.'",
|
|
1305
|
-
).value
|
|
1306
|
-
name += `.${prop}`
|
|
2399
|
+
name += `.${this.parsePropertyName("after '.'")}`
|
|
1307
2400
|
}
|
|
1308
2401
|
|
|
1309
2402
|
if (this.match(TokenType.LT)) {
|
|
@@ -1318,27 +2411,671 @@ export class Parser {
|
|
|
1318
2411
|
return name
|
|
1319
2412
|
}
|
|
1320
2413
|
|
|
1321
|
-
|
|
1322
|
-
|
|
2414
|
+
// `(a: T, b?: U, ...rest: V[])` -> "a: T, b?: U, ...rest: V[]"
|
|
2415
|
+
parseTypeParamList() {
|
|
2416
|
+
this.expect(TokenType.LPAREN, "Expected '(' to start a parameter list")
|
|
2417
|
+
const params = []
|
|
2418
|
+
while (!this.check(TokenType.RPAREN)) {
|
|
2419
|
+
const rest = this.match(TokenType.SPREAD)
|
|
2420
|
+
const name = this.parseNameToken('Expected a parameter name')
|
|
2421
|
+
const optional = this.match(TokenType.QUESTION)
|
|
2422
|
+
this.expect(TokenType.COLON, "Expected ':' after parameter name")
|
|
2423
|
+
const type = this.parseTypeExpression()
|
|
2424
|
+
params.push(`${rest ? '...' : ''}${name}${optional ? '?' : ''}: ${type}`)
|
|
2425
|
+
if (!this.match(TokenType.COMMA)) break
|
|
2426
|
+
}
|
|
2427
|
+
this.expect(TokenType.RPAREN, "Expected ')' to close a parameter list")
|
|
2428
|
+
return params.join(', ')
|
|
2429
|
+
}
|
|
2430
|
+
|
|
2431
|
+
parseMethod() {
|
|
2432
|
+
const startLine = this.peek().line
|
|
2433
|
+
const isAsync = this.match(TokenType.ASYNC)
|
|
2434
|
+
const name = this.parseNameToken('Expected method name')
|
|
2435
|
+
const typeParams = this.check(TokenType.LT) ? this.parseOptionalTypeParams() : ''
|
|
2436
|
+
this.expect(TokenType.LPAREN, "Expected '(' after method name")
|
|
2437
|
+
|
|
2438
|
+
const params = this.parseParamList()
|
|
2439
|
+
|
|
2440
|
+
let returnType = null
|
|
2441
|
+
if (this.match(TokenType.COLON)) {
|
|
2442
|
+
returnType = this.parseReturnType()
|
|
2443
|
+
}
|
|
2444
|
+
|
|
2445
|
+
this.expect(TokenType.LBRACE, "Expected '{' to start method body")
|
|
2446
|
+
const body = []
|
|
2447
|
+
while (!this.check(TokenType.RBRACE)) {
|
|
2448
|
+
body.push(this.parseStatement())
|
|
2449
|
+
}
|
|
2450
|
+
this.expect(TokenType.RBRACE, "Expected '}' to close method body")
|
|
2451
|
+
|
|
2452
|
+
return {
|
|
2453
|
+
...MethodNode(name, params, body, returnType),
|
|
2454
|
+
isAsync,
|
|
2455
|
+
...(typeParams ? { typeParams } : {}),
|
|
2456
|
+
line: startLine,
|
|
2457
|
+
}
|
|
2458
|
+
}
|
|
2459
|
+
|
|
2460
|
+
parseFunctionRest(isAsync) {
|
|
2461
|
+
this.expect(TokenType.FUNCTION, "Expected 'function'")
|
|
2462
|
+
const isGenerator = this.match(TokenType.STAR)
|
|
2463
|
+
let name = null
|
|
2464
|
+
if (!this.check(TokenType.LPAREN) && !this.check(TokenType.LT)) {
|
|
2465
|
+
name = this.parseNameToken('Expected a function name')
|
|
2466
|
+
}
|
|
2467
|
+
const typeParams = this.parseOptionalTypeParams()
|
|
2468
|
+
this.expect(TokenType.LPAREN, "Expected '(' after function name")
|
|
2469
|
+
const params = this.parseParamList()
|
|
2470
|
+
const returnType = this.match(TokenType.COLON) ? this.parseReturnType() : null
|
|
2471
|
+
// A named function with no `{` is an overload signature (statement
|
|
2472
|
+
// form only; parsePrimary rejects a body-less function expression).
|
|
2473
|
+
let body = null
|
|
2474
|
+
if (!name || this.check(TokenType.LBRACE)) {
|
|
2475
|
+
body = this.withGenerator(isGenerator, () =>
|
|
2476
|
+
this.parseBlockStatements('function body'),
|
|
2477
|
+
)
|
|
2478
|
+
} else {
|
|
2479
|
+
this.endSignature('function body')
|
|
2480
|
+
}
|
|
2481
|
+
return { name, params, body, isAsync, isGenerator, typeParams, returnType }
|
|
2482
|
+
}
|
|
2483
|
+
|
|
2484
|
+
// A body-less signature must end at `;`, `}` or a line break, so a
|
|
2485
|
+
// genuinely missing `{` still gets a clear error.
|
|
2486
|
+
endSignature(what) {
|
|
2487
|
+
if (this.match(TokenType.SEMICOLON)) return
|
|
2488
|
+
const prev = this.tokens[this.pos - 1]
|
|
2489
|
+
const next = this.peek()
|
|
2490
|
+
if (next.type === TokenType.RBRACE || next.type === TokenType.EOF || next.line !== prev.line) {
|
|
2491
|
+
return
|
|
2492
|
+
}
|
|
2493
|
+
throw new Error(
|
|
2494
|
+
`Expected '{' to start ${what} at line ${next.line}, got ${next.type}`,
|
|
2495
|
+
)
|
|
2496
|
+
}
|
|
2497
|
+
|
|
2498
|
+
parseStatementInner() {
|
|
2499
|
+
if (this.match(TokenType.SEMICOLON)) {
|
|
2500
|
+
return EmptyStatement()
|
|
2501
|
+
}
|
|
2502
|
+
|
|
2503
|
+
// A `{` at the start of a statement is always a block (JS rule).
|
|
2504
|
+
if (this.check(TokenType.LBRACE)) {
|
|
2505
|
+
return BlockStatement(this.parseBlockStatements('block'))
|
|
2506
|
+
}
|
|
2507
|
+
|
|
2508
|
+
if (this.isLabelAhead()) {
|
|
2509
|
+
const label = this.advance().value
|
|
2510
|
+
this.advance() // ':'
|
|
2511
|
+
return LabeledStatement(label, this.parseStatement())
|
|
2512
|
+
}
|
|
2513
|
+
|
|
2514
|
+
if (this.isTypeDeclarationAhead()) return this.parseTypeDeclaration()
|
|
2515
|
+
if (this.isEnumAhead()) return this.parseEnum()
|
|
2516
|
+
|
|
2517
|
+
if (this.match(TokenType.RETURN)) {
|
|
2518
|
+
const hasValue =
|
|
2519
|
+
!this.check(TokenType.SEMICOLON) && !this.check(TokenType.RBRACE)
|
|
2520
|
+
const argument = hasValue ? this.parseExpression() : null
|
|
2521
|
+
this.match(TokenType.SEMICOLON)
|
|
2522
|
+
return ReturnStatement(argument)
|
|
2523
|
+
}
|
|
2524
|
+
|
|
2525
|
+
if (this.match(TokenType.THROW)) {
|
|
2526
|
+
const argument = this.parseExpression()
|
|
2527
|
+
this.match(TokenType.SEMICOLON)
|
|
2528
|
+
return ThrowStatement(argument)
|
|
2529
|
+
}
|
|
2530
|
+
|
|
2531
|
+
if (this.match(TokenType.IF)) return this.parseIfStatement()
|
|
2532
|
+
if (this.match(TokenType.WHILE)) return this.parseWhileStatement()
|
|
2533
|
+
if (this.match(TokenType.DO)) return this.parseDoWhileStatement()
|
|
2534
|
+
if (this.match(TokenType.SWITCH)) return this.parseSwitchStatement()
|
|
2535
|
+
if (this.match(TokenType.FOR)) return this.parseForStatement()
|
|
2536
|
+
if (this.match(TokenType.REPEAT)) return this.parseRepeatStatement()
|
|
2537
|
+
if (this.match(TokenType.TRY)) return this.parseTryStatement()
|
|
2538
|
+
|
|
2539
|
+
if (this.check(TokenType.BREAK)) {
|
|
2540
|
+
const tok = this.advance()
|
|
2541
|
+
const label = this.optionalLabel(tok)
|
|
2542
|
+
this.match(TokenType.SEMICOLON)
|
|
2543
|
+
return BreakStatement(label)
|
|
2544
|
+
}
|
|
2545
|
+
|
|
2546
|
+
if (this.check(TokenType.CONTINUE)) {
|
|
2547
|
+
const tok = this.advance()
|
|
2548
|
+
const label = this.optionalLabel(tok)
|
|
2549
|
+
this.match(TokenType.SEMICOLON)
|
|
2550
|
+
return ContinueStatement(label)
|
|
2551
|
+
}
|
|
2552
|
+
|
|
2553
|
+
if (this.isClassAhead(false)) {
|
|
2554
|
+
return this.parseClass(false)
|
|
2555
|
+
}
|
|
2556
|
+
|
|
2557
|
+
// `function name(...)`, `function name<T>(...)`, `async function* name(...)`
|
|
2558
|
+
if (this.isFunctionKeywordAhead()) {
|
|
2559
|
+
let idx = this.pos + (this.check(TokenType.ASYNC) ? 2 : 1)
|
|
2560
|
+
if (this.tokens[idx]?.type === TokenType.STAR) idx++
|
|
2561
|
+
const nameTok = this.tokens[idx]
|
|
2562
|
+
const afterName = this.tokens[idx + 1]
|
|
2563
|
+
if (
|
|
2564
|
+
nameTok &&
|
|
2565
|
+
nameTok.type !== TokenType.LPAREN &&
|
|
2566
|
+
nameTok.type !== TokenType.LT &&
|
|
2567
|
+
afterName &&
|
|
2568
|
+
(afterName.type === TokenType.LPAREN || afterName.type === TokenType.LT)
|
|
2569
|
+
) {
|
|
2570
|
+
const isAsync = this.match(TokenType.ASYNC)
|
|
2571
|
+
const fn = this.parseFunctionRest(isAsync)
|
|
2572
|
+
return {
|
|
2573
|
+
...FunctionDeclaration(
|
|
2574
|
+
fn.name,
|
|
2575
|
+
fn.params,
|
|
2576
|
+
fn.body,
|
|
2577
|
+
fn.isAsync,
|
|
2578
|
+
fn.isGenerator,
|
|
2579
|
+
),
|
|
2580
|
+
...signatureExtras(fn),
|
|
2581
|
+
}
|
|
2582
|
+
}
|
|
2583
|
+
}
|
|
2584
|
+
|
|
2585
|
+
if (this.check(TokenType.CONST) || this.check(TokenType.LET)) {
|
|
2586
|
+
const kind = this.advance().type === TokenType.CONST ? 'const' : 'let'
|
|
2587
|
+
const decl = this.parseDeclarators(kind)
|
|
2588
|
+
this.match(TokenType.SEMICOLON)
|
|
2589
|
+
return decl
|
|
2590
|
+
}
|
|
2591
|
+
|
|
2592
|
+
this.rejectUnsupportedKeyword()
|
|
2593
|
+
|
|
2594
|
+
const tok = this.peek()
|
|
2595
|
+
const after = this.tokens[this.pos + 1]
|
|
2596
|
+
if (
|
|
2597
|
+
tok.type === TokenType.IDENTIFIER &&
|
|
2598
|
+
tok.value === 'debugger' &&
|
|
2599
|
+
!(
|
|
2600
|
+
after &&
|
|
2601
|
+
(after.type === TokenType.DOT ||
|
|
2602
|
+
after.type === TokenType.LPAREN ||
|
|
2603
|
+
after.type === TokenType.EQUALS)
|
|
2604
|
+
)
|
|
2605
|
+
) {
|
|
2606
|
+
this.advance()
|
|
2607
|
+
this.match(TokenType.SEMICOLON)
|
|
2608
|
+
return DebuggerStatement()
|
|
2609
|
+
}
|
|
2610
|
+
|
|
2611
|
+
const expression = this.parseExpression()
|
|
2612
|
+
this.match(TokenType.SEMICOLON)
|
|
2613
|
+
return ExpressionStatement(expression)
|
|
2614
|
+
}
|
|
2615
|
+
|
|
2616
|
+
parseIfStatement() {
|
|
2617
|
+
const condition = this.parseCondition()
|
|
2618
|
+
const consequent = this.parseBody('if body')
|
|
2619
|
+
|
|
2620
|
+
let alternate = null
|
|
2621
|
+
if (this.match(TokenType.ELSE)) {
|
|
2622
|
+
if (this.check(TokenType.IF)) {
|
|
2623
|
+
const startLine = this.peek().line
|
|
2624
|
+
this.advance()
|
|
2625
|
+
const nested = this.parseIfStatement()
|
|
2626
|
+
nested.line = nested.line ?? startLine
|
|
2627
|
+
alternate = [nested]
|
|
2628
|
+
} else {
|
|
2629
|
+
alternate = this.parseBody('else body')
|
|
2630
|
+
}
|
|
2631
|
+
}
|
|
2632
|
+
|
|
2633
|
+
return IfStatement(condition, consequent, alternate)
|
|
2634
|
+
}
|
|
2635
|
+
|
|
2636
|
+
parseWhileStatement() {
|
|
2637
|
+
const condition = this.parseCondition()
|
|
2638
|
+
const body = this.parseBody('while body')
|
|
2639
|
+
return WhileStatement(condition, body)
|
|
2640
|
+
}
|
|
2641
|
+
|
|
2642
|
+
parseRepeatStatement() {
|
|
2643
|
+
const count = this.parseCondition()
|
|
2644
|
+
const body = this.parseBody('repeat body')
|
|
2645
|
+
return RepeatStatement(count, body)
|
|
2646
|
+
}
|
|
2647
|
+
|
|
2648
|
+
parseClass(isExpression) {
|
|
2649
|
+
const isAbstract = this.isWord('abstract')
|
|
2650
|
+
if (isAbstract) this.advance()
|
|
2651
|
+
this.advance() // 'class'
|
|
2652
|
+
let name = null
|
|
2653
|
+
if (
|
|
2654
|
+
this.check(TokenType.IDENTIFIER) &&
|
|
2655
|
+
this.peek().value !== 'extends' &&
|
|
2656
|
+
this.peek().value !== 'implements'
|
|
2657
|
+
) {
|
|
2658
|
+
name = this.advance().value
|
|
2659
|
+
}
|
|
2660
|
+
const typeParams = this.parseOptionalTypeParams()
|
|
2661
|
+
let superClass = null
|
|
2662
|
+
let superTypeArgs = null
|
|
2663
|
+
let implementsList = null
|
|
2664
|
+
if (this.isWord('extends')) {
|
|
2665
|
+
this.advance()
|
|
2666
|
+
superClass = this.parseMemberExpression()
|
|
2667
|
+
superTypeArgs = this.tryParseTypeArguments([
|
|
2668
|
+
TokenType.LBRACE,
|
|
2669
|
+
TokenType.IDENTIFIER,
|
|
2670
|
+
])
|
|
2671
|
+
}
|
|
2672
|
+
if (this.isWord('implements')) {
|
|
2673
|
+
this.advance()
|
|
2674
|
+
const list = [this.parseTypeExpression()]
|
|
2675
|
+
while (this.match(TokenType.COMMA)) list.push(this.parseTypeExpression())
|
|
2676
|
+
implementsList = list.join(', ')
|
|
2677
|
+
}
|
|
2678
|
+
this.expect(TokenType.LBRACE, "Expected '{' to start the class body")
|
|
1323
2679
|
const members = []
|
|
1324
2680
|
while (!this.check(TokenType.RBRACE)) {
|
|
1325
|
-
|
|
1326
|
-
|
|
2681
|
+
if (this.match(TokenType.SEMICOLON)) continue
|
|
2682
|
+
members.push(this.parseClassMember())
|
|
2683
|
+
}
|
|
2684
|
+
this.expect(TokenType.RBRACE, "Expected '}' to close the class body")
|
|
2685
|
+
const node = isExpression
|
|
2686
|
+
? ClassExpr(name, superClass, members)
|
|
2687
|
+
: ClassDeclaration(name, superClass, members)
|
|
2688
|
+
if (typeParams) node.typeParams = typeParams
|
|
2689
|
+
if (isAbstract) node.isAbstract = true
|
|
2690
|
+
if (superTypeArgs) node.superTypeArgs = superTypeArgs
|
|
2691
|
+
if (implementsList) node.implementsList = implementsList
|
|
2692
|
+
return node
|
|
2693
|
+
}
|
|
2694
|
+
|
|
2695
|
+
parseClassMember() {
|
|
2696
|
+
const line = this.peek().line
|
|
2697
|
+
|
|
2698
|
+
// static { ... }
|
|
2699
|
+
if (
|
|
2700
|
+
this.peek().type === TokenType.IDENTIFIER &&
|
|
2701
|
+
this.peek().value === 'static' &&
|
|
2702
|
+
this.tokens[this.pos + 1]?.type === TokenType.LBRACE
|
|
2703
|
+
) {
|
|
2704
|
+
this.advance()
|
|
2705
|
+
const body = this.parseBlockStatements('static block')
|
|
2706
|
+
return { kind: 'staticBlock', static: true, body, line }
|
|
2707
|
+
}
|
|
2708
|
+
|
|
2709
|
+
let isStatic = false
|
|
2710
|
+
let isAsync = false
|
|
2711
|
+
let isGenerator = false
|
|
2712
|
+
let isReadonly = false
|
|
2713
|
+
let isOverride = false
|
|
2714
|
+
let isAbstract = false
|
|
2715
|
+
let isDeclare = false
|
|
2716
|
+
let accessibility = null
|
|
2717
|
+
let kind = 'method'
|
|
2718
|
+
|
|
2719
|
+
// Modifiers, in any order: static public private protected readonly
|
|
2720
|
+
// override abstract declare
|
|
2721
|
+
while (true) {
|
|
2722
|
+
if (this.modifierAhead('abstract')) {
|
|
2723
|
+
this.advance()
|
|
2724
|
+
isAbstract = true
|
|
2725
|
+
continue
|
|
2726
|
+
}
|
|
2727
|
+
if (this.modifierAhead('declare')) {
|
|
2728
|
+
this.advance()
|
|
2729
|
+
isDeclare = true
|
|
2730
|
+
continue
|
|
2731
|
+
}
|
|
2732
|
+
if (this.modifierAhead('static')) {
|
|
2733
|
+
this.advance()
|
|
2734
|
+
isStatic = true
|
|
2735
|
+
continue
|
|
2736
|
+
}
|
|
2737
|
+
const t = this.peek()
|
|
2738
|
+
if (
|
|
2739
|
+
t.type === TokenType.IDENTIFIER &&
|
|
2740
|
+
(t.value === 'public' || t.value === 'private' || t.value === 'protected') &&
|
|
2741
|
+
this.modifierAhead(t.value)
|
|
2742
|
+
) {
|
|
2743
|
+
accessibility = this.advance().value
|
|
2744
|
+
continue
|
|
2745
|
+
}
|
|
2746
|
+
if (this.modifierAhead('readonly')) {
|
|
2747
|
+
this.advance()
|
|
2748
|
+
isReadonly = true
|
|
2749
|
+
continue
|
|
2750
|
+
}
|
|
2751
|
+
if (this.modifierAhead('override')) {
|
|
2752
|
+
this.advance()
|
|
2753
|
+
isOverride = true
|
|
2754
|
+
continue
|
|
2755
|
+
}
|
|
2756
|
+
break
|
|
2757
|
+
}
|
|
2758
|
+
|
|
2759
|
+
if (this.modifierAhead('async')) {
|
|
2760
|
+
this.advance()
|
|
2761
|
+
isAsync = true
|
|
2762
|
+
}
|
|
2763
|
+
if (this.match(TokenType.STAR)) {
|
|
2764
|
+
isGenerator = true
|
|
2765
|
+
} else if (!isAsync && (this.modifierAhead('get') || this.modifierAhead('set'))) {
|
|
2766
|
+
kind = this.advance().value
|
|
2767
|
+
}
|
|
2768
|
+
|
|
2769
|
+
let key = null
|
|
2770
|
+
let keyExpr = null
|
|
2771
|
+
let keyKind = 'name'
|
|
2772
|
+
if (this.match(TokenType.LBRACKET)) {
|
|
2773
|
+
keyExpr = this.parseExpression()
|
|
1327
2774
|
this.expect(
|
|
1328
|
-
TokenType.
|
|
1329
|
-
"Expected '
|
|
2775
|
+
TokenType.RBRACKET,
|
|
2776
|
+
"Expected ']' to close a computed class member name",
|
|
1330
2777
|
)
|
|
1331
|
-
|
|
1332
|
-
|
|
2778
|
+
keyKind = 'computed'
|
|
2779
|
+
} else if (this.check(TokenType.STRING)) {
|
|
2780
|
+
key = this.advance().value
|
|
2781
|
+
keyKind = 'string'
|
|
2782
|
+
} else if (this.check(TokenType.NUMBER)) {
|
|
2783
|
+
key = String(this.advance().value)
|
|
2784
|
+
keyKind = 'number'
|
|
2785
|
+
} else {
|
|
2786
|
+
key = this.parseNameToken('Expected a class member name')
|
|
2787
|
+
}
|
|
2788
|
+
|
|
2789
|
+
const typeParams = this.check(TokenType.LT) ? this.parseOptionalTypeParams() : ''
|
|
2790
|
+
|
|
2791
|
+
// Method, accessor or constructor
|
|
2792
|
+
if (this.check(TokenType.LPAREN)) {
|
|
2793
|
+
this.advance()
|
|
2794
|
+
const params = this.parseParamList()
|
|
2795
|
+
let returnType = null
|
|
2796
|
+
if (this.match(TokenType.COLON)) {
|
|
2797
|
+
returnType = this.parseReturnType()
|
|
2798
|
+
}
|
|
2799
|
+
// No `{`: an abstract member or an overload signature. It exists
|
|
2800
|
+
// only for the checker and is dropped from the JS output.
|
|
2801
|
+
let body = null
|
|
2802
|
+
if (this.check(TokenType.LBRACE)) {
|
|
2803
|
+
body = this.withGenerator(isGenerator, () =>
|
|
2804
|
+
this.parseBlockStatements('method body'),
|
|
2805
|
+
)
|
|
2806
|
+
} else {
|
|
2807
|
+
this.endSignature('method body')
|
|
2808
|
+
}
|
|
2809
|
+
const isConstructor =
|
|
2810
|
+
!isStatic && keyKind === 'name' && key === 'constructor' && kind === 'method'
|
|
2811
|
+
return {
|
|
2812
|
+
kind: isConstructor ? 'constructor' : kind,
|
|
2813
|
+
static: isStatic,
|
|
2814
|
+
accessibility,
|
|
2815
|
+
isOverride,
|
|
2816
|
+
isAbstract,
|
|
2817
|
+
typeParams,
|
|
2818
|
+
key,
|
|
2819
|
+
keyExpr,
|
|
2820
|
+
keyKind,
|
|
2821
|
+
isAsync,
|
|
2822
|
+
isGenerator,
|
|
2823
|
+
params,
|
|
2824
|
+
body,
|
|
2825
|
+
returnType,
|
|
2826
|
+
line,
|
|
2827
|
+
}
|
|
2828
|
+
}
|
|
2829
|
+
|
|
2830
|
+
// Field
|
|
2831
|
+
if (kind !== 'method' || isAsync || isGenerator || typeParams) {
|
|
2832
|
+
throw new Error(
|
|
2833
|
+
`Expected '(' after the class member name at line ${this.peek().line}`,
|
|
2834
|
+
)
|
|
2835
|
+
}
|
|
2836
|
+
if (!this.match(TokenType.QUESTION)) {
|
|
2837
|
+
// definite-assignment `x!: T` is accepted and ignored
|
|
2838
|
+
if (this.check(TokenType.NOT) && this.peek().value === '!') this.advance()
|
|
2839
|
+
}
|
|
2840
|
+
const typeAnnotation = this.parseOptionalTypeAnnotation()
|
|
2841
|
+
let value = null
|
|
2842
|
+
if (this.match(TokenType.EQUALS)) {
|
|
2843
|
+
value = this.parseAssignment()
|
|
2844
|
+
}
|
|
2845
|
+
this.match(TokenType.SEMICOLON)
|
|
2846
|
+
return {
|
|
2847
|
+
kind: 'field',
|
|
2848
|
+
static: isStatic,
|
|
2849
|
+
accessibility,
|
|
2850
|
+
isReadonly,
|
|
2851
|
+
isOverride,
|
|
2852
|
+
isAbstract,
|
|
2853
|
+
isDeclare,
|
|
2854
|
+
key,
|
|
2855
|
+
keyExpr,
|
|
2856
|
+
keyKind,
|
|
2857
|
+
typeAnnotation,
|
|
2858
|
+
value,
|
|
2859
|
+
line,
|
|
2860
|
+
}
|
|
2861
|
+
}
|
|
2862
|
+
|
|
2863
|
+
tryParseArrowFunction() {
|
|
2864
|
+
const generic = this.tryParseGenericArrow()
|
|
2865
|
+
if (generic) return generic
|
|
2866
|
+
|
|
2867
|
+
if (this.check(TokenType.ASYNC)) {
|
|
2868
|
+
const next = this.tokens[this.pos + 1]
|
|
2869
|
+
const startsParams =
|
|
2870
|
+
next &&
|
|
2871
|
+
(next.type === TokenType.LPAREN ||
|
|
2872
|
+
next.type === TokenType.IDENTIFIER ||
|
|
2873
|
+
(next.type !== TokenType.ARROW && KEYWORD_TOKEN_TYPES.has(next.type)))
|
|
2874
|
+
if (startsParams) {
|
|
2875
|
+
const savedPos = this.pos
|
|
2876
|
+
this.advance() // consume 'async'
|
|
2877
|
+
const arrow = this.tryParseSyncArrow()
|
|
2878
|
+
if (arrow) return { ...arrow, isAsync: true }
|
|
2879
|
+
this.pos = savedPos
|
|
2880
|
+
return null
|
|
2881
|
+
}
|
|
2882
|
+
}
|
|
2883
|
+
return this.tryParseSyncArrow()
|
|
2884
|
+
}
|
|
2885
|
+
|
|
2886
|
+
// `<T>(x: T) => x` and `async <T>(x: T) => x`
|
|
2887
|
+
tryParseGenericArrow() {
|
|
2888
|
+
const savedPos = this.pos
|
|
2889
|
+
let isAsync = false
|
|
2890
|
+
if (this.check(TokenType.ASYNC) && this.tokens[this.pos + 1]?.type === TokenType.LT) {
|
|
2891
|
+
this.advance()
|
|
2892
|
+
isAsync = true
|
|
2893
|
+
}
|
|
2894
|
+
if (!this.check(TokenType.LT)) {
|
|
2895
|
+
this.pos = savedPos
|
|
2896
|
+
return null
|
|
2897
|
+
}
|
|
2898
|
+
let typeParams
|
|
2899
|
+
try {
|
|
2900
|
+
typeParams = this.parseOptionalTypeParams()
|
|
2901
|
+
} catch {
|
|
2902
|
+
this.pos = savedPos
|
|
2903
|
+
return null
|
|
2904
|
+
}
|
|
2905
|
+
if (!this.check(TokenType.LPAREN)) {
|
|
2906
|
+
this.pos = savedPos
|
|
2907
|
+
return null
|
|
2908
|
+
}
|
|
2909
|
+
const arrow = this.tryParseSyncArrow()
|
|
2910
|
+
if (!arrow) {
|
|
2911
|
+
this.pos = savedPos
|
|
2912
|
+
return null
|
|
2913
|
+
}
|
|
2914
|
+
return { ...arrow, isAsync, typeParams }
|
|
2915
|
+
}
|
|
2916
|
+
|
|
2917
|
+
parseTypeExpression() {
|
|
2918
|
+
const left = this.parseUnionType()
|
|
2919
|
+
// Conditional type: `T extends U ? X : Y`
|
|
2920
|
+
if (this.isWord('extends')) {
|
|
2921
|
+
this.advance()
|
|
2922
|
+
const constraint = this.parseUnionType()
|
|
2923
|
+
this.expect(TokenType.QUESTION, "Expected '?' in conditional type")
|
|
2924
|
+
const whenTrue = this.parseTypeExpression()
|
|
2925
|
+
this.expect(TokenType.COLON, "Expected ':' in conditional type")
|
|
2926
|
+
const whenFalse = this.parseTypeExpression()
|
|
2927
|
+
return `${left} extends ${constraint} ? ${whenTrue} : ${whenFalse}`
|
|
2928
|
+
}
|
|
2929
|
+
return left
|
|
2930
|
+
}
|
|
2931
|
+
|
|
2932
|
+
parseUnionType() {
|
|
2933
|
+
this.match(TokenType.PIPE) // leading "|" of a multi-line union
|
|
2934
|
+
let left = this.parseIntersectionType()
|
|
2935
|
+
while (this.match(TokenType.PIPE)) {
|
|
2936
|
+
left = `${left} | ${this.parseIntersectionType()}`
|
|
2937
|
+
}
|
|
2938
|
+
return left
|
|
2939
|
+
}
|
|
2940
|
+
|
|
2941
|
+
tryParseFunctionType() {
|
|
2942
|
+
const savedPos = this.pos
|
|
2943
|
+
try {
|
|
2944
|
+
const typeParams = this.parseOptionalTypeParams()
|
|
2945
|
+
const params = this.parseTypeParamList()
|
|
2946
|
+
this.expect(TokenType.ARROW, "Expected '=>' in function type")
|
|
2947
|
+
const returnType = this.parseReturnType()
|
|
2948
|
+
return `${typeParams}(${params}) => ${returnType}`
|
|
2949
|
+
} catch {
|
|
2950
|
+
this.pos = savedPos
|
|
2951
|
+
return null
|
|
2952
|
+
}
|
|
2953
|
+
}
|
|
2954
|
+
|
|
2955
|
+
parseTupleType() {
|
|
2956
|
+
this.expect(TokenType.LBRACKET, "Expected '[' to start a tuple type")
|
|
2957
|
+
const members = []
|
|
2958
|
+
while (!this.check(TokenType.RBRACKET)) {
|
|
2959
|
+
const rest = this.match(TokenType.SPREAD)
|
|
2960
|
+
const t = this.peek()
|
|
2961
|
+
const n = this.tokens[this.pos + 1]
|
|
2962
|
+
const n2 = this.tokens[this.pos + 2]
|
|
2963
|
+
const isLabel =
|
|
2964
|
+
this.isNameToken(t) &&
|
|
2965
|
+
n &&
|
|
2966
|
+
(n.type === TokenType.COLON ||
|
|
2967
|
+
(n.type === TokenType.QUESTION && n2?.type === TokenType.COLON))
|
|
2968
|
+
let member
|
|
2969
|
+
if (isLabel) {
|
|
2970
|
+
const label = this.advance().value
|
|
2971
|
+
const optional = this.match(TokenType.QUESTION)
|
|
2972
|
+
this.expect(TokenType.COLON, "Expected ':' after tuple member name")
|
|
2973
|
+
member = `${label}${optional ? '?' : ''}: ${this.parseTypeExpression()}`
|
|
2974
|
+
} else {
|
|
2975
|
+
member = this.parseTypeExpression()
|
|
2976
|
+
if (this.match(TokenType.QUESTION)) member += '?'
|
|
2977
|
+
}
|
|
2978
|
+
members.push(`${rest ? '...' : ''}${member}`)
|
|
2979
|
+
if (!this.match(TokenType.COMMA)) break
|
|
2980
|
+
}
|
|
2981
|
+
this.expect(TokenType.RBRACKET, "Expected ']' to close a tuple type")
|
|
2982
|
+
return `[${members.join(', ')}]`
|
|
2983
|
+
}
|
|
2984
|
+
|
|
2985
|
+
parseObjectTypeLiteral() {
|
|
2986
|
+
this.expect(TokenType.LBRACE, "Expected '{' to start object type")
|
|
2987
|
+
const members = []
|
|
2988
|
+
while (!this.check(TokenType.RBRACE)) {
|
|
2989
|
+
let prefix = ''
|
|
2990
|
+
const sign = this.peek()
|
|
2991
|
+
if (
|
|
2992
|
+
(sign.type === TokenType.MINUS || sign.type === TokenType.PLUS) &&
|
|
2993
|
+
this.tokens[this.pos + 1]?.value === 'readonly'
|
|
2994
|
+
) {
|
|
2995
|
+
this.advance()
|
|
2996
|
+
this.advance()
|
|
2997
|
+
prefix = `${sign.value}readonly `
|
|
2998
|
+
} else if (this.modifierAhead('readonly')) {
|
|
2999
|
+
this.advance()
|
|
3000
|
+
prefix = 'readonly '
|
|
3001
|
+
}
|
|
3002
|
+
|
|
3003
|
+
if (this.check(TokenType.LBRACKET)) {
|
|
3004
|
+
this.advance()
|
|
3005
|
+
const keyName = this.parseNameToken('Expected an index signature name')
|
|
3006
|
+
if (this.match(TokenType.IN)) {
|
|
3007
|
+
// mapped type: [K in keyof T as X]?: V
|
|
3008
|
+
const constraint = this.parseTypeExpression()
|
|
3009
|
+
let asClause = ''
|
|
3010
|
+
if (this.isWord('as')) {
|
|
3011
|
+
this.advance()
|
|
3012
|
+
asClause = ` as ${this.parseTypeExpression()}`
|
|
3013
|
+
}
|
|
3014
|
+
this.expect(TokenType.RBRACKET, "Expected ']' to close mapped type key")
|
|
3015
|
+
let mod = ''
|
|
3016
|
+
if (this.check(TokenType.MINUS) || this.check(TokenType.PLUS)) {
|
|
3017
|
+
mod = this.advance().value
|
|
3018
|
+
this.expect(TokenType.QUESTION, "Expected '?' after '+'/'-'")
|
|
3019
|
+
mod += '?'
|
|
3020
|
+
} else if (this.match(TokenType.QUESTION)) {
|
|
3021
|
+
mod = '?'
|
|
3022
|
+
}
|
|
3023
|
+
this.expect(TokenType.COLON, "Expected ':' in mapped type")
|
|
3024
|
+
const valueType = this.parseTypeExpression()
|
|
3025
|
+
members.push(
|
|
3026
|
+
`${prefix}[${keyName} in ${constraint}${asClause}]${mod}: ${valueType}`,
|
|
3027
|
+
)
|
|
3028
|
+
} else {
|
|
3029
|
+
// index signature: [key: string]: T
|
|
3030
|
+
this.expect(TokenType.COLON, "Expected ':' in index signature")
|
|
3031
|
+
const keyType = this.parseTypeExpression()
|
|
3032
|
+
this.expect(TokenType.RBRACKET, "Expected ']' to close index signature")
|
|
3033
|
+
this.expect(TokenType.COLON, "Expected ':' after index signature")
|
|
3034
|
+
const valueType = this.parseTypeExpression()
|
|
3035
|
+
members.push(`${prefix}[${keyName}: ${keyType}]: ${valueType}`)
|
|
3036
|
+
}
|
|
3037
|
+
} else {
|
|
3038
|
+
const key = this.check(TokenType.STRING)
|
|
3039
|
+
? JSON.stringify(this.advance().value)
|
|
3040
|
+
: this.parseNameToken('Expected a property name')
|
|
3041
|
+
const optional = this.match(TokenType.QUESTION)
|
|
3042
|
+
|
|
3043
|
+
if (this.check(TokenType.LPAREN) || this.check(TokenType.LT)) {
|
|
3044
|
+
// method signature: name<T>(a: T): R
|
|
3045
|
+
const generics = this.parseOptionalTypeParams()
|
|
3046
|
+
const params = this.parseTypeParamList()
|
|
3047
|
+
let returnType = 'any'
|
|
3048
|
+
if (this.match(TokenType.COLON)) {
|
|
3049
|
+
returnType = this.parseReturnType()
|
|
3050
|
+
}
|
|
3051
|
+
members.push(
|
|
3052
|
+
`${prefix}${key}${optional ? '?' : ''}${generics}(${params}): ${returnType}`,
|
|
3053
|
+
)
|
|
3054
|
+
} else {
|
|
3055
|
+
this.expect(
|
|
3056
|
+
TokenType.COLON,
|
|
3057
|
+
"Expected ':' after property name in object type",
|
|
3058
|
+
)
|
|
3059
|
+
const valueType = this.parseTypeExpression()
|
|
3060
|
+
members.push(`${prefix}${key}${optional ? '?' : ''}: ${valueType}`)
|
|
3061
|
+
}
|
|
3062
|
+
}
|
|
1333
3063
|
if (!this.match(TokenType.COMMA)) this.match(TokenType.SEMICOLON)
|
|
1334
3064
|
}
|
|
1335
3065
|
this.expect(TokenType.RBRACE, "Expected '}' to close object type")
|
|
1336
3066
|
return `{ ${members.join('; ')} }`
|
|
1337
3067
|
}
|
|
1338
|
-
|
|
3068
|
+
|
|
3069
|
+
// Array literal after the opening '['. A comma with nothing before
|
|
3070
|
+
// it is a hole (`[1, , 3]`), stored as `null` in `elements`.
|
|
1339
3071
|
parseArrayLiteral() {
|
|
1340
3072
|
const elements = []
|
|
1341
3073
|
while (!this.check(TokenType.RBRACKET)) {
|
|
3074
|
+
if (this.check(TokenType.COMMA)) {
|
|
3075
|
+
elements.push(null)
|
|
3076
|
+
this.advance()
|
|
3077
|
+
continue
|
|
3078
|
+
}
|
|
1342
3079
|
if (this.match(TokenType.SPREAD)) {
|
|
1343
3080
|
elements.push(SpreadElement(this.parseExpression()))
|
|
1344
3081
|
} else {
|
|
@@ -1350,12 +3087,21 @@ export class Parser {
|
|
|
1350
3087
|
return ArrayExpr(elements)
|
|
1351
3088
|
}
|
|
1352
3089
|
|
|
3090
|
+
// Object literal after the opening '{'. Supports:
|
|
3091
|
+
// { a: 1, "b-c": 2, 3: 'x' } plain / string / number keys
|
|
3092
|
+
// { name } shorthand
|
|
3093
|
+
// { ...base } spread
|
|
3094
|
+
// { [expr]: value } computed keys
|
|
3095
|
+
// { save(x) { ... } } method shorthand
|
|
3096
|
+
// { async load() { ... } } async method shorthand
|
|
3097
|
+
// { *items() { ... } } generator method (also async *)
|
|
3098
|
+
// { get total() { ... } } getter
|
|
3099
|
+
// { set total(v) { ... } } setter
|
|
1353
3100
|
parseObjectLiteral() {
|
|
1354
3101
|
const properties = []
|
|
1355
3102
|
while (!this.check(TokenType.RBRACE)) {
|
|
1356
|
-
// Object spread:
|
|
1357
|
-
//
|
|
1358
|
-
// `p.spread` before reading `p.key`.
|
|
3103
|
+
// Object spread: represented as a property with `spread: true`
|
|
3104
|
+
// and no key, so codegen must check `p.spread` first.
|
|
1359
3105
|
if (this.match(TokenType.SPREAD)) {
|
|
1360
3106
|
properties.push({
|
|
1361
3107
|
key: null,
|
|
@@ -1366,25 +3112,130 @@ export class Parser {
|
|
|
1366
3112
|
continue
|
|
1367
3113
|
}
|
|
1368
3114
|
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
3115
|
+
// `get name() {}` / `set name(v) {}`. `{ get }`, `{ get: 1 }`,
|
|
3116
|
+
// `{ get, set }` and `get() {}` stay ordinary keys/methods.
|
|
3117
|
+
let accessorKind = null
|
|
3118
|
+
if (
|
|
3119
|
+
this.check(TokenType.IDENTIFIER) &&
|
|
3120
|
+
(this.peek().value === 'get' || this.peek().value === 'set')
|
|
3121
|
+
) {
|
|
3122
|
+
const word = this.peek()
|
|
3123
|
+
const n = this.tokens[this.pos + 1]
|
|
3124
|
+
if (
|
|
3125
|
+
n &&
|
|
3126
|
+
n.line === word.line &&
|
|
3127
|
+
(n.type === TokenType.IDENTIFIER ||
|
|
3128
|
+
KEYWORD_TOKEN_TYPES.has(n.type) ||
|
|
3129
|
+
n.type === TokenType.STRING ||
|
|
3130
|
+
n.type === TokenType.NUMBER ||
|
|
3131
|
+
n.type === TokenType.LBRACKET)
|
|
3132
|
+
) {
|
|
3133
|
+
accessorKind = word.value
|
|
3134
|
+
this.advance()
|
|
3135
|
+
}
|
|
3136
|
+
}
|
|
3137
|
+
|
|
3138
|
+
// `async name(...) { }` -- but `async: x`, `async,` and `async()`
|
|
3139
|
+
// are ordinary keys/methods named "async".
|
|
3140
|
+
let isAsync = false
|
|
3141
|
+
if (!accessorKind && this.check(TokenType.ASYNC)) {
|
|
3142
|
+
const n = this.tokens[this.pos + 1]
|
|
3143
|
+
if (
|
|
3144
|
+
n &&
|
|
3145
|
+
n.type !== TokenType.COLON &&
|
|
3146
|
+
n.type !== TokenType.COMMA &&
|
|
3147
|
+
n.type !== TokenType.RBRACE &&
|
|
3148
|
+
n.type !== TokenType.LPAREN
|
|
3149
|
+
) {
|
|
3150
|
+
this.advance()
|
|
3151
|
+
isAsync = true
|
|
3152
|
+
}
|
|
3153
|
+
}
|
|
3154
|
+
|
|
3155
|
+
// `*name() { }` generator method
|
|
3156
|
+
let isGenerator = false
|
|
3157
|
+
if (!accessorKind && this.match(TokenType.STAR)) {
|
|
3158
|
+
isGenerator = true
|
|
3159
|
+
}
|
|
3160
|
+
|
|
3161
|
+
let key = null
|
|
3162
|
+
let keyExpr = null
|
|
3163
|
+
let keyKind = 'name'
|
|
3164
|
+
if (this.match(TokenType.LBRACKET)) {
|
|
3165
|
+
keyExpr = this.parseExpression()
|
|
3166
|
+
this.expect(
|
|
3167
|
+
TokenType.RBRACKET,
|
|
3168
|
+
"Expected ']' to close a computed object key",
|
|
3169
|
+
)
|
|
3170
|
+
keyKind = 'computed'
|
|
3171
|
+
} else if (this.check(TokenType.STRING)) {
|
|
3172
|
+
key = this.advance().value
|
|
3173
|
+
keyKind = 'string'
|
|
3174
|
+
} else if (this.check(TokenType.NUMBER)) {
|
|
3175
|
+
key = String(this.advance().value)
|
|
3176
|
+
keyKind = 'number'
|
|
3177
|
+
} else if (
|
|
3178
|
+
this.check(TokenType.IDENTIFIER) ||
|
|
3179
|
+
KEYWORD_TOKEN_TYPES.has(this.peek().type)
|
|
3180
|
+
) {
|
|
3181
|
+
key = this.advance().value
|
|
3182
|
+
} else {
|
|
3183
|
+
throw new Error(
|
|
3184
|
+
`Expected an object key at line ${this.peek().line}, got ${this.peek().type}`,
|
|
3185
|
+
)
|
|
3186
|
+
}
|
|
3187
|
+
|
|
3188
|
+
// Method shorthand / accessor
|
|
3189
|
+
const methodTypeParams = this.check(TokenType.LT)
|
|
3190
|
+
? this.parseOptionalTypeParams()
|
|
3191
|
+
: ''
|
|
3192
|
+
if (this.check(TokenType.LPAREN)) {
|
|
3193
|
+
this.advance()
|
|
3194
|
+
const params = this.parseParamList()
|
|
3195
|
+
const returnType = this.match(TokenType.COLON) ? this.parseReturnType() : null
|
|
3196
|
+
const body = this.withGenerator(isGenerator, () =>
|
|
3197
|
+
this.parseBlockStatements('method body'),
|
|
3198
|
+
)
|
|
3199
|
+
properties.push({
|
|
3200
|
+
key,
|
|
3201
|
+
keyExpr,
|
|
3202
|
+
method: true,
|
|
3203
|
+
kind: accessorKind ?? 'method',
|
|
3204
|
+
value: {
|
|
3205
|
+
...FunctionExpr(params, body, isAsync, null, isGenerator),
|
|
3206
|
+
...signatureExtras({ typeParams: methodTypeParams, returnType }),
|
|
3207
|
+
},
|
|
3208
|
+
})
|
|
3209
|
+
this.match(TokenType.COMMA)
|
|
3210
|
+
continue
|
|
3211
|
+
}
|
|
3212
|
+
|
|
3213
|
+
if (isAsync || isGenerator || accessorKind) {
|
|
3214
|
+
throw new Error(
|
|
3215
|
+
`Expected '(' after the method name at line ${this.peek().line}`,
|
|
3216
|
+
)
|
|
3217
|
+
}
|
|
1377
3218
|
|
|
1378
|
-
if (
|
|
1379
|
-
|
|
1380
|
-
|
|
3219
|
+
if (keyKind === 'name' && !this.check(TokenType.COLON)) {
|
|
3220
|
+
// Shorthand: { name } means { name: name }. `{ name = 1 }` is only
|
|
3221
|
+
// valid as a destructuring assignment target; see generateExpression.
|
|
3222
|
+
if (this.match(TokenType.EQUALS)) {
|
|
3223
|
+
const fallback = this.parseAssignment()
|
|
3224
|
+
properties.push({
|
|
3225
|
+
key,
|
|
3226
|
+
shorthandInit: true,
|
|
3227
|
+
value: AssignmentExpr(Identifier(key), fallback),
|
|
3228
|
+
})
|
|
3229
|
+
} else {
|
|
3230
|
+
properties.push({ key, value: Identifier(key) })
|
|
3231
|
+
}
|
|
1381
3232
|
this.match(TokenType.COMMA)
|
|
1382
3233
|
continue
|
|
1383
3234
|
}
|
|
1384
3235
|
|
|
1385
3236
|
this.expect(TokenType.COLON, "Expected ':' after object key")
|
|
1386
3237
|
const value = this.parseExpression()
|
|
1387
|
-
properties.push({ key, value })
|
|
3238
|
+
properties.push({ key, keyExpr, value })
|
|
1388
3239
|
this.match(TokenType.COMMA)
|
|
1389
3240
|
}
|
|
1390
3241
|
this.expect(TokenType.RBRACE, "Expected '}' to close object literal")
|