@tylix/compiler 0.5.2 → 0.6.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.
@@ -10,6 +10,8 @@ import {
10
10
  TernaryExpr,
11
11
  NullishCoalescingExpr,
12
12
  ArrowFunctionExpr,
13
+ FunctionExpr,
14
+ FunctionDeclaration,
13
15
  TemplateLiteralExpr,
14
16
  SpreadElement,
15
17
  Identifier,
@@ -17,6 +19,7 @@ import {
17
19
  Literal,
18
20
  ReturnStatement,
19
21
  ExpressionStatement,
22
+ EmptyStatement,
20
23
  CallExpr,
21
24
  NewExpr,
22
25
  AwaitExpr,
@@ -28,6 +31,8 @@ import {
28
31
  TryStatement,
29
32
  IfStatement,
30
33
  ForInStatement,
34
+ ForKeysStatement,
35
+ ForStatement,
31
36
  ForRangeStatement,
32
37
  RepeatStatement,
33
38
  BreakStatement,
@@ -37,6 +42,7 @@ import {
37
42
  BlockStatement,
38
43
  ThrowStatement,
39
44
  WhileStatement,
45
+ DoWhileStatement,
40
46
  SwitchStatement,
41
47
  } from '../ast/nodes.js'
42
48
  import { parseExpressionString } from './parseExpressionString.js'
@@ -47,6 +53,7 @@ const COMPARISON_SYMBOLS = {
47
53
  [TokenType.GTE]: '>=',
48
54
  [TokenType.LTE]: '<=',
49
55
  [TokenType.INSTANCEOF]: 'instanceof',
56
+ [TokenType.IN]: 'in',
50
57
  }
51
58
 
52
59
  const ADDITIVE_SYMBOLS = {
@@ -67,50 +74,102 @@ const KEYWORD_TOKEN_TYPES = new Set(Object.values(KEYWORDS))
67
74
  // `this.count += 1` becomes exactly the same AST as if the dev had
68
75
  // written `this.count = this.count + 1`, so no codegen changes are
69
76
  // needed at all; generateExpression already knows how to emit both
70
- // node types.
77
+ // node types. (`||=` / `&&=` / `??=` and the shift forms are handled
78
+ // separately in parseAssignment.)
71
79
  const COMPOUND_ASSIGNMENT_OPS = {
72
80
  [TokenType.PLUS_EQUALS]: '+',
73
81
  [TokenType.MINUS_EQUALS]: '-',
74
82
  [TokenType.STAR_EQUALS]: '*',
75
83
  [TokenType.SLASH_EQUALS]: '/',
76
84
  [TokenType.PERCENT_EQUALS]: '%',
85
+ [TokenType.STAR_STAR_EQUALS]: '**',
86
+ [TokenType.AMP_EQUALS]: '&',
87
+ [TokenType.PIPE_EQUALS]: '|',
88
+ [TokenType.CARET_EQUALS]: '^',
89
+ }
90
+
91
+ // Renders a destructuring pattern back to source text. Arrow and
92
+ // function params are stored as plain strings, so `([k, v]) => ...`
93
+ // and `({ id, name }) => ...` are kept as "[k, v]" / "{ id, name }"
94
+ // and emitted verbatim by the codegen.
95
+ function bindingToSource(t) {
96
+ if (typeof t === 'string') return t
97
+ if (t.type === 'ObjectPattern') {
98
+ 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)}`
107
+ })
108
+ if (t.rest) parts.push(`...${t.rest}`)
109
+ return `{ ${parts.join(', ')} }`
110
+ }
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
+ })
120
+ if (t.rest) parts.push(`...${t.rest}`)
121
+ return `[${parts.join(', ')}]`
122
+ }
123
+
124
+ // True when token `b` starts exactly where token `a` ends -- i.e. the
125
+ // two were written with no whitespace between them.
126
+ function adjacent(a, b) {
127
+ return !!a && !!b && b.start === a.start + String(a.value).length
77
128
  }
78
129
 
79
130
  /**
80
131
  * Parses the token stream from the Lexer into a Page AST.
81
132
  *
82
133
  * Expressions are parsed with real precedence-climbing, low to high:
83
- * arrow function (x => expr, (a, b) => expr, block bodies
84
- * x => { ... }, and the async forms of all of these) -- tried
85
- * first, with backtracking, since it can start with the same
86
- * tokens as a grouped expression or a bare identifier
87
- * assignment (= += -= *= /= %= ??=)
134
+ * 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
137
+ * assignment (= += -= *= /= %= **= ??= ||= &&= &= |= ^= <<= >>= >>>=)
88
138
  * ternary (?:)
89
139
  * nullish (??)
90
- * logical or (or)
91
- * logical and (and)
92
- * equality (is / is not)
93
- * comparison (> < >= <= instanceof)
140
+ * logical or (or, ||)
141
+ * logical and (and, &&)
142
+ * bitwise or (|)
143
+ * bitwise xor (^)
144
+ * bitwise and (&)
145
+ * equality (is / is not, also ===, !==, ==, !=)
146
+ * comparison (> < >= <= instanceof in)
94
147
  * predicate (has / exists / missing)
148
+ * shift (<< >> >>>)
95
149
  * additive (+ -)
96
150
  * multiplicative (* / %)
97
151
  * exponent (**, right-associative)
98
- * unary (not, -, await, typeof, prefix ++/--)
152
+ * unary (not, !, ~, -, await, typeof, delete, void, prefix ++/--)
99
153
  * postfix (x++, x--)
100
154
  * member/call (a.b, a(), a?.b, a?.())
101
- * primary (literals, identifiers, grouping, arrays, objects,
102
- * template literals)
155
+ * primary (literals, regex, bigint, identifiers, grouping, arrays,
156
+ * objects, template literals, function expressions)
103
157
  *
104
158
  * `x++` / `++x` desugar to `x = x + 1` (same trick as compound
105
159
  * assignment), so the expression's value is the NEW value in both
106
- * forms, unlike JS where postfix yields the old one. Fine for
107
- * statements and event handlers, which is where it is used.
160
+ * forms, unlike JS where postfix yields the old one.
161
+ *
162
+ * Shifts are recombined from adjacent LT/GT tokens (see
163
+ * shiftOperatorAt) because the Lexer never emits << or >> as single
164
+ * tokens -- that keeps `Array<Array<T>>` parseable as a type.
108
165
  */
109
166
  export class Parser {
110
- constructor(tokens) {
111
- this.tokens = tokens
112
- this.pos = 0
113
- }
167
+ constructor(tokens, options = {}) {
168
+ this.tokens = tokens
169
+ this.pos = 0
170
+ this.options = options
171
+ this.looseNot = options.not === 'loose'
172
+ }
114
173
 
115
174
  parse() {
116
175
  const page = {
@@ -376,23 +435,42 @@ export class Parser {
376
435
  return { ...StateNode(name, value, typeAnnotation), line: startLine }
377
436
  }
378
437
 
379
- parseMethod() {
380
- const startLine = this.peek().line
381
- const isAsync = this.match(TokenType.ASYNC)
382
- const name = this.parseNameToken('Expected method name')
383
- this.expect(TokenType.LPAREN, "Expected '(' after method name")
384
-
438
+ // Parses a parameter list. The opening '(' must already be
439
+ // consumed; this consumes the closing ')'. Supports types
440
+ // (`a: number`), defaults (`a = 1`), rest (`...args`) and
441
+ // destructured params (`{ id, name }`, `[a, b]`).
442
+ parseParamList() {
385
443
  const params = []
386
444
  while (!this.check(TokenType.RPAREN)) {
387
- const paramName = this.parseNameToken('Expected parameter name')
388
- let paramType = null
445
+ const rest = this.match(TokenType.SPREAD)
446
+ let name
447
+ if (this.check(TokenType.LBRACE) || this.check(TokenType.LBRACKET)) {
448
+ name = bindingToSource(this.parseBindingTarget())
449
+ } else {
450
+ name = this.parseNameToken('Expected parameter name')
451
+ }
452
+ let typeAnnotation = null
389
453
  if (this.match(TokenType.COLON)) {
390
- paramType = this.parseTypeExpression()
454
+ typeAnnotation = this.parseTypeExpression()
455
+ }
456
+ let defaultValue = null
457
+ if (this.match(TokenType.EQUALS)) {
458
+ defaultValue = this.parseAssignment()
391
459
  }
392
- params.push({ name: paramName, typeAnnotation: paramType })
460
+ params.push({ name, typeAnnotation, defaultValue, rest })
393
461
  this.match(TokenType.COMMA)
394
462
  }
395
463
  this.expect(TokenType.RPAREN, "Expected ')' after parameters")
464
+ return params
465
+ }
466
+
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()
396
474
 
397
475
  let returnType = null
398
476
  if (this.match(TokenType.COLON)) {
@@ -552,8 +630,8 @@ export class Parser {
552
630
  }
553
631
 
554
632
  // `{ stmt stmt ... }` -- shared by the newer statement forms
555
- // (while, switch clauses, block-bodied arrows). `what` only feeds
556
- // the error messages.
633
+ // (while, switch clauses, block-bodied arrows, functions, loops).
634
+ // `what` only feeds the error messages.
557
635
  parseBlockStatements(what) {
558
636
  this.expect(TokenType.LBRACE, `Expected '{' to start ${what}`)
559
637
  const body = []
@@ -564,7 +642,36 @@ export class Parser {
564
642
  return body
565
643
  }
566
644
 
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
+
662
+ isFunctionKeywordAhead() {
663
+ return (
664
+ this.check(TokenType.FUNCTION) ||
665
+ (this.check(TokenType.ASYNC) &&
666
+ this.tokens[this.pos + 1]?.type === TokenType.FUNCTION)
667
+ )
668
+ }
669
+
567
670
  parseStatementInner() {
671
+ if (this.match(TokenType.SEMICOLON)) {
672
+ return EmptyStatement()
673
+ }
674
+
568
675
  if (this.match(TokenType.RETURN)) {
569
676
  const hasValue =
570
677
  !this.check(TokenType.SEMICOLON) && !this.check(TokenType.RBRACE)
@@ -587,6 +694,10 @@ export class Parser {
587
694
  return this.parseWhileStatement()
588
695
  }
589
696
 
697
+ if (this.match(TokenType.DO)) {
698
+ return this.parseDoWhileStatement()
699
+ }
700
+
590
701
  if (this.match(TokenType.SWITCH)) {
591
702
  return this.parseSwitchStatement()
592
703
  }
@@ -613,13 +724,30 @@ export class Parser {
613
724
  return ContinueStatement()
614
725
  }
615
726
 
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)
743
+ }
744
+ }
745
+
616
746
  if (this.check(TokenType.CONST) || this.check(TokenType.LET)) {
617
747
  const kind = this.advance().type === TokenType.CONST ? 'const' : 'let'
618
- const target = this.parseBindingTarget()
619
- this.expect(TokenType.EQUALS, "Expected '=' in variable declaration")
620
- const init = this.parseExpression()
748
+ const decl = this.parseDeclarators(kind)
621
749
  this.match(TokenType.SEMICOLON)
622
- return VariableDeclaration(kind, target, init)
750
+ return decl
623
751
  }
624
752
 
625
753
  const expression = this.parseExpression()
@@ -627,37 +755,63 @@ export class Parser {
627
755
  return ExpressionStatement(expression)
628
756
  }
629
757
 
630
- parseIfStatement() {
631
- const hasParen = this.match(TokenType.LPAREN)
632
- const condition = this.parseExpression()
633
- if (hasParen) {
634
- this.expect(TokenType.RPAREN, "Expected ')' after if condition")
758
+ // `target [= init] [, target [= init] ...]` after const/let.
759
+ // `let x` (no initializer) is allowed; `const x` requires one.
760
+ parseDeclarators(kind) {
761
+ const target = this.parseBindingTarget()
762
+ let init = null
763
+ if (this.match(TokenType.EQUALS)) {
764
+ init = this.parseExpression()
765
+ } else if (kind === 'const') {
766
+ throw new Error(
767
+ `Missing initializer in const declaration at line ${this.peek().line}`,
768
+ )
635
769
  }
636
- this.expect(TokenType.LBRACE, "Expected '{' to start if body")
637
- const consequent = []
638
- while (!this.check(TokenType.RBRACE)) {
639
- consequent.push(this.parseStatement())
770
+ const more = []
771
+ while (this.match(TokenType.COMMA)) {
772
+ const name = this.parseBindingTarget()
773
+ let moreInit = null
774
+ if (this.match(TokenType.EQUALS)) {
775
+ moreInit = this.parseExpression()
776
+ } else if (kind === 'const') {
777
+ throw new Error(
778
+ `Missing initializer in const declaration at line ${this.peek().line}`,
779
+ )
780
+ }
781
+ more.push({ name, init: moreInit })
640
782
  }
641
- this.expect(TokenType.RBRACE, "Expected '}' to close if body")
783
+ return VariableDeclaration(kind, target, init, more)
784
+ }
642
785
 
643
- let alternate = null
644
- if (this.match(TokenType.ELSE)) {
645
- if (this.check(TokenType.IF)) {
646
- this.advance()
647
- alternate = [this.parseIfStatement()]
648
- } else {
649
- this.expect(TokenType.LBRACE, "Expected '{' to start else body")
650
- alternate = []
651
- while (!this.check(TokenType.RBRACE)) {
652
- alternate.push(this.parseStatement())
653
- }
654
- this.expect(TokenType.RBRACE, "Expected '}' to close else body")
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())
655
808
  }
809
+ this.expect(TokenType.RBRACE, "Expected '}' to close else body")
656
810
  }
657
-
658
- return IfStatement(condition, consequent, alternate)
659
811
  }
660
812
 
813
+ return IfStatement(condition, consequent, alternate)
814
+ }
661
815
  // `while cond { ... }` or `while (cond) { ... }`. Parentheses need no
662
816
  // special handling: `(cond)` already parses as a grouped expression,
663
817
  // which also keeps `while (a) and (b) { ... }` working.
@@ -667,6 +821,15 @@ export class Parser {
667
821
  return WhileStatement(condition, body)
668
822
  }
669
823
 
824
+ // `do { ... } while cond` (parentheses optional, trailing ; optional)
825
+ parseDoWhileStatement() {
826
+ const body = this.parseBlockStatements('do body')
827
+ this.expect(TokenType.WHILE, "Expected 'while' after the do body")
828
+ const condition = this.parseExpression()
829
+ this.match(TokenType.SEMICOLON)
830
+ return DoWhileStatement(body, condition)
831
+ }
832
+
670
833
  // Tylix-style switch: braces for every clause, no fallthrough, and
671
834
  // `case a, b { ... }` instead of stacked labels. Codegen emits the
672
835
  // `break` itself.
@@ -709,41 +872,119 @@ export class Parser {
709
872
  return SwitchStatement(discriminant, cases)
710
873
  }
711
874
 
875
+ // All the `for` forms:
876
+ // for x in arr { } for x of arr { }
877
+ // for [k, v] of Object.entries(o) for const x of arr { }
878
+ // for i from 0 to n { }
879
+ // for (const x of arr) { } for (const k in obj) { } (keys)
880
+ // for (let i = 0, n = a.length; i < n; i++) { }
712
881
  parseForStatement() {
713
- const varName = this.expect(
714
- TokenType.IDENTIFIER,
715
- "Expected a loop variable name after 'for'",
716
- ).value
882
+ if (this.check(TokenType.LPAREN)) {
883
+ return this.parseParenFor()
884
+ }
717
885
 
718
- if (this.match(TokenType.IN)) {
886
+ let declKind = 'const'
887
+ if (this.check(TokenType.CONST) || this.check(TokenType.LET)) {
888
+ declKind = this.advance().type === TokenType.CONST ? 'const' : 'let'
889
+ }
890
+
891
+ let varName
892
+ if (this.check(TokenType.LBRACKET) || this.check(TokenType.LBRACE)) {
893
+ varName = this.parseBindingTarget()
894
+ } else {
895
+ varName = this.expect(
896
+ TokenType.IDENTIFIER,
897
+ "Expected a loop variable name after 'for'",
898
+ ).value
899
+ }
900
+
901
+ if (this.match(TokenType.IN) || this.match(TokenType.OF)) {
719
902
  const iterable = this.parseExpression()
720
- this.expect(TokenType.LBRACE, "Expected '{' to start the loop body")
721
- const body = []
722
- while (!this.check(TokenType.RBRACE)) {
723
- body.push(this.parseStatement())
724
- }
725
- this.expect(TokenType.RBRACE, "Expected '}' to close the loop body")
726
- return ForInStatement(varName, iterable, body)
903
+ const body = this.parseBlockStatements('loop body')
904
+ return ForInStatement(varName, iterable, body, declKind)
727
905
  }
728
906
 
729
907
  if (this.match(TokenType.FROM)) {
908
+ if (typeof varName !== 'string') {
909
+ throw new Error(
910
+ `'for ... from ... to' needs a plain loop variable at line ${this.peek().line}`,
911
+ )
912
+ }
730
913
  const start = this.parseExpression()
731
914
  this.expect(TokenType.TO, "Expected 'to' after the loop's starting value")
732
915
  const end = this.parseExpression()
733
- this.expect(TokenType.LBRACE, "Expected '{' to start the loop body")
734
- const body = []
735
- while (!this.check(TokenType.RBRACE)) {
736
- body.push(this.parseStatement())
737
- }
738
- this.expect(TokenType.RBRACE, "Expected '}' to close the loop body")
916
+ const body = this.parseBlockStatements('loop body')
739
917
  return ForRangeStatement(varName, start, end, body)
740
918
  }
741
919
 
742
920
  throw new Error(
743
- `Expected 'in' or 'from' after 'for ${varName}' at line ${this.peek().line}`,
921
+ `Expected 'in', 'of' or 'from' after 'for ${typeof varName === 'string' ? varName : '...'}' at line ${this.peek().line}`,
744
922
  )
745
923
  }
746
924
 
925
+ parseParenFor() {
926
+ this.expect(TokenType.LPAREN, "Expected '(' after 'for'")
927
+
928
+ let init = null
929
+ if (this.check(TokenType.SEMICOLON)) {
930
+ // no init
931
+ } else if (this.check(TokenType.CONST) || this.check(TokenType.LET)) {
932
+ const kind = this.advance().type === TokenType.CONST ? 'const' : 'let'
933
+ const target = this.parseBindingTarget()
934
+
935
+ if (this.check(TokenType.OF) || this.check(TokenType.IN)) {
936
+ const isOf = this.advance().type === TokenType.OF
937
+ const iterable = this.parseExpression()
938
+ this.expect(TokenType.RPAREN, "Expected ')' after the for header")
939
+ const body = this.parseBlockStatements('loop body')
940
+ return isOf
941
+ ? ForInStatement(target, iterable, body, kind)
942
+ : ForKeysStatement(target, iterable, body, kind)
943
+ }
944
+
945
+ // C-style declaration: re-enter declarator parsing with the
946
+ // target we already consumed.
947
+ let first = null
948
+ if (this.match(TokenType.EQUALS)) {
949
+ first = this.parseExpression()
950
+ } else if (kind === 'const') {
951
+ throw new Error(
952
+ `Missing initializer in const declaration at line ${this.peek().line}`,
953
+ )
954
+ }
955
+ const more = []
956
+ while (this.match(TokenType.COMMA)) {
957
+ const name = this.parseBindingTarget()
958
+ let moreInit = null
959
+ if (this.match(TokenType.EQUALS)) moreInit = this.parseExpression()
960
+ more.push({ name, init: moreInit })
961
+ }
962
+ init = VariableDeclaration(kind, target, first, more)
963
+ } else {
964
+ const expressions = [this.parseExpression()]
965
+ while (this.match(TokenType.COMMA)) {
966
+ expressions.push(this.parseExpression())
967
+ }
968
+ init = { type: 'ExpressionList', expressions }
969
+ }
970
+
971
+ this.expect(TokenType.SEMICOLON, "Expected ';' after the for-loop init")
972
+ const test = this.check(TokenType.SEMICOLON) ? null : this.parseExpression()
973
+ this.expect(TokenType.SEMICOLON, "Expected ';' after the for-loop condition")
974
+
975
+ const update = []
976
+ if (!this.check(TokenType.RPAREN)) {
977
+ update.push(this.parseExpression())
978
+ while (this.match(TokenType.COMMA)) {
979
+ update.push(this.parseExpression())
980
+ }
981
+ }
982
+ this.expect(TokenType.RPAREN, "Expected ')' to close the for header")
983
+
984
+ const body = this.parseBlockStatements('loop body')
985
+ return ForStatement(init, test, update, body)
986
+ }
987
+
747
988
  parseRepeatStatement() {
748
989
  const count = this.parseExpression()
749
990
  this.expect(TokenType.LBRACE, "Expected '{' to start the repeat body")
@@ -798,6 +1039,54 @@ export class Parser {
798
1039
  return this.parseAssignment()
799
1040
  }
800
1041
 
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 }
1052
+ }
1053
+ if (a.type === TokenType.GT && b.type === TokenType.GTE && adjacent(a, b)) {
1054
+ return { op: '>>', len: 2 }
1055
+ }
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 }
1065
+ }
1066
+ return null
1067
+ }
1068
+
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
1088
+ }
1089
+
801
1090
  parseAssignment() {
802
1091
  const arrow = this.tryParseArrowFunction()
803
1092
  if (arrow) return arrow
@@ -814,6 +1103,16 @@ export class Parser {
814
1103
  return AssignmentExpr(left, NullishCoalescingExpr(left, value))
815
1104
  }
816
1105
 
1106
+ if (this.match(TokenType.OR_EQUALS)) {
1107
+ const value = this.parseAssignment()
1108
+ return AssignmentExpr(left, BinaryExpr('||', left, value))
1109
+ }
1110
+
1111
+ if (this.match(TokenType.AND_EQUALS)) {
1112
+ const value = this.parseAssignment()
1113
+ return AssignmentExpr(left, BinaryExpr('&&', left, value))
1114
+ }
1115
+
817
1116
  const compoundOp = COMPOUND_ASSIGNMENT_OPS[this.peek().type]
818
1117
 
819
1118
  if (compoundOp) {
@@ -822,6 +1121,13 @@ export class Parser {
822
1121
  return AssignmentExpr(left, BinaryExpr(compoundOp, left, value))
823
1122
  }
824
1123
 
1124
+ const shiftAssign = this.compoundShiftAt()
1125
+ if (shiftAssign) {
1126
+ this.pos += shiftAssign.len
1127
+ const value = this.parseAssignment()
1128
+ return AssignmentExpr(left, BinaryExpr(shiftAssign.op, left, value))
1129
+ }
1130
+
825
1131
  return left
826
1132
  }
827
1133
 
@@ -839,6 +1145,19 @@ export class Parser {
839
1145
  }
840
1146
  }
841
1147
 
1148
+ // Speculatively parses a destructuring pattern used as an arrow
1149
+ // parameter and returns its source text ("[k, v]", "{ id, name }"),
1150
+ // or null (position restored) if it isn't a valid param pattern.
1151
+ tryParseDestructuredParam() {
1152
+ const savedPos = this.pos
1153
+ try {
1154
+ return bindingToSource(this.parseBindingTarget())
1155
+ } catch {
1156
+ this.pos = savedPos
1157
+ return null
1158
+ }
1159
+ }
1160
+
842
1161
  // After `=>`: either a block body or a single expression.
843
1162
  //
844
1163
  // A `{` after `=>` is a BLOCK (JS semantics), except when the
@@ -846,9 +1165,10 @@ export class Parser {
846
1165
  // `{ key: value }`, `{ a, b }` -- in which case it's an object
847
1166
  // literal, so the older `x => { id: x }` style keeps working. A
848
1167
  // block can't legally start with `name :` (no labels) or `name ,`
849
- // (no comma operator), so the lookahead is unambiguous. The two
850
- // cases it can't resolve are `{}` and `{ name }`; those are blocks,
851
- // exactly as in JS. Write `({})` / `({ name })` for an object.
1168
+ // (no comma operator), so the lookahead is unambiguous. The cases it
1169
+ // can't resolve are `{}`, `{ name }`, `{ [key]: v }` and
1170
+ // `{ method() {} }`; those are blocks, exactly as in JS. Wrap an
1171
+ // object literal in parentheses: `x => ({ ... })`.
852
1172
  parseArrowBody() {
853
1173
  if (this.check(TokenType.LBRACE) && !this.looksLikeObjectLiteral()) {
854
1174
  return BlockStatement(this.parseBlockStatements('arrow function body'))
@@ -863,6 +1183,7 @@ export class Parser {
863
1183
  if (first.type === TokenType.SPREAD) return true
864
1184
  const isKey =
865
1185
  first.type === TokenType.STRING ||
1186
+ first.type === TokenType.NUMBER ||
866
1187
  first.type === TokenType.IDENTIFIER ||
867
1188
  KEYWORD_TOKEN_TYPES.has(first.type)
868
1189
  return (
@@ -910,6 +1231,10 @@ export class Parser {
910
1231
  // expression. The body is an expression or, via parseArrowBody, a
911
1232
  // `{ ... }` statement block (script code only -- templates reject
912
1233
  // BlockStatement in their expression generators).
1234
+ //
1235
+ // 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).
913
1238
  tryParseSyncArrow() {
914
1239
  // single-param form: x => expr or x: Type => expr
915
1240
  if (
@@ -921,7 +1246,7 @@ export class Parser {
921
1246
  const param = this.advance().value
922
1247
  this.advance() // consume '=>'
923
1248
  const body = this.parseArrowBody()
924
- return ArrowFunctionExpr([param], body, [null])
1249
+ return ArrowFunctionExpr([param], body, [null], false, [null])
925
1250
  }
926
1251
  if (next && next.type === TokenType.COLON) {
927
1252
  const savedPos = this.pos
@@ -931,7 +1256,7 @@ export class Parser {
931
1256
  if (paramType !== null && this.check(TokenType.ARROW)) {
932
1257
  this.advance()
933
1258
  const body = this.parseArrowBody()
934
- return ArrowFunctionExpr([param], body, [paramType])
1259
+ return ArrowFunctionExpr([param], body, [paramType], false, [null])
935
1260
  }
936
1261
  // wasn't actually a typed arrow param (e.g. the `x : y` part
937
1262
  // of a ternary) -- back out
@@ -940,25 +1265,45 @@ export class Parser {
940
1265
  return null
941
1266
  }
942
1267
 
943
- // (a, b) => expr or (a: Type, b: Type) => expr
1268
+ // (a, b) => expr or (a: Type, b = 1, ...rest) => expr
1269
+ // also ([k, v]) => expr, ({ id }) => expr
944
1270
  if (this.check(TokenType.LPAREN)) {
945
1271
  const savedPos = this.pos
946
1272
  this.pos++
947
1273
 
948
1274
  const params = []
949
1275
  const paramTypes = []
1276
+ const paramDefaults = []
950
1277
  let isValidParamList = true
951
1278
 
952
1279
  if (!this.check(TokenType.RPAREN)) {
953
1280
  while (true) {
954
- if (
955
- !this.check(TokenType.IDENTIFIER) &&
956
- !KEYWORD_TOKEN_TYPES.has(this.peek().type)
1281
+ let name
1282
+ if (this.match(TokenType.SPREAD)) {
1283
+ if (!this.check(TokenType.IDENTIFIER)) {
1284
+ isValidParamList = false
1285
+ break
1286
+ }
1287
+ name = `...${this.advance().value}`
1288
+ } else if (
1289
+ this.check(TokenType.LBRACKET) ||
1290
+ this.check(TokenType.LBRACE)
1291
+ ) {
1292
+ name = this.tryParseDestructuredParam()
1293
+ if (name === null) {
1294
+ isValidParamList = false
1295
+ break
1296
+ }
1297
+ } else if (
1298
+ this.check(TokenType.IDENTIFIER) ||
1299
+ KEYWORD_TOKEN_TYPES.has(this.peek().type)
957
1300
  ) {
1301
+ name = this.advance().value
1302
+ } else {
958
1303
  isValidParamList = false
959
1304
  break
960
1305
  }
961
- params.push(this.advance().value)
1306
+ params.push(name)
962
1307
 
963
1308
  let paramType = null
964
1309
  if (this.match(TokenType.COLON)) {
@@ -970,6 +1315,17 @@ export class Parser {
970
1315
  }
971
1316
  paramTypes.push(paramType)
972
1317
 
1318
+ let defaultValue = null
1319
+ if (this.match(TokenType.EQUALS)) {
1320
+ try {
1321
+ defaultValue = this.parseAssignment()
1322
+ } catch {
1323
+ isValidParamList = false
1324
+ break
1325
+ }
1326
+ }
1327
+ paramDefaults.push(defaultValue)
1328
+
973
1329
  if (this.match(TokenType.COMMA)) continue
974
1330
  break
975
1331
  }
@@ -980,7 +1336,7 @@ export class Parser {
980
1336
  if (this.check(TokenType.ARROW)) {
981
1337
  this.pos++
982
1338
  const body = this.parseArrowBody()
983
- return ArrowFunctionExpr(params, body, paramTypes)
1339
+ return ArrowFunctionExpr(params, body, paramTypes, false, paramDefaults)
984
1340
  }
985
1341
  }
986
1342
 
@@ -1019,11 +1375,53 @@ export class Parser {
1019
1375
  return left
1020
1376
  }
1021
1377
 
1022
- parseLogicalAnd() {
1378
+ parseLogicalAnd() {
1379
+ let left = this.parseNotOperand()
1380
+ while (this.match(TokenType.AND)) {
1381
+ const right = this.parseNotOperand()
1382
+ left = BinaryExpr('&&', left, right)
1383
+ }
1384
+ return left
1385
+ }
1386
+
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())
1398
+ }
1399
+ return this.parseBitwiseOr()
1400
+ }
1401
+
1402
+ parseBitwiseOr() {
1403
+ let left = this.parseBitwiseXor()
1404
+ while (this.match(TokenType.PIPE)) {
1405
+ const right = this.parseBitwiseXor()
1406
+ left = BinaryExpr('|', left, right)
1407
+ }
1408
+ return left
1409
+ }
1410
+
1411
+ parseBitwiseXor() {
1412
+ let left = this.parseBitwiseAnd()
1413
+ while (this.match(TokenType.CARET)) {
1414
+ const right = this.parseBitwiseAnd()
1415
+ left = BinaryExpr('^', left, right)
1416
+ }
1417
+ return left
1418
+ }
1419
+
1420
+ parseBitwiseAnd() {
1023
1421
  let left = this.parseEquality()
1024
- while (this.match(TokenType.AND)) {
1422
+ while (this.match(TokenType.AMP)) {
1025
1423
  const right = this.parseEquality()
1026
- left = BinaryExpr('&&', left, right)
1424
+ left = BinaryExpr('&', left, right)
1027
1425
  }
1028
1426
  return left
1029
1427
  }
@@ -1041,7 +1439,9 @@ export class Parser {
1041
1439
 
1042
1440
  parseComparison() {
1043
1441
  let left = this.parsePredicate()
1044
- while (COMPARISON_SYMBOLS[this.peek().type]) {
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()) {
1045
1445
  const operator = COMPARISON_SYMBOLS[this.advance().type]
1046
1446
  const right = this.parsePredicate()
1047
1447
  left = BinaryExpr(operator, left, right)
@@ -1050,7 +1450,7 @@ export class Parser {
1050
1450
  }
1051
1451
 
1052
1452
  parsePredicate() {
1053
- const left = this.parseAdditive()
1453
+ const left = this.parseShift()
1054
1454
 
1055
1455
  if (this.match(TokenType.EXISTS)) {
1056
1456
  return BinaryExpr('!=', left, Literal(null))
@@ -1059,13 +1459,24 @@ export class Parser {
1059
1459
  return BinaryExpr('==', left, Literal(null))
1060
1460
  }
1061
1461
  if (this.match(TokenType.HAS)) {
1062
- const right = this.parseAdditive()
1462
+ const right = this.parseShift()
1063
1463
  return CallExpr(MemberExpr(left, 'includes'), [right])
1064
1464
  }
1065
1465
 
1066
1466
  return left
1067
1467
  }
1068
1468
 
1469
+ parseShift() {
1470
+ let left = this.parseAdditive()
1471
+ let shift
1472
+ while ((shift = this.shiftOperatorAt())) {
1473
+ this.pos += shift.len
1474
+ const right = this.parseAdditive()
1475
+ left = BinaryExpr(shift.op, left, right)
1476
+ }
1477
+ return left
1478
+ }
1479
+
1069
1480
  parseAdditive() {
1070
1481
  let left = this.parseMultiplicative()
1071
1482
  while (ADDITIVE_SYMBOLS[this.peek().type]) {
@@ -1105,12 +1516,21 @@ export class Parser {
1105
1516
  if (this.match(TokenType.NOT)) {
1106
1517
  return UnaryExpr('!', this.parseUnary())
1107
1518
  }
1519
+ if (this.match(TokenType.TILDE)) {
1520
+ return UnaryExpr('~', this.parseUnary())
1521
+ }
1108
1522
  if (this.match(TokenType.MINUS)) {
1109
1523
  return UnaryExpr('-', this.parseUnary())
1110
1524
  }
1111
1525
  if (this.match(TokenType.TYPEOF)) {
1112
1526
  return UnaryExpr('typeof', this.parseUnary())
1113
1527
  }
1528
+ if (this.match(TokenType.DELETE)) {
1529
+ return UnaryExpr('delete', this.parseUnary())
1530
+ }
1531
+ if (this.match(TokenType.VOID)) {
1532
+ return UnaryExpr('void', this.parseUnary())
1533
+ }
1114
1534
  if (this.match(TokenType.PLUS_PLUS)) {
1115
1535
  const target = this.parseUnary()
1116
1536
  return AssignmentExpr(target, BinaryExpr('+', target, Literal(1)))
@@ -1192,77 +1612,105 @@ export class Parser {
1192
1612
  return args
1193
1613
  }
1194
1614
 
1195
- parsePrimary() {
1196
- if (this.match(TokenType.NEW)) {
1197
- let callee = this.parsePrimary()
1198
- while (this.match(TokenType.DOT)) {
1199
- const property = this.expect(
1200
- TokenType.IDENTIFIER,
1201
- "Expected a property name after '.'",
1202
- ).value
1203
- callee = MemberExpr(callee, property)
1204
- }
1205
- let args = []
1206
- if (this.check(TokenType.LPAREN)) {
1207
- args = this.parseCallArguments()
1208
- }
1209
- return NewExpr(callee, args)
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)
1210
1624
  }
1211
-
1212
- if (this.check(TokenType.NUMBER) || this.check(TokenType.STRING)) {
1213
- return Literal(this.advance().value)
1625
+ let args = []
1626
+ if (this.check(TokenType.LPAREN)) {
1627
+ args = this.parseCallArguments()
1214
1628
  }
1629
+ return NewExpr(callee, args)
1630
+ }
1631
+
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
+ }
1215
1638
 
1216
- if (this.check(TokenType.TEMPLATE_LITERAL)) {
1217
- const rawParts = this.advance().value
1218
- const parts = rawParts.map((p) =>
1219
- p.type === 'text'
1220
- ? p
1221
- : { type: 'expr', expression: parseExpressionString(p.source) },
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}`,
1222
1649
  )
1223
- return TemplateLiteralExpr(parts)
1224
1650
  }
1651
+ }
1225
1652
 
1226
- if (
1227
- this.check(TokenType.IDENTIFIER) ||
1228
- KEYWORD_TOKEN_TYPES.has(this.peek().type)
1229
- ) {
1230
- const name = this.advance().value
1231
- // "null"/"true"/"false"/"undefined" are lexed as plain identifier
1232
- // tokens (there's no separate keyword TokenType for them), but
1233
- // they're JS keyword literals, not variable/state references.
1234
- // Emitting them as Literal here -- instead of Identifier -- means
1235
- // every downstream consumer (generateExpression,
1236
- // generateTemplateExpression, and anything added later) treats
1237
- // them correctly by construction, rather than each one needing its
1238
- // own special-case list of magic strings to avoid prefixing them
1239
- // with "instance.".
1240
- if (name === 'null') return Literal(null)
1241
- if (name === 'undefined') return Literal(undefined)
1242
- if (name === 'true') return Literal(true)
1243
- if (name === 'false') return Literal(false)
1244
- return Identifier(name)
1245
- }
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
+ }
1246
1659
 
1247
- if (this.match(TokenType.LPAREN)) {
1248
- const expr = this.parseExpression()
1249
- this.expect(
1250
- TokenType.RPAREN,
1251
- "Expected ')' to close a grouped expression",
1252
- )
1253
- return expr
1254
- }
1255
- if (this.match(TokenType.LBRACE)) {
1256
- return this.parseObjectLiteral()
1257
- }
1258
- if (this.match(TokenType.LBRACKET)) {
1259
- return this.parseArrayLiteral()
1260
- }
1261
- throw new Error(
1262
- `Unexpected token ${this.peek().type} at line ${this.peek().line}`,
1660
+ if (this.check(TokenType.NUMBER) || this.check(TokenType.STRING)) {
1661
+ return Literal(this.advance().value)
1662
+ }
1663
+
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
+ },
1263
1675
  )
1676
+ return TemplateLiteralExpr(parts)
1677
+ }
1678
+
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)
1264
1694
  }
1265
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",
1701
+ )
1702
+ return expr
1703
+ }
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
+ }
1266
1714
  // Type expressions are captured as plain strings, not a full type
1267
1715
  // AST -- Tylix's own codegen never interprets them, it only needs
1268
1716
  // the exact TS source text to paste into the virtual .ts file handed
@@ -1350,12 +1798,18 @@ export class Parser {
1350
1798
  return ArrayExpr(elements)
1351
1799
  }
1352
1800
 
1801
+ // Object literal after the opening '{'. Supports:
1802
+ // { a: 1, "b-c": 2, 3: 'x' } plain / string / number keys
1803
+ // { name } shorthand
1804
+ // { ...base } spread
1805
+ // { [expr]: value } computed keys
1806
+ // { save(x) { ... } } method shorthand
1807
+ // { async load() { ... } } async method shorthand
1353
1808
  parseObjectLiteral() {
1354
1809
  const properties = []
1355
1810
  while (!this.check(TokenType.RBRACE)) {
1356
- // Object spread: { ...base, extra: 1 }. Represented as a
1357
- // property with `spread: true` and no key, so codegen must check
1358
- // `p.spread` before reading `p.key`.
1811
+ // Object spread: represented as a property with `spread: true`
1812
+ // and no key, so codegen must check `p.spread` first.
1359
1813
  if (this.match(TokenType.SPREAD)) {
1360
1814
  properties.push({
1361
1815
  key: null,
@@ -1366,16 +1820,73 @@ export class Parser {
1366
1820
  continue
1367
1821
  }
1368
1822
 
1369
- const isString = this.check(TokenType.STRING)
1370
- const isKeywordKey =
1371
- !isString && KEYWORD_TOKEN_TYPES.has(this.peek().type)
1372
- const key = isString
1373
- ? this.advance().value
1374
- : isKeywordKey
1375
- ? this.advance().value
1376
- : this.expect(TokenType.IDENTIFIER, 'Expected an object key').value
1823
+ // `async name(...) { }` -- but `async: x`, `async,` and `async()`
1824
+ // are ordinary keys/methods named "async".
1825
+ let isAsync = false
1826
+ if (this.check(TokenType.ASYNC)) {
1827
+ const n = this.tokens[this.pos + 1]
1828
+ if (
1829
+ n &&
1830
+ n.type !== TokenType.COLON &&
1831
+ n.type !== TokenType.COMMA &&
1832
+ n.type !== TokenType.RBRACE &&
1833
+ n.type !== TokenType.LPAREN
1834
+ ) {
1835
+ this.advance()
1836
+ isAsync = true
1837
+ }
1838
+ }
1839
+
1840
+ let key = null
1841
+ let keyExpr = null
1842
+ let keyKind = 'name'
1843
+ if (this.match(TokenType.LBRACKET)) {
1844
+ keyExpr = this.parseExpression()
1845
+ this.expect(
1846
+ TokenType.RBRACKET,
1847
+ "Expected ']' to close a computed object key",
1848
+ )
1849
+ keyKind = 'computed'
1850
+ } else if (this.check(TokenType.STRING)) {
1851
+ key = this.advance().value
1852
+ keyKind = 'string'
1853
+ } else if (this.check(TokenType.NUMBER)) {
1854
+ key = String(this.advance().value)
1855
+ keyKind = 'number'
1856
+ } else if (
1857
+ this.check(TokenType.IDENTIFIER) ||
1858
+ KEYWORD_TOKEN_TYPES.has(this.peek().type)
1859
+ ) {
1860
+ key = this.advance().value
1861
+ } else {
1862
+ throw new Error(
1863
+ `Expected an object key at line ${this.peek().line}, got ${this.peek().type}`,
1864
+ )
1865
+ }
1866
+
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
+ })
1879
+ this.match(TokenType.COMMA)
1880
+ continue
1881
+ }
1882
+
1883
+ if (isAsync) {
1884
+ throw new Error(
1885
+ `Expected '(' after async method name at line ${this.peek().line}`,
1886
+ )
1887
+ }
1377
1888
 
1378
- if (!isString && !this.check(TokenType.COLON)) {
1889
+ if (keyKind === 'name' && !this.check(TokenType.COLON)) {
1379
1890
  // Shorthand: { name } means { name: name }
1380
1891
  properties.push({ key, value: Identifier(key) })
1381
1892
  this.match(TokenType.COMMA)
@@ -1384,7 +1895,7 @@ export class Parser {
1384
1895
 
1385
1896
  this.expect(TokenType.COLON, "Expected ':' after object key")
1386
1897
  const value = this.parseExpression()
1387
- properties.push({ key, value })
1898
+ properties.push({ key, keyExpr, value })
1388
1899
  this.match(TokenType.COMMA)
1389
1900
  }
1390
1901
  this.expect(TokenType.RBRACE, "Expected '}' to close object literal")