@tylix/compiler 0.6.0 → 1.0.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.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +30 -2
  3. package/src/ast/nodes.js +145 -23
  4. package/src/ast/substituteCapabilityRefs.js +52 -5
  5. package/src/codegen/emitStatementLines.js +60 -10
  6. package/src/codegen/generateExpression.js +294 -35
  7. package/src/codegen/generateStatement.js +125 -20
  8. package/src/codegen/generateTemplate.js +107 -96
  9. package/src/codegen/generateTemplateExpression.js +63 -10
  10. package/src/codegen/jsGlobals.js +62 -2
  11. package/src/compileComponent.js +37 -6
  12. package/src/lexer/Lexer.js +128 -28
  13. package/src/parser/Parser.js +1840 -500
  14. package/src/parser/parseExpressionString.js +5 -0
  15. package/src/parser/parseTemplate.js +153 -41
  16. package/src/renderPageDocument.js +71 -8
  17. package/src/runtime/capability.js +8 -1
  18. package/src/runtime/reactive.js +289 -61
  19. package/src/runtime/useApi.js +74 -13
  20. package/src/runtime/useChannel.js +27 -6
  21. package/src/typecheck/buildVirtualTs.js +11 -1
  22. package/src/typecheck/tylix-globals.d.ts +23 -4
  23. package/src/typecheck/typedTemplateExpr.js +90 -27
  24. package/src/codegen/generateExpression.array.test.js +0 -13
  25. package/src/codegen/generateExpression.callexpr.test.js +0 -19
  26. package/src/codegen/generateExpression.test.js +0 -59
  27. package/src/codegen/generateMethod.asyncawait.test.js +0 -37
  28. package/src/codegen/generateMethod.ifstatement.test.js +0 -20
  29. package/src/codegen/generateMethod.test.js +0 -81
  30. package/src/codegen/generatePage.onmount.test.js +0 -46
  31. package/src/codegen/generatePage.test.js +0 -138
  32. package/src/codegen/generateStatement.test.js +0 -31
  33. package/src/codegen/generateTemplate.ifeach.test.js +0 -138
  34. package/src/codegen/generateTemplate.test.js +0 -149
  35. package/src/codegen/generateTemplateExpression.test.js +0 -34
  36. package/src/compileComponent.test.js +0 -121
  37. package/src/lexer/Lexer.test.js +0 -151
  38. package/src/parser/Parser.array.test.js +0 -37
  39. package/src/parser/Parser.asyncawait.test.js +0 -33
  40. package/src/parser/Parser.ifstatement.test.js +0 -20
  41. package/src/parser/Parser.onmount.test.js +0 -18
  42. package/src/parser/Parser.test.js +0 -315
  43. package/src/parser/parseComponent.test.js +0 -53
  44. package/src/parser/parsePageFile.test.js +0 -101
  45. package/src/parser/parseTemplate.ifeach.test.js +0 -33
  46. package/src/parser/parseTemplate.pre.test.js +0 -39
  47. package/src/parser/parseTemplate.test.js +0 -112
  48. package/src/renderPageDocument.test.js +0 -125
  49. package/src/runtime/reactive.test.js +0 -106
  50. package/test/dashboard-syntax.test.js +0 -116
@@ -7,13 +7,19 @@ 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,
13
16
  FunctionExpr,
14
17
  FunctionDeclaration,
15
18
  TemplateLiteralExpr,
19
+ TaggedTemplateExpr,
16
20
  SpreadElement,
21
+ SequenceExpr,
22
+ YieldExpr,
17
23
  Identifier,
18
24
  MemberExpr,
19
25
  Literal,
@@ -23,6 +29,8 @@ import {
23
29
  CallExpr,
24
30
  NewExpr,
25
31
  AwaitExpr,
32
+ AsExpr,
33
+ NonNullExpr,
26
34
  VariableDeclaration,
27
35
  ObjectExpr,
28
36
  ArrayExpr,
@@ -37,6 +45,10 @@ import {
37
45
  RepeatStatement,
38
46
  BreakStatement,
39
47
  ContinueStatement,
48
+ LabeledStatement,
49
+ DebuggerStatement,
50
+ ClassDeclaration,
51
+ ClassExpr,
40
52
  CapabilityRefNode,
41
53
  MetaEntryNode,
42
54
  BlockStatement,
@@ -46,6 +58,7 @@ import {
46
58
  SwitchStatement,
47
59
  } from '../ast/nodes.js'
48
60
  import { parseExpressionString } from './parseExpressionString.js'
61
+ import { generateExpression } from '../codegen/generateExpression.js'
49
62
 
50
63
  const COMPARISON_SYMBOLS = {
51
64
  [TokenType.GT]: '>',
@@ -94,46 +107,117 @@ const COMPOUND_ASSIGNMENT_OPS = {
94
107
  // and emitted verbatim by the codegen.
95
108
  function bindingToSource(t) {
96
109
  if (typeof t === 'string') return t
110
+ const withDefault = (src, def) =>
111
+ def ? `${src} = ${generateExpression(def)}` : src
97
112
  if (t.type === 'ObjectPattern') {
98
113
  const parts = t.properties.map((p) => {
99
- if (p.defaultValue) {
100
- throw new Error(
101
- 'Default values inside destructured parameters are not supported; use a default on the whole parameter or a const inside the body',
102
- )
103
- }
104
- return typeof p.binding === 'string' && p.binding === p.key
105
- ? p.key
106
- : `${p.key}: ${bindingToSource(p.binding)}`
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)
107
117
  })
108
118
  if (t.rest) parts.push(`...${t.rest}`)
109
119
  return `{ ${parts.join(', ')} }`
110
120
  }
111
- const parts = t.elements.map((el) => {
112
- if (el === null) return ''
113
- if (el.defaultValue) {
114
- throw new Error(
115
- 'Default values inside destructured parameters are not supported; use a default on the whole parameter or a const inside the body',
116
- )
117
- }
118
- return bindingToSource(el.binding)
119
- })
121
+ const parts = t.elements.map((el) =>
122
+ el === null ? '' : withDefault(bindingToSource(el.binding), el.defaultValue),
123
+ )
120
124
  if (t.rest) parts.push(`...${t.rest}`)
121
125
  return `[${parts.join(', ')}]`
122
126
  }
123
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
+
124
150
  // True when token `b` starts exactly where token `a` ends -- i.e. the
125
151
  // two were written with no whitespace between them.
126
152
  function adjacent(a, b) {
127
153
  return !!a && !!b && b.start === a.start + String(a.value).length
128
154
  }
129
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])
210
+ }
211
+
130
212
  /**
131
213
  * Parses the token stream from the Lexer into a Page AST.
132
214
  *
133
215
  * Expressions are parsed with real precedence-climbing, low to high:
134
216
  * arrow function (x => expr, (a, b = 1) => expr, destructured and
135
- * rest params, block bodies x => { ... }, and the async forms of
136
- * all of these) -- tried first, with backtracking
217
+ * rest params, optional params, return types, block bodies
218
+ * x => { ... }, and the async forms of all of these) -- tried
219
+ * first, with backtracking
220
+ * yield / yield* (inside generators)
137
221
  * assignment (= += -= *= /= %= **= ??= ||= &&= &= |= ^= <<= >>= >>>=)
138
222
  * ternary (?:)
139
223
  * nullish (??)
@@ -143,17 +227,18 @@ function adjacent(a, b) {
143
227
  * bitwise xor (^)
144
228
  * bitwise and (&)
145
229
  * equality (is / is not, also ===, !==, ==, !=)
146
- * comparison (> < >= <= instanceof in)
230
+ * comparison (> < >= <= instanceof in, and the `as` / `satisfies` casts)
147
231
  * predicate (has / exists / missing)
148
232
  * shift (<< >> >>>)
149
233
  * additive (+ -)
150
234
  * multiplicative (* / %)
151
235
  * exponent (**, right-associative)
152
- * unary (not, !, ~, -, await, typeof, delete, void, prefix ++/--)
236
+ * unary (not, !, ~, -, +, await, typeof, delete, void, prefix ++/--)
153
237
  * postfix (x++, x--)
154
- * member/call (a.b, a(), a?.b, a?.())
155
- * primary (literals, regex, bigint, identifiers, grouping, arrays,
156
- * objects, template literals, function expressions)
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)
157
242
  *
158
243
  * `x++` / `++x` desugar to `x = x + 1` (same trick as compound
159
244
  * assignment), so the expression's value is the NEW value in both
@@ -162,14 +247,31 @@ function adjacent(a, b) {
162
247
  * Shifts are recombined from adjacent LT/GT tokens (see
163
248
  * shiftOperatorAt) because the Lexer never emits << or >> as single
164
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.
165
254
  */
166
255
  export class Parser {
167
256
  constructor(tokens, options = {}) {
168
- this.tokens = tokens
169
- this.pos = 0
170
- this.options = options
171
- this.looseNot = options.not === 'loose'
172
- }
257
+ this.tokens = tokens
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
+ }
274
+ }
173
275
 
174
276
  parse() {
175
277
  const page = {
@@ -178,6 +280,7 @@ export class Parser {
178
280
  computed: [],
179
281
  actions: [],
180
282
  uses: [],
283
+ helpers: [],
181
284
  onMount: null,
182
285
  }
183
286
 
@@ -220,6 +323,8 @@ export class Parser {
220
323
  )
221
324
  } else if (this.match(TokenType.META)) {
222
325
  page.meta = this.parseSectionBlock(this.parseMetaEntry.bind(this))
326
+ } else if (this.isModuleDeclarationAhead()) {
327
+ page.helpers.push(this.parseStatement())
223
328
  } else {
224
329
  throw new Error(
225
330
  `Unexpected token ${this.peek().type} at line ${this.peek().line}`,
@@ -295,9 +400,10 @@ export class Parser {
295
400
  )
296
401
  }
297
402
 
298
- isAtSectionBoundary() {
403
+ isAtSectionBoundary(allowDeclarations = false) {
299
404
  const type = this.peek().type
300
405
  if (this.isSectionKeyword(type)) return true
406
+ if (allowDeclarations && this.isModuleDeclarationAhead()) return true
301
407
  if (this.isAmbiguousSectionKeyword(type)) {
302
408
  const next = this.tokens[this.pos + 1]
303
409
  // Followed by ':' or '(' means it's a field/prop/method name in
@@ -313,7 +419,7 @@ export class Parser {
313
419
 
314
420
  parseBareBlock(parseEntry) {
315
421
  const entries = []
316
- while (!this.isAtSectionBoundary()) {
422
+ while (!this.isAtSectionBoundary(true)) {
317
423
  entries.push(parseEntry())
318
424
  this.match(TokenType.COMMA)
319
425
  }
@@ -421,27 +527,50 @@ export class Parser {
421
527
  }
422
528
 
423
529
  this.expect(TokenType.COLON, "Expected ':' after state name")
424
- if (this.match(TokenType.MINUS)) {
425
- const num = this.expect(
426
- TokenType.NUMBER,
427
- "Expected a number after '-'",
428
- ).value
429
- return {
430
- ...StateNode(name, Literal(-num), typeAnnotation),
431
- line: startLine,
432
- }
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)
433
546
  }
434
- const value = this.parsePrimary()
547
+
435
548
  return { ...StateNode(name, value, typeAnnotation), line: startLine }
436
549
  }
437
550
 
438
551
  // Parses a parameter list. The opening '(' must already be
439
552
  // consumed; this consumes the closing ')'. Supports types
440
- // (`a: number`), defaults (`a = 1`), rest (`...args`) and
441
- // destructured params (`{ id, name }`, `[a, b]`).
553
+ // (`a: number`), optional (`a?: number`), defaults (`a = 1`), rest
554
+ // (`...args`) and destructured params (`{ id, name }`, `[a, b]`).
442
555
  parseParamList() {
443
556
  const params = []
444
557
  while (!this.check(TokenType.RPAREN)) {
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
+ }
445
574
  const rest = this.match(TokenType.SPREAD)
446
575
  let name
447
576
  if (this.check(TokenType.LBRACE) || this.check(TokenType.LBRACKET)) {
@@ -449,6 +578,7 @@ export class Parser {
449
578
  } else {
450
579
  name = this.parseNameToken('Expected parameter name')
451
580
  }
581
+ const optional = this.match(TokenType.QUESTION)
452
582
  let typeAnnotation = null
453
583
  if (this.match(TokenType.COLON)) {
454
584
  typeAnnotation = this.parseTypeExpression()
@@ -457,46 +587,25 @@ export class Parser {
457
587
  if (this.match(TokenType.EQUALS)) {
458
588
  defaultValue = this.parseAssignment()
459
589
  }
460
- params.push({ name, typeAnnotation, defaultValue, rest })
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)
461
595
  this.match(TokenType.COMMA)
462
596
  }
463
597
  this.expect(TokenType.RPAREN, "Expected ')' after parameters")
464
598
  return params
465
599
  }
466
600
 
467
- parseMethod() {
468
- const startLine = this.peek().line
469
- const isAsync = this.match(TokenType.ASYNC)
470
- const name = this.parseNameToken('Expected method name')
471
- this.expect(TokenType.LPAREN, "Expected '(' after method name")
472
-
473
- const params = this.parseParamList()
474
-
475
- let returnType = null
476
- if (this.match(TokenType.COLON)) {
477
- returnType = this.parseTypeExpression()
478
- }
479
-
480
- this.expect(TokenType.LBRACE, "Expected '{' to start method body")
481
- const body = []
482
- while (!this.check(TokenType.RBRACE)) {
483
- body.push(this.parseStatement())
484
- }
485
- this.expect(TokenType.RBRACE, "Expected '}' to close method body")
486
601
 
487
- return {
488
- ...MethodNode(name, params, body, returnType),
489
- isAsync,
490
- line: startLine,
491
- }
492
- }
493
602
 
494
603
  // A binding target is anywhere a name is bound to a value: a plain
495
604
  // identifier, or -- for destructuring -- a nested object/array
496
605
  // pattern. Shared by top-level const/let targets, object pattern
497
- // property values, and array pattern elements, so `const { a: { b } }
498
- // = x` and `const [[a, b]] = x` both fall out for free instead of
499
- // needing separate one-level-deep parsing logic in three places.
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.
500
609
  parseBindingTarget() {
501
610
  if (this.check(TokenType.LBRACE)) return this.parseObjectPattern()
502
611
  if (this.check(TokenType.LBRACKET)) return this.parseArrayPattern()
@@ -642,23 +751,7 @@ export class Parser {
642
751
  return body
643
752
  }
644
753
 
645
- // After `function` (and an optional preceding `async`, already
646
- // consumed by the caller): `[name] (params) [: ReturnType] { body }`.
647
- parseFunctionRest(isAsync) {
648
- this.expect(TokenType.FUNCTION, "Expected 'function'")
649
- let name = null
650
- if (!this.check(TokenType.LPAREN)) {
651
- name = this.parseNameToken('Expected a function name')
652
- }
653
- this.expect(TokenType.LPAREN, "Expected '(' after function name")
654
- const params = this.parseParamList()
655
- if (this.match(TokenType.COLON)) {
656
- this.parseTypeExpression() // return type: checked only in the virtual .ts
657
- }
658
- const body = this.parseBlockStatements('function body')
659
- return { name, params, body, isAsync }
660
- }
661
-
754
+
662
755
  isFunctionKeywordAhead() {
663
756
  return (
664
757
  this.check(TokenType.FUNCTION) ||
@@ -667,98 +760,120 @@ export class Parser {
667
760
  )
668
761
  }
669
762
 
670
- parseStatementInner() {
671
- if (this.match(TokenType.SEMICOLON)) {
672
- return EmptyStatement()
673
- }
674
-
675
- if (this.match(TokenType.RETURN)) {
676
- const hasValue =
677
- !this.check(TokenType.SEMICOLON) && !this.check(TokenType.RBRACE)
678
- const argument = hasValue ? this.parseExpression() : null
679
- this.match(TokenType.SEMICOLON)
680
- return ReturnStatement(argument)
681
- }
682
-
683
- if (this.match(TokenType.THROW)) {
684
- const argument = this.parseExpression()
685
- this.match(TokenType.SEMICOLON)
686
- return ThrowStatement(argument)
687
- }
688
-
689
- if (this.match(TokenType.IF)) {
690
- return this.parseIfStatement()
691
- }
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
+ }
692
770
 
693
- if (this.match(TokenType.WHILE)) {
694
- return this.parseWhileStatement()
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
695
778
  }
779
+ return null
780
+ }
696
781
 
697
- if (this.match(TokenType.DO)) {
698
- return this.parseDoWhileStatement()
699
- }
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
700
790
 
701
- if (this.match(TokenType.SWITCH)) {
702
- return this.parseSwitchStatement()
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
+ )
703
801
  }
704
802
 
705
- if (this.match(TokenType.FOR)) {
706
- return this.parseForStatement()
707
- }
803
+ if (tok.type !== TokenType.IDENTIFIER) return
708
804
 
709
- if (this.match(TokenType.REPEAT)) {
710
- return this.parseRepeatStatement()
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
+ )
711
814
  }
712
815
 
713
- if (this.match(TokenType.TRY)) {
714
- return this.parseTryStatement()
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
+ )
715
824
  }
716
825
 
717
- if (this.match(TokenType.BREAK)) {
718
- this.match(TokenType.SEMICOLON)
719
- return BreakStatement()
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
+ )
720
830
  }
721
831
 
722
- if (this.match(TokenType.CONTINUE)) {
723
- this.match(TokenType.SEMICOLON)
724
- return ContinueStatement()
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
+ )
725
846
  }
726
847
 
727
- // `function name(...) { }` / `async function name(...) { }` as a
728
- // declaration. An anonymous `function (...) { }` falls through to
729
- // the expression-statement path below.
730
- if (this.isFunctionKeywordAhead()) {
731
- const nameIdx = this.pos + (this.check(TokenType.ASYNC) ? 2 : 1)
732
- const nameTok = this.tokens[nameIdx]
733
- const afterName = this.tokens[nameIdx + 1]
734
- if (
735
- nameTok &&
736
- nameTok.type !== TokenType.LPAREN &&
737
- afterName &&
738
- afterName.type === TokenType.LPAREN
739
- ) {
740
- const isAsync = this.match(TokenType.ASYNC)
741
- const fn = this.parseFunctionRest(isAsync)
742
- return FunctionDeclaration(fn.name, fn.params, fn.body, fn.isAsync)
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})`)
743
861
  }
744
862
  }
863
+ }
745
864
 
746
- if (this.check(TokenType.CONST) || this.check(TokenType.LET)) {
747
- const kind = this.advance().type === TokenType.CONST ? 'const' : 'let'
748
- const decl = this.parseDeclarators(kind)
749
- this.match(TokenType.SEMICOLON)
750
- return decl
751
- }
865
+
752
866
 
753
- const expression = this.parseExpression()
754
- this.match(TokenType.SEMICOLON)
755
- return ExpressionStatement(expression)
867
+ // `: Type` after a binding name, or null when there is none.
868
+ parseOptionalTypeAnnotation() {
869
+ return this.match(TokenType.COLON) ? this.parseTypeExpression() : null
756
870
  }
757
871
 
758
- // `target [= init] [, target [= init] ...]` after const/let.
759
- // `let x` (no initializer) is allowed; `const x` requires one.
872
+ // `target [: Type] [= init] [, target [: Type] [= init] ...]` after
873
+ // const/let. `let x` (no initializer) is allowed; `const x` requires one.
760
874
  parseDeclarators(kind) {
761
875
  const target = this.parseBindingTarget()
876
+ const typeAnnotation = this.parseOptionalTypeAnnotation()
762
877
  let init = null
763
878
  if (this.match(TokenType.EQUALS)) {
764
879
  init = this.parseExpression()
@@ -770,6 +885,7 @@ export class Parser {
770
885
  const more = []
771
886
  while (this.match(TokenType.COMMA)) {
772
887
  const name = this.parseBindingTarget()
888
+ const moreType = this.parseOptionalTypeAnnotation()
773
889
  let moreInit = null
774
890
  if (this.match(TokenType.EQUALS)) {
775
891
  moreInit = this.parseExpression()
@@ -778,48 +894,12 @@ export class Parser {
778
894
  `Missing initializer in const declaration at line ${this.peek().line}`,
779
895
  )
780
896
  }
781
- more.push({ name, init: moreInit })
782
- }
783
- return VariableDeclaration(kind, target, init, more)
784
- }
785
-
786
- parseIfStatement() {
787
- const condition = this.parseExpression()
788
- this.expect(TokenType.LBRACE, "Expected '{' to start if body")
789
- const consequent = []
790
- while (!this.check(TokenType.RBRACE)) {
791
- consequent.push(this.parseStatement())
792
- }
793
- this.expect(TokenType.RBRACE, "Expected '}' to close if body")
794
-
795
- let alternate = null
796
- if (this.match(TokenType.ELSE)) {
797
- if (this.check(TokenType.IF)) {
798
- const startLine = this.peek().line
799
- this.advance()
800
- const nested = this.parseIfStatement()
801
- nested.line = nested.line ?? startLine
802
- alternate = [nested]
803
- } else {
804
- this.expect(TokenType.LBRACE, "Expected '{' to start else body")
805
- alternate = []
806
- while (!this.check(TokenType.RBRACE)) {
807
- alternate.push(this.parseStatement())
808
- }
809
- this.expect(TokenType.RBRACE, "Expected '}' to close else body")
897
+ more.push({ name, init: moreInit, typeAnnotation: moreType })
810
898
  }
899
+ return VariableDeclaration(kind, target, init, more, typeAnnotation)
811
900
  }
812
901
 
813
- return IfStatement(condition, consequent, alternate)
814
- }
815
- // `while cond { ... }` or `while (cond) { ... }`. Parentheses need no
816
- // special handling: `(cond)` already parses as a grouped expression,
817
- // which also keeps `while (a) and (b) { ... }` working.
818
- parseWhileStatement() {
819
- const condition = this.parseExpression()
820
- const body = this.parseBlockStatements('while body')
821
- return WhileStatement(condition, body)
822
- }
902
+
823
903
 
824
904
  // `do { ... } while cond` (parentheses optional, trailing ; optional)
825
905
  parseDoWhileStatement() {
@@ -850,6 +930,7 @@ export class Parser {
850
930
  while (this.match(TokenType.COMMA)) {
851
931
  tests.push(this.parseExpression())
852
932
  }
933
+ this.rejectSwitchColon()
853
934
  cases.push({ tests, body: this.parseBlockStatements('case body') })
854
935
  } else if (this.check(TokenType.DEFAULT)) {
855
936
  const line = this.advance().line
@@ -857,6 +938,7 @@ export class Parser {
857
938
  throw new Error(`Duplicate 'default' in switch at line ${line}`)
858
939
  }
859
940
  hasDefault = true
941
+ this.rejectSwitchColon()
860
942
  cases.push({
861
943
  tests: null,
862
944
  body: this.parseBlockStatements('default body'),
@@ -872,15 +954,26 @@ export class Parser {
872
954
  return SwitchStatement(discriminant, cases)
873
955
  }
874
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
+
875
965
  // All the `for` forms:
876
966
  // for x in arr { } for x of arr { }
877
967
  // for [k, v] of Object.entries(o) for const x of arr { }
878
968
  // for i from 0 to n { }
879
969
  // for (const x of arr) { } for (const k in obj) { } (keys)
880
970
  // for (let i = 0, n = a.length; i < n; i++) { }
971
+ // for await (const x of stream) { } for await x of stream { }
881
972
  parseForStatement() {
973
+ const isAwait = this.match(TokenType.AWAIT)
974
+
882
975
  if (this.check(TokenType.LPAREN)) {
883
- return this.parseParenFor()
976
+ return this.parseParenFor(isAwait)
884
977
  }
885
978
 
886
979
  let declKind = 'const'
@@ -900,11 +993,16 @@ export class Parser {
900
993
 
901
994
  if (this.match(TokenType.IN) || this.match(TokenType.OF)) {
902
995
  const iterable = this.parseExpression()
903
- const body = this.parseBlockStatements('loop body')
904
- return ForInStatement(varName, iterable, body, declKind)
996
+ const body = this.parseBody('loop body')
997
+ return ForInStatement(varName, iterable, body, declKind, isAwait)
905
998
  }
906
999
 
907
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
+ }
908
1006
  if (typeof varName !== 'string') {
909
1007
  throw new Error(
910
1008
  `'for ... from ... to' needs a plain loop variable at line ${this.peek().line}`,
@@ -913,7 +1011,7 @@ export class Parser {
913
1011
  const start = this.parseExpression()
914
1012
  this.expect(TokenType.TO, "Expected 'to' after the loop's starting value")
915
1013
  const end = this.parseExpression()
916
- const body = this.parseBlockStatements('loop body')
1014
+ const body = this.parseBody('loop body')
917
1015
  return ForRangeStatement(varName, start, end, body)
918
1016
  }
919
1017
 
@@ -922,7 +1020,7 @@ export class Parser {
922
1020
  )
923
1021
  }
924
1022
 
925
- parseParenFor() {
1023
+ parseParenFor(isAwait = false) {
926
1024
  this.expect(TokenType.LPAREN, "Expected '(' after 'for'")
927
1025
 
928
1026
  let init = null
@@ -934,16 +1032,22 @@ export class Parser {
934
1032
 
935
1033
  if (this.check(TokenType.OF) || this.check(TokenType.IN)) {
936
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
+ }
937
1040
  const iterable = this.parseExpression()
938
1041
  this.expect(TokenType.RPAREN, "Expected ')' after the for header")
939
- const body = this.parseBlockStatements('loop body')
1042
+ const body = this.parseBody('loop body')
940
1043
  return isOf
941
- ? ForInStatement(target, iterable, body, kind)
1044
+ ? ForInStatement(target, iterable, body, kind, isAwait)
942
1045
  : ForKeysStatement(target, iterable, body, kind)
943
1046
  }
944
1047
 
945
1048
  // C-style declaration: re-enter declarator parsing with the
946
1049
  // target we already consumed.
1050
+ const typeAnnotation = this.parseOptionalTypeAnnotation()
947
1051
  let first = null
948
1052
  if (this.match(TokenType.EQUALS)) {
949
1053
  first = this.parseExpression()
@@ -955,11 +1059,12 @@ export class Parser {
955
1059
  const more = []
956
1060
  while (this.match(TokenType.COMMA)) {
957
1061
  const name = this.parseBindingTarget()
1062
+ const moreType = this.parseOptionalTypeAnnotation()
958
1063
  let moreInit = null
959
1064
  if (this.match(TokenType.EQUALS)) moreInit = this.parseExpression()
960
- more.push({ name, init: moreInit })
1065
+ more.push({ name, init: moreInit, typeAnnotation: moreType })
961
1066
  }
962
- init = VariableDeclaration(kind, target, first, more)
1067
+ init = VariableDeclaration(kind, target, first, more, typeAnnotation)
963
1068
  } else {
964
1069
  const expressions = [this.parseExpression()]
965
1070
  while (this.match(TokenType.COMMA)) {
@@ -968,6 +1073,12 @@ export class Parser {
968
1073
  init = { type: 'ExpressionList', expressions }
969
1074
  }
970
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
+
971
1082
  this.expect(TokenType.SEMICOLON, "Expected ';' after the for-loop init")
972
1083
  const test = this.check(TokenType.SEMICOLON) ? null : this.parseExpression()
973
1084
  this.expect(TokenType.SEMICOLON, "Expected ';' after the for-loop condition")
@@ -981,21 +1092,13 @@ export class Parser {
981
1092
  }
982
1093
  this.expect(TokenType.RPAREN, "Expected ')' to close the for header")
983
1094
 
984
- const body = this.parseBlockStatements('loop body')
1095
+ const body = this.parseBody('loop body')
985
1096
  return ForStatement(init, test, update, body)
986
1097
  }
987
1098
 
988
- parseRepeatStatement() {
989
- const count = this.parseExpression()
990
- this.expect(TokenType.LBRACE, "Expected '{' to start the repeat body")
991
- const body = []
992
- while (!this.check(TokenType.RBRACE)) {
993
- body.push(this.parseStatement())
994
- }
995
- this.expect(TokenType.RBRACE, "Expected '}' to close the repeat body")
996
- return RepeatStatement(count, body)
997
- }
998
1099
 
1100
+ // `catch (e)`, `catch (e: unknown)`, `catch ({ message })`,
1101
+ // `catch ([first])` and the optional-binding `catch { }`.
999
1102
  parseTryStatement() {
1000
1103
  this.expect(TokenType.LBRACE, "Expected '{' to start try block")
1001
1104
  const tryBlock = []
@@ -1005,13 +1108,14 @@ export class Parser {
1005
1108
  this.expect(TokenType.RBRACE, "Expected '}' to close try block")
1006
1109
 
1007
1110
  let catchParam = null
1111
+ let catchType = null
1008
1112
  let catchBlock = null
1009
1113
  if (this.match(TokenType.CATCH)) {
1010
1114
  if (this.match(TokenType.LPAREN)) {
1011
- catchParam = this.expect(
1012
- TokenType.IDENTIFIER,
1013
- 'Expected catch parameter name',
1014
- ).value
1115
+ catchParam = this.parseBindingTarget()
1116
+ if (this.match(TokenType.COLON)) {
1117
+ catchType = this.parseTypeExpression()
1118
+ }
1015
1119
  this.expect(TokenType.RPAREN, "Expected ')' after catch parameter")
1016
1120
  }
1017
1121
  this.expect(TokenType.LBRACE, "Expected '{' to start catch block")
@@ -1032,83 +1136,422 @@ export class Parser {
1032
1136
  this.expect(TokenType.RBRACE, "Expected '}' to close finally block")
1033
1137
  }
1034
1138
 
1035
- return TryStatement(tryBlock, catchParam, catchBlock, finallyBlock)
1139
+ return TryStatement(tryBlock, catchParam, catchBlock, finallyBlock, catchType)
1036
1140
  }
1037
1141
 
1038
- parseExpression() {
1039
- return this.parseAssignment()
1040
- }
1142
+ // ---- classes ----
1041
1143
 
1042
- // `<<=` is LT + LTE, `>>=` is GT + GTE, `>>>=` is GT + GT + GTE, all
1043
- // written with no whitespace between them. Returns { op, len } (len =
1044
- // number of tokens) or null.
1045
- compoundShiftAt() {
1046
- const a = this.tokens[this.pos]
1047
- const b = this.tokens[this.pos + 1]
1048
- const c = this.tokens[this.pos + 2]
1049
- if (!a || !b) return null
1050
- if (a.type === TokenType.LT && b.type === TokenType.LTE && adjacent(a, b)) {
1051
- return { op: '<<', len: 2 }
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
1052
1157
  }
1053
- if (a.type === TokenType.GT && b.type === TokenType.GTE && adjacent(a, b)) {
1054
- return { op: '>>', len: 2 }
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
1055
1162
  }
1056
- if (
1057
- a.type === TokenType.GT &&
1058
- b.type === TokenType.GT &&
1059
- c &&
1060
- c.type === TokenType.GTE &&
1061
- adjacent(a, b) &&
1062
- adjacent(b, c)
1063
- ) {
1064
- return { op: '>>>', len: 3 }
1163
+ if (isExpression) {
1164
+ return next.type === TokenType.LBRACE || next.type === TokenType.IDENTIFIER
1065
1165
  }
1066
- return null
1166
+ return next.type === TokenType.IDENTIFIER && next.value !== 'extends'
1067
1167
  }
1068
1168
 
1069
- // `<<` is LT LT, `>>` is GT GT, `>>>` is GT GT GT, adjacent. Refuses
1070
- // anything that is really a compound assignment (`>>>=` also starts
1071
- // with GT GT).
1072
- shiftOperatorAt() {
1073
- const a = this.tokens[this.pos]
1074
- const b = this.tokens[this.pos + 1]
1075
- const c = this.tokens[this.pos + 2]
1076
- if (!a || !b) return null
1077
- if (a.type === TokenType.LT && b.type === TokenType.LT && adjacent(a, b)) {
1078
- return { op: '<<', len: 2 }
1079
- }
1080
- if (a.type === TokenType.GT && b.type === TokenType.GT && adjacent(a, b)) {
1081
- if (c && c.type === TokenType.GTE && adjacent(b, c)) return null // >>>=
1082
- if (c && c.type === TokenType.GT && adjacent(b, c)) {
1083
- return { op: '>>>', len: 3 }
1084
- }
1085
- return { op: '>>', len: 2 }
1086
- }
1087
- return null
1169
+ isWord(word) {
1170
+ const tok = this.peek()
1171
+ return tok.type === TokenType.IDENTIFIER && tok.value === word
1088
1172
  }
1089
1173
 
1090
- parseAssignment() {
1091
- const arrow = this.tryParseArrowFunction()
1092
- if (arrow) return arrow
1174
+ isNameToken(tok) {
1175
+ return (
1176
+ !!tok &&
1177
+ (tok.type === TokenType.IDENTIFIER || KEYWORD_TOKEN_TYPES.has(tok.type))
1178
+ )
1179
+ }
1093
1180
 
1094
- const left = this.parseTernary()
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
+ }
1095
1186
 
1096
- if (this.match(TokenType.EQUALS)) {
1097
- const value = this.parseAssignment()
1098
- return AssignmentExpr(left, value)
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
+ }
1099
1196
  }
1197
+ return -1
1198
+ }
1100
1199
 
1101
- if (this.match(TokenType.NULLISH_EQUALS)) {
1102
- const value = this.parseAssignment()
1103
- return AssignmentExpr(left, NullishCoalescingExpr(left, value))
1200
+ startsBody(tok) {
1201
+ if (tok.type === TokenType.IDENTIFIER) {
1202
+ return tok.value !== 'as' && tok.value !== 'satisfies'
1104
1203
  }
1204
+ return STATEMENT_START_TOKENS.has(tok.type)
1205
+ }
1105
1206
 
1106
- if (this.match(TokenType.OR_EQUALS)) {
1107
- const value = this.parseAssignment()
1108
- return AssignmentExpr(left, BinaryExpr('||', left, value))
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
+ }
1109
1221
  }
1222
+ return this.parseExpression()
1223
+ }
1110
1224
 
1111
- if (this.match(TokenType.AND_EQUALS)) {
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
1230
+ const savedPos = this.pos
1231
+ try {
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(', ')
1241
+ } catch {
1242
+ this.pos = savedPos
1243
+ return null
1244
+ }
1245
+ }
1246
+
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)
1112
1555
  const value = this.parseAssignment()
1113
1556
  return AssignmentExpr(left, BinaryExpr('&&', left, value))
1114
1557
  }
@@ -1116,6 +1559,7 @@ export class Parser {
1116
1559
  const compoundOp = COMPOUND_ASSIGNMENT_OPS[this.peek().type]
1117
1560
 
1118
1561
  if (compoundOp) {
1562
+ this.assertTargetRunsOnce(left)
1119
1563
  this.advance()
1120
1564
  const value = this.parseAssignment()
1121
1565
  return AssignmentExpr(left, BinaryExpr(compoundOp, left, value))
@@ -1123,6 +1567,7 @@ export class Parser {
1123
1567
 
1124
1568
  const shiftAssign = this.compoundShiftAt()
1125
1569
  if (shiftAssign) {
1570
+ this.assertTargetRunsOnce(left)
1126
1571
  this.pos += shiftAssign.len
1127
1572
  const value = this.parseAssignment()
1128
1573
  return AssignmentExpr(left, BinaryExpr(shiftAssign.op, left, value))
@@ -1131,19 +1576,7 @@ export class Parser {
1131
1576
  return left
1132
1577
  }
1133
1578
 
1134
- // Parses a type expression speculatively: on failure the position is
1135
- // restored and null is returned instead of throwing. Needed because
1136
- // `cond ? label : 'none'` looks exactly like the start of a typed
1137
- // arrow parameter (`label: Type => ...`) until the type fails to parse.
1138
- tryParseTypeExpression() {
1139
- const savedPos = this.pos
1140
- try {
1141
- return this.parseTypeExpression()
1142
- } catch {
1143
- this.pos = savedPos
1144
- return null
1145
- }
1146
- }
1579
+
1147
1580
 
1148
1581
  // Speculatively parses a destructuring pattern used as an arrow
1149
1582
  // parameter and returns its source text ("[k, v]", "{ id, name }"),
@@ -1169,11 +1602,15 @@ export class Parser {
1169
1602
  // can't resolve are `{}`, `{ name }`, `{ [key]: v }` and
1170
1603
  // `{ method() {} }`; those are blocks, exactly as in JS. Wrap an
1171
1604
  // object literal in parentheses: `x => ({ ... })`.
1605
+ //
1606
+ // `yield` is never an operator inside an arrow body.
1172
1607
  parseArrowBody() {
1173
- if (this.check(TokenType.LBRACE) && !this.looksLikeObjectLiteral()) {
1174
- return BlockStatement(this.parseBlockStatements('arrow function body'))
1175
- }
1176
- return this.parseAssignment()
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
+ })
1177
1614
  }
1178
1615
 
1179
1616
  looksLikeObjectLiteral() {
@@ -1193,36 +1630,6 @@ export class Parser {
1193
1630
  )
1194
1631
  }
1195
1632
 
1196
- // Entry point for arrow functions, including the async forms:
1197
- // async x => ... async (a, b) => ...
1198
- // async x: Type => ... async (a: Type) => ...
1199
- //
1200
- // `async` is a keyword token but also a legal identifier name, so
1201
- // it is only treated as the async modifier when what follows could
1202
- // start an arrow's parameter list (an identifier/keyword name or
1203
- // '('). `async => 1` (a param literally named async) still goes
1204
- // down the normal path, and so does `async(x)` as a plain call,
1205
- // because the speculative parse below backs out and restores the
1206
- // position when no `=>` follows.
1207
- tryParseArrowFunction() {
1208
- if (this.check(TokenType.ASYNC)) {
1209
- const next = this.tokens[this.pos + 1]
1210
- const startsParams =
1211
- next &&
1212
- (next.type === TokenType.LPAREN ||
1213
- next.type === TokenType.IDENTIFIER ||
1214
- (next.type !== TokenType.ARROW && KEYWORD_TOKEN_TYPES.has(next.type)))
1215
- if (startsParams) {
1216
- const savedPos = this.pos
1217
- this.advance() // consume 'async'
1218
- const arrow = this.tryParseSyncArrow()
1219
- if (arrow) return { ...arrow, isAsync: true }
1220
- this.pos = savedPos
1221
- return null
1222
- }
1223
- }
1224
- return this.tryParseSyncArrow()
1225
- }
1226
1633
 
1227
1634
  // Arrow functions are tried with backtracking before falling
1228
1635
  // through to the normal ternary/assignment chain, since both forms
@@ -1233,8 +1640,9 @@ export class Parser {
1233
1640
  // BlockStatement in their expression generators).
1234
1641
  //
1235
1642
  // Parenthesized params may be plain names, destructuring patterns
1236
- // ([k, v], { id, name }), rest params (...args), typed (a: number)
1237
- // and have defaults (a = 1).
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`.
1238
1646
  tryParseSyncArrow() {
1239
1647
  // single-param form: x => expr or x: Type => expr
1240
1648
  if (
@@ -1265,7 +1673,7 @@ export class Parser {
1265
1673
  return null
1266
1674
  }
1267
1675
 
1268
- // (a, b) => expr or (a: Type, b = 1, ...rest) => expr
1676
+ // (a, b) => expr or (a: Type, b?: T, c = 1, ...rest) => expr
1269
1677
  // also ([k, v]) => expr, ({ id }) => expr
1270
1678
  if (this.check(TokenType.LPAREN)) {
1271
1679
  const savedPos = this.pos
@@ -1274,6 +1682,7 @@ export class Parser {
1274
1682
  const params = []
1275
1683
  const paramTypes = []
1276
1684
  const paramDefaults = []
1685
+ const paramOptional = []
1277
1686
  let isValidParamList = true
1278
1687
 
1279
1688
  if (!this.check(TokenType.RPAREN)) {
@@ -1305,6 +1714,11 @@ export class Parser {
1305
1714
  }
1306
1715
  params.push(name)
1307
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))
1721
+
1308
1722
  let paramType = null
1309
1723
  if (this.match(TokenType.COLON)) {
1310
1724
  paramType = this.tryParseTypeExpression()
@@ -1333,10 +1747,32 @@ export class Parser {
1333
1747
 
1334
1748
  if (isValidParamList && this.check(TokenType.RPAREN)) {
1335
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
+
1336
1764
  if (this.check(TokenType.ARROW)) {
1337
1765
  this.pos++
1338
1766
  const body = this.parseArrowBody()
1339
- return ArrowFunctionExpr(params, body, paramTypes, false, paramDefaults)
1767
+ return ArrowFunctionExpr(
1768
+ params,
1769
+ body,
1770
+ paramTypes,
1771
+ false,
1772
+ paramDefaults,
1773
+ paramOptional,
1774
+ returnType,
1775
+ )
1340
1776
  }
1341
1777
  }
1342
1778
 
@@ -1375,29 +1811,29 @@ export class Parser {
1375
1811
  return left
1376
1812
  }
1377
1813
 
1378
- parseLogicalAnd() {
1379
- let left = this.parseNotOperand()
1380
- while (this.match(TokenType.AND)) {
1381
- const right = this.parseNotOperand()
1382
- left = BinaryExpr('&&', left, right)
1814
+ parseLogicalAnd() {
1815
+ let left = this.parseNotOperand()
1816
+ while (this.match(TokenType.AND)) {
1817
+ const right = this.parseNotOperand()
1818
+ left = BinaryExpr('&&', left, right)
1819
+ }
1820
+ return left
1383
1821
  }
1384
- return left
1385
- }
1386
1822
 
1387
- // Loose mode only: the WORD `not` (value 'not') sits above is/has/
1388
- // exists. In tight mode, or for the symbol `!`, this falls straight
1389
- // through and parseUnary handles it as before.
1390
- parseNotOperand() {
1391
- if (
1392
- this.looseNot &&
1393
- this.check(TokenType.NOT) &&
1394
- this.peek().value === 'not'
1395
- ) {
1396
- this.advance()
1397
- return UnaryExpr('!', this.parseNotOperand())
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()
1398
1836
  }
1399
- return this.parseBitwiseOr()
1400
- }
1401
1837
 
1402
1838
  parseBitwiseOr() {
1403
1839
  let left = this.parseBitwiseXor()
@@ -1437,14 +1873,58 @@ parseNotOperand() {
1437
1873
  return left
1438
1874
  }
1439
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
+
1440
1905
  parseComparison() {
1441
1906
  let left = this.parsePredicate()
1442
- // `>>=` / `<<=` start with a GT/LT token; those belong to
1443
- // parseAssignment, not to a comparison.
1444
- while (COMPARISON_SYMBOLS[this.peek().type] && !this.compoundShiftAt()) {
1445
- const operator = COMPARISON_SYMBOLS[this.advance().type]
1446
- const right = this.parsePredicate()
1447
- left = BinaryExpr(operator, left, right)
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
1448
1928
  }
1449
1929
  return left
1450
1930
  }
@@ -1460,7 +1940,7 @@ parseNotOperand() {
1460
1940
  }
1461
1941
  if (this.match(TokenType.HAS)) {
1462
1942
  const right = this.parseShift()
1463
- return CallExpr(MemberExpr(left, 'includes'), [right])
1943
+ return hasExpr(left, right)
1464
1944
  }
1465
1945
 
1466
1946
  return left
@@ -1522,6 +2002,9 @@ parseNotOperand() {
1522
2002
  if (this.match(TokenType.MINUS)) {
1523
2003
  return UnaryExpr('-', this.parseUnary())
1524
2004
  }
2005
+ if (this.match(TokenType.PLUS)) {
2006
+ return UnaryExpr('+', this.parseUnary())
2007
+ }
1525
2008
  if (this.match(TokenType.TYPEOF)) {
1526
2009
  return UnaryExpr('typeof', this.parseUnary())
1527
2010
  }
@@ -1532,27 +2015,66 @@ parseNotOperand() {
1532
2015
  return UnaryExpr('void', this.parseUnary())
1533
2016
  }
1534
2017
  if (this.match(TokenType.PLUS_PLUS)) {
1535
- const target = this.parseUnary()
1536
- return AssignmentExpr(target, BinaryExpr('+', target, Literal(1)))
2018
+ return UpdateExpr('++', this.parseUnary(), true)
1537
2019
  }
1538
2020
  if (this.match(TokenType.MINUS_MINUS)) {
1539
- const target = this.parseUnary()
1540
- return AssignmentExpr(target, BinaryExpr('-', target, Literal(1)))
2021
+ return UpdateExpr('--', this.parseUnary(), true)
1541
2022
  }
1542
2023
 
1543
2024
  const expr = this.parseMemberExpression()
1544
- if (this.match(TokenType.PLUS_PLUS)) {
1545
- return AssignmentExpr(expr, BinaryExpr('+', expr, Literal(1)))
1546
- }
1547
- if (this.match(TokenType.MINUS_MINUS)) {
1548
- return AssignmentExpr(expr, BinaryExpr('-', expr, Literal(1)))
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)
1549
2030
  }
1550
2031
  return expr
1551
2032
  }
1552
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
+
1553
2052
  parseMemberExpression() {
1554
2053
  let expr = this.parsePrimary()
1555
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
+ }
1556
2078
  if (this.match(TokenType.DOT)) {
1557
2079
  const property = this.parsePropertyName("after '.'")
1558
2080
  expr = MemberExpr(expr, property)
@@ -1567,6 +2089,16 @@ parseNotOperand() {
1567
2089
  expr = MemberExpr(expr, property, true)
1568
2090
  continue
1569
2091
  }
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
+
1570
2102
  if (this.check(TokenType.LPAREN)) {
1571
2103
  expr = CallExpr(expr, this.parseCallArguments())
1572
2104
  continue
@@ -1612,146 +2144,259 @@ parseNotOperand() {
1612
2144
  return args
1613
2145
  }
1614
2146
 
1615
- parsePrimary() {
1616
- if (this.match(TokenType.NEW)) {
1617
- let callee = this.parsePrimary()
1618
- while (this.match(TokenType.DOT)) {
1619
- const property = this.expect(
1620
- TokenType.IDENTIFIER,
1621
- "Expected a property name after '.'",
1622
- ).value
1623
- callee = MemberExpr(callee, property)
2147
+ parsePrimary() {
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
+ }
2160
+ let callee = this.parsePrimary()
2161
+ while (this.match(TokenType.DOT)) {
2162
+ const property = this.parsePropertyName("after '.'")
2163
+ callee = MemberExpr(callee, property)
2164
+ }
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)
1624
2173
  }
1625
- let args = []
1626
- if (this.check(TokenType.LPAREN)) {
1627
- args = this.parseCallArguments()
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
+ }
1628
2188
  }
1629
- return NewExpr(callee, args)
1630
- }
1631
2189
 
1632
- // function (a, b) { ... } / async function name(a) { ... }
1633
- if (this.isFunctionKeywordAhead()) {
1634
- const isAsync = this.match(TokenType.ASYNC)
1635
- const fn = this.parseFunctionRest(isAsync)
1636
- return FunctionExpr(fn.params, fn.body, fn.isAsync, fn.name)
1637
- }
2190
+ // class { ... } / class Name extends Base { ... } as an expression
2191
+ if (this.isClassAhead(true)) {
2192
+ return this.parseClass(true)
2193
+ }
1638
2194
 
1639
- // Regex literal. String(regex) yields "/pattern/flags", which
1640
- // every generator already emits for Literal nodes, so no codegen
1641
- // changes are needed.
1642
- if (this.check(TokenType.REGEX)) {
1643
- const tok = this.advance()
1644
- try {
1645
- return Literal(new RegExp(tok.value.pattern, tok.value.flags))
1646
- } catch (err) {
1647
- throw new Error(
1648
- `Invalid regular expression at line ${tok.line}: ${err.message}`,
1649
- )
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
+ )
2206
+ }
1650
2207
  }
1651
- }
1652
2208
 
1653
- // 10n -> BigInt("10"), so every generator handles it as a normal
1654
- // call to the BigInt global.
1655
- if (this.check(TokenType.BIGINT)) {
1656
- const text = this.advance().value
1657
- return CallExpr(Identifier('BigInt'), [Literal(text)])
1658
- }
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)])
2214
+ }
1659
2215
 
1660
- if (this.check(TokenType.NUMBER) || this.check(TokenType.STRING)) {
1661
- return Literal(this.advance().value)
1662
- }
2216
+ if (this.check(TokenType.NUMBER) || this.check(TokenType.STRING)) {
2217
+ return Literal(this.advance().value)
2218
+ }
1663
2219
 
1664
- if (this.check(TokenType.TEMPLATE_LITERAL)) {
1665
- const rawParts = this.advance().value
1666
- const parts = rawParts.map((p) =>
1667
- p.type === 'text'
1668
- ? p
1669
- : {
1670
- type: 'expr',
1671
- // Same language options as the enclosing parser, so
1672
- // `${ not items has x }` follows the project's `not` mode.
1673
- expression: parseExpressionString(p.source, this.options),
1674
- },
1675
- )
1676
- return TemplateLiteralExpr(parts)
1677
- }
2220
+ if (this.check(TokenType.TEMPLATE_LITERAL)) {
2221
+ return this.templateLiteralFromParts(this.advance().value)
2222
+ }
1678
2223
 
1679
- if (
1680
- this.check(TokenType.IDENTIFIER) ||
1681
- KEYWORD_TOKEN_TYPES.has(this.peek().type)
1682
- ) {
1683
- const name = this.advance().value
1684
- // "null"/"true"/"false"/"undefined" are lexed as plain identifier
1685
- // tokens (there's no separate keyword TokenType for them), but
1686
- // they're JS keyword literals, not variable/state references.
1687
- // Emitting them as Literal here -- instead of Identifier -- means
1688
- // every downstream consumer treats them correctly by construction.
1689
- if (name === 'null') return Literal(null)
1690
- if (name === 'undefined') return Literal(undefined)
1691
- if (name === 'true') return Literal(true)
1692
- if (name === 'false') return Literal(false)
1693
- return Identifier(name)
1694
- }
1695
-
1696
- if (this.match(TokenType.LPAREN)) {
1697
- const expr = this.parseExpression()
1698
- this.expect(
1699
- TokenType.RPAREN,
1700
- "Expected ')' to close a grouped expression",
2224
+ if (
2225
+ this.check(TokenType.IDENTIFIER) ||
2226
+ KEYWORD_TOKEN_TYPES.has(this.peek().type)
2227
+ ) {
2228
+ const name = this.advance().value
2229
+ // "null"/"true"/"false"/"undefined" are lexed as plain identifier
2230
+ // tokens (there's no separate keyword TokenType for them), but
2231
+ // they're JS keyword literals, not variable/state references.
2232
+ // Emitting them as Literal here -- instead of Identifier -- means
2233
+ // every downstream consumer treats them correctly by construction.
2234
+ if (name === 'null') return Literal(null)
2235
+ if (name === 'undefined') return Literal(undefined)
2236
+ if (name === 'true') return Literal(true)
2237
+ if (name === 'false') return Literal(false)
2238
+ return Identifier(name)
2239
+ }
2240
+
2241
+ // Grouping, and the comma operator: (a, b, c)
2242
+ if (this.match(TokenType.LPAREN)) {
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
+ }
2251
+ this.expect(
2252
+ TokenType.RPAREN,
2253
+ "Expected ')' to close a grouped expression",
2254
+ )
2255
+ return expr
2256
+ }
2257
+ if (this.match(TokenType.LBRACE)) {
2258
+ return this.parseObjectLiteral()
2259
+ }
2260
+ if (this.match(TokenType.LBRACKET)) {
2261
+ return this.parseArrayLiteral()
2262
+ }
2263
+ throw new Error(
2264
+ `Unexpected token ${this.peek().type} at line ${this.peek().line}`,
1701
2265
  )
1702
- return expr
1703
2266
  }
1704
- if (this.match(TokenType.LBRACE)) {
1705
- return this.parseObjectLiteral()
1706
- }
1707
- if (this.match(TokenType.LBRACKET)) {
1708
- return this.parseArrayLiteral()
1709
- }
1710
- throw new Error(
1711
- `Unexpected token ${this.peek().type} at line ${this.peek().line}`,
1712
- )
1713
- }
2267
+
1714
2268
  // Type expressions are captured as plain strings, not a full type
1715
2269
  // AST -- Tylix's own codegen never interprets them, it only needs
1716
2270
  // the exact TS source text to paste into the virtual .ts file handed
1717
2271
  // to the TypeScript compiler API.
1718
- parseTypeExpression() {
1719
- let left = this.parseUnionTypeOperand()
1720
- while (this.check(TokenType.PIPE)) {
1721
- this.advance()
1722
- const right = this.parseUnionTypeOperand()
1723
- left = `${left} | ${right}`
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()}`
1724
2287
  }
1725
2288
  return left
1726
2289
  }
1727
2290
 
1728
- parseUnionTypeOperand() {
1729
- let type = this.parsePrimaryType()
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) {
1730
2327
  while (this.check(TokenType.LBRACKET)) {
1731
2328
  this.advance()
1732
- this.expect(TokenType.RBRACKET, "Expected ']' to close array type")
1733
- type = `${type}[]`
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
+ }
1734
2339
  }
1735
2340
  return type
1736
2341
  }
1737
2342
 
1738
2343
  parsePrimaryType() {
1739
- if (this.check(TokenType.LBRACE)) {
1740
- return this.parseObjectTypeLiteral()
2344
+ const tok = this.peek()
2345
+
2346
+ if (tok.type === TokenType.STRING) {
2347
+ this.advance()
2348
+ return JSON.stringify(tok.value)
1741
2349
  }
1742
- if (this.match(TokenType.LPAREN)) {
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()
1743
2385
  const inner = this.parseTypeExpression()
1744
2386
  this.expect(TokenType.RPAREN, "Expected ')' to close grouped type")
1745
2387
  return `(${inner})`
1746
2388
  }
1747
2389
 
1748
- let name = this.expect(TokenType.IDENTIFIER, 'Expected a type name').value
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
1749
2398
  while (this.match(TokenType.DOT)) {
1750
- const prop = this.expect(
1751
- TokenType.IDENTIFIER,
1752
- "Expected a property name after '.'",
1753
- ).value
1754
- name += `.${prop}`
2399
+ name += `.${this.parsePropertyName("after '.'")}`
1755
2400
  }
1756
2401
 
1757
2402
  if (this.match(TokenType.LT)) {
@@ -1766,27 +2411,671 @@ parsePrimary() {
1766
2411
  return name
1767
2412
  }
1768
2413
 
1769
- parseObjectTypeLiteral() {
1770
- this.expect(TokenType.LBRACE, "Expected '{' to start object type")
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")
1771
2679
  const members = []
1772
2680
  while (!this.check(TokenType.RBRACE)) {
1773
- const key = this.parseNameToken('Expected a property name')
1774
- const optional = this.match(TokenType.QUESTION)
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()
1775
2774
  this.expect(
1776
- TokenType.COLON,
1777
- "Expected ':' after property name in object type",
2775
+ TokenType.RBRACKET,
2776
+ "Expected ']' to close a computed class member name",
1778
2777
  )
1779
- const valueType = this.parseTypeExpression()
1780
- members.push(`${key}${optional ? '?' : ''}: ${valueType}`)
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
+ }
1781
3063
  if (!this.match(TokenType.COMMA)) this.match(TokenType.SEMICOLON)
1782
3064
  }
1783
3065
  this.expect(TokenType.RBRACE, "Expected '}' to close object type")
1784
3066
  return `{ ${members.join('; ')} }`
1785
3067
  }
1786
-
3068
+
3069
+ // Array literal after the opening '['. A comma with nothing before
3070
+ // it is a hole (`[1, , 3]`), stored as `null` in `elements`.
1787
3071
  parseArrayLiteral() {
1788
3072
  const elements = []
1789
3073
  while (!this.check(TokenType.RBRACKET)) {
3074
+ if (this.check(TokenType.COMMA)) {
3075
+ elements.push(null)
3076
+ this.advance()
3077
+ continue
3078
+ }
1790
3079
  if (this.match(TokenType.SPREAD)) {
1791
3080
  elements.push(SpreadElement(this.parseExpression()))
1792
3081
  } else {
@@ -1805,6 +3094,9 @@ parsePrimary() {
1805
3094
  // { [expr]: value } computed keys
1806
3095
  // { save(x) { ... } } method shorthand
1807
3096
  // { async load() { ... } } async method shorthand
3097
+ // { *items() { ... } } generator method (also async *)
3098
+ // { get total() { ... } } getter
3099
+ // { set total(v) { ... } } setter
1808
3100
  parseObjectLiteral() {
1809
3101
  const properties = []
1810
3102
  while (!this.check(TokenType.RBRACE)) {
@@ -1820,10 +3112,33 @@ parsePrimary() {
1820
3112
  continue
1821
3113
  }
1822
3114
 
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
+
1823
3138
  // `async name(...) { }` -- but `async: x`, `async,` and `async()`
1824
3139
  // are ordinary keys/methods named "async".
1825
3140
  let isAsync = false
1826
- if (this.check(TokenType.ASYNC)) {
3141
+ if (!accessorKind && this.check(TokenType.ASYNC)) {
1827
3142
  const n = this.tokens[this.pos + 1]
1828
3143
  if (
1829
3144
  n &&
@@ -1837,6 +3152,12 @@ parsePrimary() {
1837
3152
  }
1838
3153
  }
1839
3154
 
3155
+ // `*name() { }` generator method
3156
+ let isGenerator = false
3157
+ if (!accessorKind && this.match(TokenType.STAR)) {
3158
+ isGenerator = true
3159
+ }
3160
+
1840
3161
  let key = null
1841
3162
  let keyExpr = null
1842
3163
  let keyKind = 'name'
@@ -1864,31 +3185,50 @@ parsePrimary() {
1864
3185
  )
1865
3186
  }
1866
3187
 
1867
- // Method shorthand
1868
- if (this.check(TokenType.LPAREN)) {
1869
- this.advance()
1870
- const params = this.parseParamList()
1871
- if (this.match(TokenType.COLON)) this.parseTypeExpression()
1872
- const body = this.parseBlockStatements('method body')
1873
- properties.push({
1874
- key,
1875
- keyExpr,
1876
- method: true,
1877
- value: FunctionExpr(params, body, isAsync),
1878
- })
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
+ })
1879
3209
  this.match(TokenType.COMMA)
1880
3210
  continue
1881
3211
  }
1882
3212
 
1883
- if (isAsync) {
3213
+ if (isAsync || isGenerator || accessorKind) {
1884
3214
  throw new Error(
1885
- `Expected '(' after async method name at line ${this.peek().line}`,
3215
+ `Expected '(' after the method name at line ${this.peek().line}`,
1886
3216
  )
1887
3217
  }
1888
3218
 
1889
3219
  if (keyKind === 'name' && !this.check(TokenType.COLON)) {
1890
- // Shorthand: { name } means { name: name }
1891
- properties.push({ key, value: Identifier(key) })
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
+ }
1892
3232
  this.match(TokenType.COMMA)
1893
3233
  continue
1894
3234
  }