@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
@@ -1,33 +1,101 @@
1
1
  import { generateStatement } from './generateStatement.js'
2
2
 
3
3
  // Note: generateStatement.js imports generateExpression and this file
4
- // imports generateStatement (block-bodied arrows and function
5
- // expressions need it). That circular import is safe in ES modules
6
- // because both are hoisted function declarations only called at
7
- // runtime, never at load time.
4
+ // imports generateStatement (block-bodied arrows, function expressions
5
+ // and class bodies need it). That circular import is safe in ES
6
+ // modules because both are hoisted function declarations only called
7
+ // at runtime, never at load time.
8
8
 
9
9
  // Word operators (typeof, delete, void) need a space before their
10
- // operand; symbolic ones (!, ~, -) must not get one.
10
+ // operand; symbolic ones (!, ~, -, +) must not get one.
11
11
  function unaryPrefix(operator) {
12
12
  return /^[a-z]/i.test(operator) ? `${operator} ` : operator
13
13
  }
14
14
 
15
+ // Joins array-literal element sources. A hole is an empty string, and
16
+ // a trailing hole needs one extra comma to keep the array's length
17
+ // (`[1, ,]` has length 2).
18
+ export function joinArrayElements(parts) {
19
+ const joined = parts.join(', ')
20
+ return parts.length > 0 && parts[parts.length - 1] === ''
21
+ ? `${joined},`
22
+ : joined
23
+ }
24
+
25
+ // `5.toFixed(1)` is a syntax error; `(5).toFixed(1)` is not.
26
+ function memberObjectSource(node, typed) {
27
+ const src = generateExpression(node, typed)
28
+ return node.type === 'Literal' && typeof node.value === 'number'
29
+ ? `(${src})`
30
+ : src
31
+ }
32
+
33
+ // Renders an object/array literal used as a destructuring ASSIGNMENT
34
+ // target (`[a = 1, b] = arr`, `({ x, y = 2 } = obj)`). In a pattern, a
35
+ // default is `target = value` without the parentheses an ordinary
36
+ // assignment expression gets. `gen` renders ordinary expressions, so
37
+ // the script, template and virtual-.ts generators can all share this.
38
+ export function assignmentPatternSource(node, gen) {
39
+ const pat = (n) => assignmentPatternSource(n, gen)
40
+ if (node.type === 'ArrayExpression') {
41
+ return `[${joinArrayElements(node.elements.map((e) => (e === null ? '' : pat(e))))}]`
42
+ }
43
+ if (node.type === 'ObjectExpression') {
44
+ const parts = node.properties.map((p) => {
45
+ if (p.spread) return `...${pat(p.value)}`
46
+ if (p.method) {
47
+ throw new Error('Methods are not allowed in a destructuring assignment target')
48
+ }
49
+ const keySrc = p.keyExpr ? `[${gen(p.keyExpr)}]` : JSON.stringify(p.key)
50
+ return `${keySrc}: ${pat(p.value)}`
51
+ })
52
+ return `{ ${parts.join(', ')} }`
53
+ }
54
+ if (node.type === 'SpreadElement') return `...${pat(node.argument)}`
55
+ if (node.type === 'AssignmentExpression') {
56
+ return `${pat(node.target)} = ${gen(node.value)}`
57
+ }
58
+ return gen(node)
59
+ }
60
+
61
+ // Generic parameters and return type text for functions, virtual .ts
62
+ // only. Async functions are written with the INNER type (like
63
+ // methods), so it is wrapped in Promise<>; generators are left alone.
64
+ export function functionSignature(node, typed) {
65
+ if (!typed) return { generics: '', ret: '' }
66
+ const generics = node.typeParams ?? ''
67
+ let ret = ''
68
+ if (node.returnType && !node.isGenerator) {
69
+ ret = `: ${node.isAsync ? `Promise<${node.returnType}>` : node.returnType}`
70
+ }
71
+ return { generics, ret }
72
+ }
73
+
15
74
  /**
16
- * Renders a parameter list: [{ name, typeAnnotation, defaultValue, rest }].
17
- * `typed` adds `: Type` annotations (falling back to `any`, or `any[]`
18
- * for rest params) for the virtual .ts file; real JS output omits them.
75
+ * Renders a parameter list: [{ name, typeAnnotation, defaultValue,
76
+ * rest, optional }]. `typed` adds `: Type` annotations (falling back
77
+ * to `any`, or `any[]` for rest params) and `?` for optional params
78
+ * for the virtual .ts file; real JS output omits them. An optional
79
+ * param with a default gets no `?` (TypeScript forbids both).
19
80
  */
20
81
  export function generateParams(params, typed = false) {
21
82
  return params
22
83
  .map((p) => {
23
84
  const rest = p.rest ? '...' : ''
85
+ const optional = typed && p.optional && !p.defaultValue ? '?' : ''
24
86
  const type = typed
25
- ? `: ${p.typeAnnotation ?? (p.rest ? 'any[]' : 'any')}`
87
+ ? `${optional}: ${p.typeAnnotation ?? (p.rest ? 'any[]' : 'any')}`
26
88
  : ''
27
89
  const def = p.defaultValue
28
90
  ? ` = ${generateExpression(p.defaultValue, typed)}`
29
91
  : ''
30
- return `${rest}${p.name}${type}${def}`
92
+ // Parameter-property modifiers stay for the checker; JS gets
93
+ // explicit `this.x = x` assignments instead (classMemberSource).
94
+ const mods =
95
+ typed && p.isProperty
96
+ ? `${p.accessibility ? `${p.accessibility} ` : ''}${p.isOverride ? 'override ' : ''}${p.isReadonly ? 'readonly ' : ''}`
97
+ : ''
98
+ return `${mods}${rest}${p.name}${type}${def}`
31
99
  })
32
100
  .join(', ')
33
101
  }
@@ -36,6 +104,113 @@ function statementsInline(body, typed) {
36
104
  return body.map((s) => generateStatement(s, typed)).join(' ')
37
105
  }
38
106
 
107
+ function classMemberSource(m, typed) {
108
+ if (m.kind === 'staticBlock') {
109
+ return `static { ${statementsInline(m.body, typed)} }`
110
+ }
111
+
112
+ // Modifiers: accessibility / override / readonly exist only in the
113
+ // virtual .ts; real JS keeps just `static`.
114
+ // Abstract members, `declare` fields and overload signatures carry no
115
+ // runtime code; they exist only in the virtual .ts.
116
+ const isSignature = m.kind !== 'field' && m.body == null
117
+ if (!typed && (m.isAbstract || m.isDeclare || isSignature)) return null
118
+
119
+ const stat = m.static ? 'static ' : ''
120
+ const mods = typed
121
+ ? `${m.isDeclare ? 'declare ' : ''}${m.accessibility ? `${m.accessibility} ` : ''}${stat}${m.isAbstract ? 'abstract ' : ''}${m.isOverride ? 'override ' : ''}${m.isReadonly ? 'readonly ' : ''}`
122
+ : stat
123
+ const keySrc =
124
+ m.keyKind === 'computed'
125
+ ? `[${generateExpression(m.keyExpr, typed)}]`
126
+ : m.keyKind === 'string'
127
+ ? JSON.stringify(m.key)
128
+ : m.key // plain names (including #private) and number keys
129
+
130
+ if (m.kind === 'field') {
131
+ const init = m.value ? ` = ${generateExpression(m.value, typed)}` : ''
132
+ let annotation = ''
133
+ if (typed) {
134
+ const type = m.typeAnnotation ?? 'any'
135
+ // An instance field with no initializer needs `!` under strict;
136
+ // TypeScript forbids `!` on static, abstract and declare fields.
137
+ const definite = !m.value && !m.static && !m.isAbstract && !m.isDeclare
138
+ annotation = definite ? `!: ${type}` : `: ${type}`
139
+ }
140
+ return `${mods}${keySrc}${annotation}${init};`
141
+ }
142
+
143
+ const generics = typed ? (m.typeParams ?? '') : ''
144
+ const params = generateParams(m.params, typed)
145
+ let ret = ''
146
+ if (typed && m.returnType && !m.isGenerator) {
147
+ ret = m.isAsync ? `: Promise<${m.returnType}>` : `: ${m.returnType}`
148
+ }
149
+
150
+ // Body-less (typed only, by the early return above): end with `;`.
151
+ if (isSignature) {
152
+ if (m.kind === 'constructor') return `constructor(${params});`
153
+ if (m.kind === 'get') return `${mods}get ${keySrc}()${ret};`
154
+ if (m.kind === 'set') return `${mods}set ${keySrc}(${params});`
155
+ return `${mods}${m.isAsync ? 'async ' : ''}${m.isGenerator ? '*' : ''}${keySrc}${generics}(${params})${ret};`
156
+ }
157
+
158
+ const body = statementsInline(m.body, typed)
159
+ if (m.kind === 'constructor') {
160
+ return `constructor(${params}) { ${typed ? body : withParamProperties(m, body, typed)} }`
161
+ }
162
+ if (m.kind === 'get') return `${mods}get ${keySrc}()${ret} { ${body} }`
163
+ if (m.kind === 'set') return `${mods}set ${keySrc}(${params}) { ${body} }`
164
+ return `${mods}${m.isAsync ? 'async ' : ''}${m.isGenerator ? '*' : ''}${keySrc}${generics}(${params})${ret} { ${body} }`
165
+ }
166
+
167
+ // JS for `constructor(public x)`: assign `this.x = x` right after the
168
+ // top-level `super(...)` call when there is one (before it `this` is
169
+ // unusable), otherwise at the very start, matching TypeScript.
170
+ function withParamProperties(m, body, typed) {
171
+ const props = m.params.filter((p) => p.isProperty)
172
+ if (props.length === 0) return body
173
+ const assigns = props.map((p) => `this.${p.name} = ${p.name};`).join(' ')
174
+ const superIdx = m.body.findIndex(
175
+ (s) =>
176
+ s.type === 'ExpressionStatement' &&
177
+ s.expression.type === 'CallExpression' &&
178
+ s.expression.callee.type === 'Identifier' &&
179
+ s.expression.callee.name === 'super',
180
+ )
181
+ if (superIdx === -1) return `${assigns} ${body}`
182
+ const before = statementsInline(m.body.slice(0, superIdx + 1), typed)
183
+ const after = statementsInline(m.body.slice(superIdx + 1), typed)
184
+ return `${before} ${assigns} ${after}`
185
+ }
186
+
187
+ /**
188
+ * Renders a ClassDeclaration / ClassExpression node. Statement form
189
+ * has no trailing semicolon; the expression form wraps it in parens
190
+ * in generateExpression. Generics, `implements` and member modifiers
191
+ * are emitted only in typed mode.
192
+ */
193
+ export function generateClass(node, typed = false) {
194
+ const name = node.name ? ` ${node.name}` : ''
195
+ const generics = typed ? (node.typeParams ?? '') : ''
196
+ let ext = ''
197
+ if (node.superClass) {
198
+ const args = typed && node.superTypeArgs ? `<${node.superTypeArgs}>` : ''
199
+ ext = ` extends ${generateExpression(node.superClass, typed)}${args}`
200
+ }
201
+ const impl = typed && node.implementsList ? ` implements ${node.implementsList}` : ''
202
+ const members = node.members
203
+ .map((m) => classMemberSource(m, typed))
204
+ .filter((src) => src !== null)
205
+ .map((src) => ` ${src}`)
206
+ // JS classes often create fields in the constructor (`this.n = n`).
207
+ // The index signature stops the checker from rejecting those, the
208
+ // same way the page class does.
209
+ if (typed) members.unshift(' [key: string]: any;')
210
+ const abstract = typed && node.isAbstract ? 'abstract ' : ''
211
+ return `${abstract}class${name}${generics}${ext}${impl} {\n${members.join('\n')}\n }`
212
+ }
213
+
39
214
  /**
40
215
  * Compiles a single expression AST node into a JS (or, when
41
216
  * typed=true, TypeScript) source string. Used both for method-body
@@ -44,11 +219,12 @@ function statementsInline(body, typed) {
44
219
  * (typed=true) -- one source of truth for expression -> source
45
220
  * translation, so the two outputs can never structurally drift from
46
221
  * each other. `typed` only changes whether parameters get `: Type`
47
- * annotations. Everything else emits identically either way.
222
+ * annotations and whether `as` / `!` / generics are kept. Everything
223
+ * else emits identically either way.
48
224
  *
49
- * `await` and assignment are always parenthesized: `(await f()).x`
50
- * and `ok && (count = count + 1)` are only valid JS with the parens,
51
- * and the extra pair is harmless at statement level.
225
+ * `await`, `yield` and assignment are always parenthesized:
226
+ * `(await f()).x` and `ok && (count = count + 1)` are only valid JS
227
+ * with the parens, and the extra pair is harmless at statement level.
52
228
  */
53
229
  export function generateExpression(node, typed = false) {
54
230
  switch (node.type) {
@@ -62,16 +238,17 @@ export function generateExpression(node, typed = false) {
62
238
 
63
239
  case 'MemberExpression':
64
240
  if (node.computed) {
65
- return `${generateExpression(node.object, typed)}${node.optional ? '?.' : ''}[${generateExpression(node.property, typed)}]`
241
+ return `${memberObjectSource(node.object, typed)}${node.optional ? '?.' : ''}[${generateExpression(node.property, typed)}]`
66
242
  }
67
- return `${generateExpression(node.object, typed)}${node.optional ? '?.' : '.'}${node.property}`
243
+ return `${memberObjectSource(node.object, typed)}${node.optional ? '?.' : '.'}${node.property}`
68
244
 
69
245
  case 'NullishCoalescingExpression':
70
246
  return `(${generateExpression(node.left, typed)} ?? ${generateExpression(node.right, typed)})`
71
247
 
72
248
  case 'NewExpression': {
73
249
  const args = node.args.map((a) => generateExpression(a, typed)).join(', ')
74
- return `new ${generateExpression(node.callee, typed)}(${args})`
250
+ const typeArgs = typed && node.typeArgs ? `<${node.typeArgs}>` : ''
251
+ return `new ${generateExpression(node.callee, typed)}${typeArgs}(${args})`
75
252
  }
76
253
 
77
254
  case 'BinaryExpression':
@@ -80,24 +257,52 @@ export function generateExpression(node, typed = false) {
80
257
  case 'UnaryExpression':
81
258
  return `(${unaryPrefix(node.operator)}${generateExpression(node.argument, typed)})`
82
259
 
260
+ case 'UpdateExpression': {
261
+ const arg = generateExpression(node.argument, typed)
262
+ return node.prefix ? `(${node.operator}${arg})` : `(${arg}${node.operator})`
263
+ }
264
+
83
265
  case 'TernaryExpression':
84
266
  return `(${generateExpression(node.condition, typed)} ? ${generateExpression(node.consequent, typed)} : ${generateExpression(node.alternate, typed)})`
85
267
 
268
+ // `(a, b, c)` -- the comma operator.
269
+ case 'SequenceExpression':
270
+ return `(${node.expressions.map((e) => generateExpression(e, typed)).join(', ')})`
271
+
272
+ // `x as T`, `x satisfies T` and `x!` exist only for the
273
+ // TypeScript checker; in real JS output they reduce to the inner
274
+ // expression.
275
+ case 'AsExpression':
276
+ return typed
277
+ ? `(${generateExpression(node.expression, typed)} ${node.keyword ?? 'as'} ${node.typeAnnotation})`
278
+ : generateExpression(node.expression, typed)
279
+
280
+ case 'NonNullExpression':
281
+ return typed
282
+ ? `${generateExpression(node.expression, typed)}!`
283
+ : generateExpression(node.expression, typed)
284
+
86
285
  case 'ArrowFunctionExpression': {
87
286
  // paramTypes is a parallel array of type strings or null,
88
287
  // populated by tryParseSyncArrow when a dev writes
89
288
  // `f: Post => ...`; absent/null entries mean "no annotation
90
289
  // was written" -- in typed mode those fall back to `any`
91
- // rather than being left bare, since a bare untyped param in a
92
- // .ts arrow function has no implicit-any exemption the way
93
- // real JS does. paramDefaults is a parallel array of default
94
- // value expressions (or null).
290
+ // (`any[]` for a rest param) rather than being left bare,
291
+ // since a bare untyped param in a .ts arrow function has no
292
+ // implicit-any exemption the way real JS does. paramDefaults and
293
+ // paramOptional are parallel arrays too (expression or null,
294
+ // boolean).
95
295
  const paramTypes = node.paramTypes ?? node.params.map(() => null)
96
296
  const paramDefaults = node.paramDefaults ?? node.params.map(() => null)
297
+ const paramOptional = node.paramOptional ?? node.params.map(() => false)
97
298
  const params = node.params
98
299
  .map((name, i) => {
99
300
  let out = name
100
- if (typed) out = `${name}: ${paramTypes[i] ?? 'any'}`
301
+ if (typed) {
302
+ const fallback = name.startsWith('...') ? 'any[]' : 'any'
303
+ const optional = paramOptional[i] && !paramDefaults[i] ? '?' : ''
304
+ out = `${name}${optional}: ${paramTypes[i] ?? fallback}`
305
+ }
101
306
  if (paramDefaults[i]) {
102
307
  out += ` = ${generateExpression(paramDefaults[i], typed)}`
103
308
  }
@@ -105,23 +310,37 @@ export function generateExpression(node, typed = false) {
105
310
  })
106
311
  .join(', ')
107
312
  const asyncPrefix = node.isAsync ? 'async ' : ''
313
+ const generics = typed ? (node.typeParams ?? '') : ''
314
+ const returnType =
315
+ typed && node.returnType ? `: ${node.returnType}` : ''
108
316
 
109
317
  // Block body: `x => { stmt stmt }`. Statements are emitted on
110
318
  // one line separated by spaces; multi-line statements (if,
111
319
  // for, try) keep their own newlines, which is still valid JS.
112
320
  if (node.body.type === 'BlockStatement') {
113
- return `${asyncPrefix}(${params}) => { ${statementsInline(node.body.body, typed)} }`
321
+ return `${asyncPrefix}${generics}(${params})${returnType} => { ${statementsInline(node.body.body, typed)} }`
114
322
  }
115
323
 
116
324
  // Expression body is always parenthesized so an object literal
117
325
  // body (`x => ({ ...x })`) is never parsed as a block.
118
- return `${asyncPrefix}(${params}) => (${generateExpression(node.body, typed)})`
326
+ return `${asyncPrefix}${generics}(${params})${returnType} => (${generateExpression(node.body, typed)})`
119
327
  }
120
328
 
121
329
  case 'FunctionExpression': {
330
+ const { generics, ret } = functionSignature(node, typed)
122
331
  const asyncPrefix = node.isAsync ? 'async ' : ''
332
+ const star = node.isGenerator ? '*' : ''
123
333
  const name = node.name ? ` ${node.name}` : ''
124
- return `(${asyncPrefix}function${name}(${generateParams(node.params, typed)}) { ${statementsInline(node.body, typed)} })`
334
+ return `(${asyncPrefix}function${star}${name}${generics}(${generateParams(node.params, typed)})${ret} { ${statementsInline(node.body, typed)} })`
335
+ }
336
+
337
+ case 'ClassExpression':
338
+ return `(${generateClass(node, typed)})`
339
+
340
+ case 'YieldExpression': {
341
+ const star = node.delegate ? '*' : ''
342
+ const arg = node.argument ? ` ${generateExpression(node.argument, typed)}` : ''
343
+ return `(yield${star}${arg})`
125
344
  }
126
345
 
127
346
  case 'TemplateLiteralExpression': {
@@ -135,14 +354,42 @@ export function generateExpression(node, typed = false) {
135
354
  return `\`${inner}\``
136
355
  }
137
356
 
138
- case 'AssignmentExpression':
139
- return `(${generateExpression(node.target, typed)} = ${generateExpression(node.value, typed)})`
357
+ // tag`text ${x}`: text parts are emitted exactly as written
358
+ // (`raw`), so String.raw and custom tags see the original escapes.
359
+ case 'TaggedTemplateExpression': {
360
+ const inner = node.quasi.parts
361
+ .map((p) =>
362
+ p.type === 'text'
363
+ ? (p.raw ?? escapeTemplateText(p.value))
364
+ : `\${${generateExpression(p.expression, typed)}}`,
365
+ )
366
+ .join('')
367
+ return `${generateExpression(node.tag, typed)}\`${inner}\``
368
+ }
369
+
370
+ case 'AssignmentExpression': {
371
+ const isPattern =
372
+ node.target.type === 'ObjectExpression' ||
373
+ node.target.type === 'ArrayExpression'
374
+ const target = isPattern
375
+ ? assignmentPatternSource(node.target, (n) => generateExpression(n, typed))
376
+ : generateExpression(node.target, typed)
377
+ return `(${target} = ${generateExpression(node.value, typed)})`
378
+ }
140
379
 
141
380
  case 'CallExpression': {
142
381
  const args = node.args
143
382
  .map((a) => generateExpression(a, typed))
144
383
  .join(', ')
145
- return `${generateExpression(node.callee, typed)}${node.optional ? '?.' : ''}(${args})`
384
+ let callee = generateExpression(node.callee, typed)
385
+ // An arrow is not parenthesized on its own, and
386
+ // `(x) => (y)(args)` would call the body, not the arrow. (The
387
+ // `has` operator produces exactly this shape.)
388
+ if (node.callee.type === 'ArrowFunctionExpression') {
389
+ callee = `(${callee})`
390
+ }
391
+ const typeArgs = typed && node.typeArgs ? `<${node.typeArgs}>` : ''
392
+ return `${callee}${node.optional ? '?.' : ''}${typeArgs}(${args})`
146
393
  }
147
394
 
148
395
  case 'AwaitExpression':
@@ -154,17 +401,28 @@ export function generateExpression(node, typed = false) {
154
401
  case 'ObjectExpression': {
155
402
  // Spread entries have key === null and spread === true (see
156
403
  // Parser.parseObjectLiteral), so check p.spread before p.key.
157
- // Computed keys carry keyExpr; method shorthand carries
158
- // method === true with a FunctionExpression value.
404
+ // Computed keys carry keyExpr; method shorthand and accessors
405
+ // carry method === true with a FunctionExpression value and a
406
+ // kind of 'method' | 'get' | 'set'.
159
407
  const props = node.properties
160
408
  .map((p) => {
161
409
  if (p.spread) return `...${generateExpression(p.value, typed)}`
410
+ if (p.shorthandInit) {
411
+ throw new Error(
412
+ `"{ ${p.key} = ... }" is only valid as a destructuring assignment target, e.g. ({ ${p.key} = 1 } = obj)`,
413
+ )
414
+ }
162
415
  const keySrc = p.keyExpr
163
416
  ? `[${generateExpression(p.keyExpr, typed)}]`
164
417
  : JSON.stringify(p.key)
165
418
  if (p.method) {
166
419
  const f = p.value
167
- return `${f.isAsync ? 'async ' : ''}${keySrc}(${generateParams(f.params, typed)}) { ${statementsInline(f.body, typed)} }`
420
+ const body = statementsInline(f.body, typed)
421
+ const params = generateParams(f.params, typed)
422
+ const { generics, ret } = functionSignature(f, typed)
423
+ if (p.kind === 'get') return `get ${keySrc}() { ${body} }`
424
+ if (p.kind === 'set') return `set ${keySrc}(${params}) { ${body} }`
425
+ return `${f.isAsync ? 'async ' : ''}${f.isGenerator ? '*' : ''}${keySrc}${generics}(${params})${ret} { ${body} }`
168
426
  }
169
427
  return `${keySrc}: ${generateExpression(p.value, typed)}`
170
428
  })
@@ -172,11 +430,12 @@ export function generateExpression(node, typed = false) {
172
430
  return `{ ${props} }`
173
431
  }
174
432
 
433
+ // Holes (`null` elements) become empty slots: [1, , 3]
175
434
  case 'ArrayExpression': {
176
- const elements = node.elements
177
- .map((e) => generateExpression(e, typed))
178
- .join(', ')
179
- return `[${elements}]`
435
+ const parts = node.elements.map((e) =>
436
+ e === null ? '' : generateExpression(e, typed),
437
+ )
438
+ return `[${joinArrayElements(parts)}]`
180
439
  }
181
440
 
182
441
  default:
@@ -1,12 +1,18 @@
1
- import { generateExpression, generateParams } from './generateExpression.js'
1
+ import {
2
+ generateExpression,
3
+ generateParams,
4
+ generateClass,
5
+ functionSignature,
6
+ } from './generateExpression.js'
2
7
 
3
8
  /**
4
9
  * Compiles a single statement AST node into a JS source line.
5
10
  *
6
11
  * `typed` is threaded through to generateExpression so a block-bodied
7
12
  * arrow compiled for the virtual .ts file keeps its `: any` param
8
- * annotations on nested arrows. It defaults to false, so every
9
- * existing caller (generateMethod, generateCapability) is unchanged.
13
+ * annotations on nested arrows, and so local declarations keep their
14
+ * `: Type`. It defaults to false, so every existing caller
15
+ * (generateMethod, generateCapability) is unchanged.
10
16
  */
11
17
  export function generateStatement(node, typed = false) {
12
18
  const expr = (n) => generateExpression(n, typed)
@@ -17,6 +23,22 @@ export function generateStatement(node, typed = false) {
17
23
  case 'EmptyStatement':
18
24
  return ';'
19
25
 
26
+ case 'DebuggerStatement':
27
+ return 'debugger;'
28
+
29
+ // `type X = ...` / `interface X {...}` exist only for the checker.
30
+ case 'TypeDeclaration':
31
+ return typed ? node.source : ''
32
+
33
+ case 'EnumDeclaration':
34
+ return generateEnum(node, typed)
35
+
36
+ case 'BlockStatement':
37
+ return `{\n${stmts(node.body)}\n }`
38
+
39
+ case 'LabeledStatement':
40
+ return `${node.label}: ${generateStatement(node.body, typed)}`
41
+
20
42
  case 'ReturnStatement':
21
43
  return node.argument ? `return ${expr(node.argument)};` : 'return;'
22
44
 
@@ -29,8 +51,16 @@ export function generateStatement(node, typed = false) {
29
51
  case 'VariableDeclaration':
30
52
  return `${declarationSource(node, typed)};`
31
53
 
32
- case 'FunctionDeclaration':
33
- return `${node.isAsync ? 'async ' : ''}function ${node.name}(${generateParams(node.params, typed)}) {\n${stmts(node.body)}\n }`
54
+ case 'ClassDeclaration':
55
+ return generateClass(node, typed)
56
+
57
+ case 'FunctionDeclaration': {
58
+ const { generics, ret } = functionSignature(node, typed)
59
+ const head = `${node.isAsync ? 'async ' : ''}function${node.isGenerator ? '*' : ''} ${node.name}${generics}(${generateParams(node.params, typed)})${ret}`
60
+ // Overload signature: checker-only.
61
+ if (node.body == null) return typed ? `${head};` : ''
62
+ return `${head} {\n${stmts(node.body)}\n }`
63
+ }
34
64
 
35
65
  case 'IfStatement': {
36
66
  let out = `if (${expr(node.condition)}) {\n${stmts(node.consequent)}\n }`
@@ -63,7 +93,7 @@ export function generateStatement(node, typed = false) {
63
93
  }
64
94
 
65
95
  case 'ForInStatement':
66
- return `for (${node.declKind ?? 'const'} ${generateDeclarationTarget(node.varName, typed)} of ${expr(node.iterable)}) {\n${stmts(node.body)}\n }`
96
+ return `for ${node.isAwait ? 'await ' : ''}(${node.declKind ?? 'const'} ${generateDeclarationTarget(node.varName, typed)} of ${expr(node.iterable)}) {\n${stmts(node.body)}\n }`
67
97
 
68
98
  case 'ForKeysStatement':
69
99
  return `for (${node.declKind ?? 'const'} ${generateDeclarationTarget(node.varName, typed)} in ${expr(node.object)}) {\n${stmts(node.body)}\n }`
@@ -78,19 +108,35 @@ export function generateStatement(node, typed = false) {
78
108
  return `for (let __i = 0; __i < ${expr(node.count)}; __i++) {\n${stmts(node.body)}\n }`
79
109
 
80
110
  case 'BreakStatement':
81
- return 'break;'
111
+ return node.label ? `break ${node.label};` : 'break;'
82
112
 
83
113
  case 'ContinueStatement':
84
- return 'continue;'
114
+ return node.label ? `continue ${node.label};` : 'continue;'
85
115
 
86
116
  case 'TryStatement': {
87
117
  let out = `try {\n${stmts(node.tryBlock)}\n }`
88
118
 
89
119
  if (node.catchBlock) {
90
- const catchHeader = node.catchParam
91
- ? `catch (${node.catchParam})`
92
- : 'catch'
93
- out += ` ${catchHeader} {\n${stmts(node.catchBlock)}\n }`
120
+ let header = 'catch'
121
+ let prelude = ''
122
+ if (node.catchParam != null) {
123
+ if (typeof node.catchParam === 'string') {
124
+ // Typed: JS gives the catch variable `any` semantics, so
125
+ // the virtual file does too (TypeScript's default would
126
+ // be `unknown` under strict).
127
+ header = typed
128
+ ? `catch (${node.catchParam}: ${node.catchType ?? 'any'})`
129
+ : `catch (${node.catchParam})`
130
+ } else if (typed) {
131
+ // TypeScript forbids a destructuring pattern directly in
132
+ // a catch clause with a type, so bind it on the next line.
133
+ header = 'catch (__caught: any)'
134
+ prelude = ` const ${generateDeclarationTarget(node.catchParam, true)} = __caught;\n`
135
+ } else {
136
+ header = `catch (${generateDeclarationTarget(node.catchParam)})`
137
+ }
138
+ }
139
+ out += ` ${header} {\n${prelude}${stmts(node.catchBlock)}\n }`
94
140
  }
95
141
 
96
142
  if (node.finallyBlock) {
@@ -105,17 +151,76 @@ export function generateStatement(node, typed = false) {
105
151
  }
106
152
  }
107
153
 
108
- // `const a = 1, { b } = x` -- the declaration WITHOUT a trailing
154
+ // Real JS: a plain object with TypeScript-style reverse mapping for
155
+ // numeric members. Typed: a real TS `enum`.
156
+ // enum Color { Red, Green = 5, Blue } -> Red 0, Green 5, Blue 6
157
+ function generateEnum(node, typed) {
158
+ if (typed) {
159
+ const members = node.members.map((m) => {
160
+ const key = /^[A-Za-z_$][\w$]*$/.test(m.name) ? m.name : JSON.stringify(m.name)
161
+ return m.init ? `${key} = ${generateExpression(m.init, true)}` : key
162
+ })
163
+ return `enum ${node.name} { ${members.join(', ')} }`
164
+ }
165
+ const body = node.members
166
+ .map((m) => {
167
+ const k = JSON.stringify(m.name)
168
+ if (m.init && m.init.type === 'Literal' && typeof m.init.value === 'string') {
169
+ return `__e[${k}] = ${JSON.stringify(m.init.value)};`
170
+ }
171
+ const set = m.init ? `__n = ${generateExpression(m.init)}; ` : ''
172
+ return `${set}__e[__e[${k}] = __n] = ${k}; __n++;`
173
+ })
174
+ .join(' ')
175
+ return `const ${node.name} = (() => { const __e = {}; let __n = 0; ${body} return __e; })();`
176
+ }
177
+
178
+ // Names a statement declares at its own scope (functions, classes,
179
+ // enums, const/let including destructured ones). Used to expose
180
+ // module-level helpers to templates.
181
+ export function declaredNames(stmt) {
182
+ if (
183
+ stmt.type === 'FunctionDeclaration' ||
184
+ stmt.type === 'ClassDeclaration' ||
185
+ stmt.type === 'EnumDeclaration'
186
+ ) {
187
+ return stmt.name ? [stmt.name] : []
188
+ }
189
+ if (stmt.type === 'VariableDeclaration') {
190
+ return [stmt.name, ...(stmt.more ?? []).map((m) => m.name)].flatMap(patternNames)
191
+ }
192
+ return []
193
+ }
194
+
195
+ function patternNames(t) {
196
+ if (typeof t === 'string') return [t]
197
+ if (t.type === 'ObjectPattern') {
198
+ return [
199
+ ...t.properties.flatMap((p) => patternNames(p.binding)),
200
+ ...(t.rest ? [t.rest] : []),
201
+ ]
202
+ }
203
+ return [
204
+ ...t.elements.flatMap((el) => (el === null ? [] : patternNames(el.binding))),
205
+ ...(t.rest ? [t.rest] : []),
206
+ ]
207
+ }
208
+
209
+ // `const a: A = 1, { b } = x` -- the declaration WITHOUT a trailing
109
210
  // semicolon (used by statements and by C-style for headers). A null
110
- // init (`let x`) emits just the target.
211
+ // init (`let x`) emits just the target. Type annotations are emitted
212
+ // only in typed mode (the virtual .ts); real JS output omits them.
111
213
  export function declarationSource(node, typed = false) {
112
- const one = (name, init) =>
113
- init == null
114
- ? generateDeclarationTarget(name, typed)
115
- : `${generateDeclarationTarget(name, typed)} = ${generateExpression(init, typed)}`
214
+ const one = (name, init, type) => {
215
+ const target = generateDeclarationTarget(name, typed)
216
+ const annotation = typed && type ? `: ${type}` : ''
217
+ return init == null
218
+ ? `${target}${annotation}`
219
+ : `${target}${annotation} = ${generateExpression(init, typed)}`
220
+ }
116
221
  const parts = [
117
- one(node.name, node.init),
118
- ...(node.more ?? []).map((m) => one(m.name, m.init)),
222
+ one(node.name, node.init, node.typeAnnotation),
223
+ ...(node.more ?? []).map((m) => one(m.name, m.init, m.typeAnnotation)),
119
224
  ]
120
225
  return `${node.kind} ${parts.join(', ')}`
121
226
  }