@tylix/compiler 0.5.2 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +30 -2
  3. package/src/ast/nodes.js +219 -16
  4. package/src/ast/substituteCapabilityRefs.js +185 -61
  5. package/src/codegen/emitStatementLines.js +98 -54
  6. package/src/codegen/generateExpression.js +339 -36
  7. package/src/codegen/generateMethod.js +5 -3
  8. package/src/codegen/generatePage.js +74 -44
  9. package/src/codegen/generateStatement.js +169 -20
  10. package/src/codegen/generateTemplate.js +183 -101
  11. package/src/codegen/generateTemplateExpression.js +102 -59
  12. package/src/codegen/jsGlobals.js +211 -0
  13. package/src/compileComponent.js +39 -8
  14. package/src/imports/extractImports.js +112 -26
  15. package/src/imports/resolveImports.js +186 -0
  16. package/src/index.js +3 -2
  17. package/src/lexer/Lexer.js +430 -235
  18. package/src/lexer/tokenTypes.js +32 -7
  19. package/src/parser/Parser.js +2176 -325
  20. package/src/parser/languageOptions.js +16 -0
  21. package/src/parser/parseExpressionString.js +23 -7
  22. package/src/parser/parsePageFile.js +139 -58
  23. package/src/parser/parseTemplate.js +350 -62
  24. package/src/renderPageDocument.js +338 -56
  25. package/src/runtime/capability.js +39 -17
  26. package/src/runtime/loadingIndicator.js +91 -29
  27. package/src/runtime/reactive.js +362 -64
  28. package/src/runtime/useApi.js +74 -13
  29. package/src/runtime/useChannel.js +27 -6
  30. package/src/typecheck/buildVirtualTs.js +23 -12
  31. package/src/typecheck/tylix-globals.d.ts +23 -4
  32. package/src/typecheck/typedTemplateExpr.js +195 -53
  33. package/src/typecheckPage.js +28 -4
  34. package/src/codegen/generateExpression.array.test.js +0 -13
  35. package/src/codegen/generateExpression.callexpr.test.js +0 -19
  36. package/src/codegen/generateExpression.test.js +0 -59
  37. package/src/codegen/generateMethod.asyncawait.test.js +0 -37
  38. package/src/codegen/generateMethod.ifstatement.test.js +0 -20
  39. package/src/codegen/generateMethod.test.js +0 -81
  40. package/src/codegen/generatePage.onmount.test.js +0 -46
  41. package/src/codegen/generatePage.test.js +0 -138
  42. package/src/codegen/generateStatement.test.js +0 -31
  43. package/src/codegen/generateTemplate.ifeach.test.js +0 -138
  44. package/src/codegen/generateTemplate.test.js +0 -149
  45. package/src/codegen/generateTemplateExpression.test.js +0 -34
  46. package/src/compileComponent.test.js +0 -121
  47. package/src/imports/resolvePackageComponents.js +0 -41
  48. package/src/lexer/Lexer.test.js +0 -151
  49. package/src/parser/Parser.array.test.js +0 -37
  50. package/src/parser/Parser.asyncawait.test.js +0 -33
  51. package/src/parser/Parser.ifstatement.test.js +0 -20
  52. package/src/parser/Parser.onmount.test.js +0 -18
  53. package/src/parser/Parser.test.js +0 -315
  54. package/src/parser/parseComponent.test.js +0 -53
  55. package/src/parser/parsePageFile.test.js +0 -101
  56. package/src/parser/parseTemplate.ifeach.test.js +0 -33
  57. package/src/parser/parseTemplate.pre.test.js +0 -39
  58. package/src/parser/parseTemplate.test.js +0 -112
  59. package/src/renderPageDocument.test.js +0 -125
  60. package/src/runtime/reactive.test.js +0 -106
  61. package/test/dashboard-syntax.test.js +0 -116
@@ -1,3 +1,5 @@
1
+ import { JS_GLOBALS, paramNames } from '../codegen/jsGlobals.js'
2
+ import { joinArrayElements, assignmentPatternSource } from '../codegen/generateExpression.js'
1
3
  // generateTemplateExpression's twin, for the virtual .ts class body
2
4
  // built in buildVirtualPageTs. The REAL compiled template (see
3
5
  // codegen/generateTemplateExpression.js) prefixes state reads with
@@ -17,16 +19,26 @@ function unaryPrefix(operator) {
17
19
  return /^[a-z]/i.test(operator) ? `${operator} ` : operator
18
20
  }
19
21
 
22
+ // `5.toFixed(1)` is a syntax error; `(5).toFixed(1)` is not.
23
+ function memberObject(node, scope) {
24
+ const src = typedTemplateExpr(node, scope)
25
+ return node.type === 'Literal' && typeof node.value === 'number'
26
+ ? `(${src})`
27
+ : src
28
+ }
29
+
20
30
  export function typedTemplateExpr(node, scope) {
21
31
  if (node.type === 'Identifier') {
22
32
  if (node.name === '$event' || scope.has(node.name)) return node.name
33
+ if (node.name === 'this') return 'this'
34
+ if (JS_GLOBALS.has(node.name)) return node.name
23
35
  return `this.${node.name}`
24
36
  }
25
37
  if (node.type === 'MemberExpression') {
26
38
  if (node.computed) {
27
- return `${typedTemplateExpr(node.object, scope)}${node.optional ? '?.' : ''}[${typedTemplateExpr(node.property, scope)}]`
39
+ return `${memberObject(node.object, scope)}${node.optional ? '?.' : ''}[${typedTemplateExpr(node.property, scope)}]`
28
40
  }
29
- return `${typedTemplateExpr(node.object, scope)}${node.optional ? '?.' : '.'}${node.property}`
41
+ return `${memberObject(node.object, scope)}${node.optional ? '?.' : '.'}${node.property}`
30
42
  }
31
43
  if (node.type === 'BinaryExpression') {
32
44
  return `(${typedTemplateExpr(node.left, scope)} ${node.operator} ${typedTemplateExpr(node.right, scope)})`
@@ -34,6 +46,23 @@ export function typedTemplateExpr(node, scope) {
34
46
  if (node.type === 'UnaryExpression') {
35
47
  return `(${unaryPrefix(node.operator)}${typedTemplateExpr(node.argument, scope)})`
36
48
  }
49
+ if (node.type === 'UpdateExpression') {
50
+ const arg = typedTemplateExpr(node.argument, scope)
51
+ return node.prefix ? `(${node.operator}${arg})` : `(${arg}${node.operator})`
52
+ }
53
+
54
+ // `(a, b)` -- the comma operator.
55
+ if (node.type === 'SequenceExpression') {
56
+ return `(${node.expressions.map((e) => typedTemplateExpr(e, scope)).join(', ')})`
57
+ }
58
+
59
+ // The casts are the whole point of the virtual file: keep them.
60
+ if (node.type === 'AsExpression') {
61
+ return `(${typedTemplateExpr(node.expression, scope)} ${node.keyword ?? 'as'} ${node.typeAnnotation})`
62
+ }
63
+ if (node.type === 'NonNullExpression') {
64
+ return `${typedTemplateExpr(node.expression, scope)}!`
65
+ }
37
66
 
38
67
  if (node.type === 'AwaitExpression') {
39
68
  return `(await ${typedTemplateExpr(node.argument, scope)})`
@@ -47,45 +76,77 @@ export function typedTemplateExpr(node, scope) {
47
76
  return `(${typedTemplateExpr(node.left, scope)} ?? ${typedTemplateExpr(node.right, scope)})`
48
77
  }
49
78
 
50
- if (node.type === 'AssignmentExpression') {
51
- return `${typedTemplateExpr(node.target, scope)} = ${typedTemplateExpr(node.value, scope)}`
52
- }
53
- if (node.type === 'CallExpression') {
54
- const args = node.args.map((a) => typedTemplateExpr(a, scope)).join(', ')
55
- return `${typedTemplateExpr(node.callee, scope)}${node.optional ? '?.' : ''}(${args})`
56
- }
57
- if (node.type === 'NewExpression') {
58
- const args = node.args.map((a) => typedTemplateExpr(a, scope)).join(', ')
59
- return `new ${typedTemplateExpr(node.callee, scope)}(${args})`
60
- }
79
+ if (node.type === 'AssignmentExpression') {
80
+ const isPattern =
81
+ node.target.type === 'ObjectExpression' || node.target.type === 'ArrayExpression'
82
+ const target = isPattern
83
+ ? assignmentPatternSource(node.target, (n) => typedTemplateExpr(n, scope))
84
+ : typedTemplateExpr(node.target, scope)
85
+ return `(${target} = ${typedTemplateExpr(node.value, scope)})`
86
+ }
87
+ if (node.type === 'CallExpression') {
88
+ const args = node.args.map((a) => typedTemplateExpr(a, scope)).join(', ')
89
+ const typeArgs = node.typeArgs ? `<${node.typeArgs}>` : ''
90
+ return `${typedTemplateExpr(node.callee, scope)}${node.optional ? '?.' : ''}${typeArgs}(${args})`
91
+ }
92
+ if (node.type === 'NewExpression') {
93
+ const args = node.args.map((a) => typedTemplateExpr(a, scope)).join(', ')
94
+ const typeArgs = node.typeArgs ? `<${node.typeArgs}>` : ''
95
+ return `new ${typedTemplateExpr(node.callee, scope)}${typeArgs}(${args})`
96
+ }
61
97
 
62
- // Arrow params are typed `any` unless annotated, matching what
63
- // generateExpression does in typed mode. Params become locals, so
64
- // they are referenced bare in the body.
98
+ // Arrow params are typed `any` (`any[]` for rest) unless annotated,
99
+ // matching what generateExpression does in typed mode. Params become
100
+ // locals, so they are referenced bare in the body. Destructured/rest
101
+ // params are stored as source strings; paramNames() extracts the
102
+ // names they bind. Defaults are checked in the arrow's own scope.
65
103
  if (node.type === 'ArrowFunctionExpression') {
66
- const innerScope = new Set([...scope, ...node.params])
104
+ if (node.body.type === 'BlockStatement') {
105
+ throw new Error(
106
+ 'Block-bodied arrow functions (x => { ... }) are not allowed in templates; use an expression body or move the code into an action',
107
+ )
108
+ }
109
+ const innerScope = new Set([...scope, ...paramNames(node.params)])
67
110
  const types = node.paramTypes ?? node.params.map(() => null)
111
+ const defaults = node.paramDefaults ?? []
112
+ const optionals = node.paramOptional ?? []
68
113
  const params = node.params
69
- .map((name, i) => `${name}: ${types[i] ?? 'any'}`)
114
+ .map((name, i) => {
115
+ const fallback = name.startsWith('...') ? 'any[]' : 'any'
116
+ const optional = optionals[i] && !defaults[i] ? '?' : ''
117
+ const base = `${name}${optional}: ${types[i] ?? fallback}`
118
+ return defaults[i]
119
+ ? `${base} = ${typedTemplateExpr(defaults[i], innerScope)}`
120
+ : base
121
+ })
70
122
  .join(', ')
71
123
  const asyncPrefix = node.isAsync ? 'async ' : ''
72
- return `(${asyncPrefix}(${params}) => (${typedTemplateExpr(node.body, innerScope)}))`
124
+ const returnType = node.returnType ? `: ${node.returnType}` : ''
125
+ return `(${asyncPrefix}${node.typeParams ?? ''}(${params})${returnType} => (${typedTemplateExpr(node.body, innerScope)}))`
73
126
  }
74
127
 
128
+ // Holes (`null` elements) become empty slots: [1, , 3]
75
129
  if (node.type === 'ArrayExpression') {
76
- const elements = node.elements
77
- .map((e) => typedTemplateExpr(e, scope))
78
- .join(', ')
79
- return `[${elements}]`
130
+ const parts = node.elements.map((e) =>
131
+ e === null ? '' : typedTemplateExpr(e, scope),
132
+ )
133
+ return `[${joinArrayElements(parts)}]`
80
134
  }
81
135
 
82
136
  if (node.type === 'ObjectExpression') {
83
137
  const properties = node.properties
84
- .map((p) =>
85
- p.spread
86
- ? `...${typedTemplateExpr(p.value, scope)}`
87
- : `${JSON.stringify(p.key)}: ${typedTemplateExpr(p.value, scope)}`,
88
- )
138
+ .map((p) => {
139
+ if (p.spread) return `...${typedTemplateExpr(p.value, scope)}`
140
+ if (p.method) {
141
+ throw new Error(
142
+ 'Methods and getters/setters in object literals ({ fn() {} }, { get x() {} }) are only allowed in script code, not in template expressions',
143
+ )
144
+ }
145
+ const keySrc = p.keyExpr
146
+ ? `[${typedTemplateExpr(p.keyExpr, scope)}]`
147
+ : JSON.stringify(p.key)
148
+ return `${keySrc}: ${typedTemplateExpr(p.value, scope)}`
149
+ })
89
150
  .join(', ')
90
151
  return `({ ${properties} })`
91
152
  }
@@ -105,41 +166,110 @@ export function typedTemplateExpr(node, scope) {
105
166
  return `\`${body}\``
106
167
  }
107
168
 
169
+ // tag`text ${x}` -- text parts are emitted as written (`raw`).
170
+ if (node.type === 'TaggedTemplateExpression') {
171
+ const body = node.quasi.parts
172
+ .map((part) =>
173
+ part.type === 'text'
174
+ ? (part.raw ?? escapeTemplateText(part.value))
175
+ : `\${${typedTemplateExpr(part.expression, scope)}}`,
176
+ )
177
+ .join('')
178
+ return `${typedTemplateExpr(node.tag, scope)}\`${body}\``
179
+ }
180
+
108
181
  if (node.type === 'Literal') {
109
182
  return typeof node.value === 'string'
110
183
  ? JSON.stringify(node.value)
111
184
  : String(node.value)
112
185
  }
186
+
187
+ if (node.type === 'ClassExpression') {
188
+ throw new Error(
189
+ 'Classes are only allowed in script code, not in template expressions',
190
+ )
191
+ }
192
+
113
193
  throw new Error(`typedTemplateExpr: unsupported node type "${node.type}"`)
114
194
  }
115
195
 
116
- const EVENT_ATTR_RE = /^on(click|input|change|submit)$/i
117
-
118
- // Which DOM element type a synthetic $event's `target` should be
119
- // typed as, keyed by the event name captured from EVENT_ATTR_RE
120
- // (lowercased). Deliberately narrow -- these are the only event
121
- // attributes the template grammar currently recognizes at all.
122
- // Anything not listed falls back to the generic HTMLElement, same as
123
- // a real framework would for an untyped/unknown handler.
124
- const EVENT_TARGET_TYPES = {
125
- input: 'HTMLInputElement',
126
- change: 'HTMLInputElement',
127
- submit: 'HTMLFormElement',
128
- click: 'HTMLElement',
196
+ // Any on<event> attribute is an event listener (see generateTemplate).
197
+ const EVENT_ATTR_RE = /^on([a-z]+)$/i
198
+
199
+ // [event interface, element type of `event.target`] per DOM event
200
+ // name. Anything not listed falls back to a plain Event on a generic
201
+ // HTMLElement, same as a real framework would for an unknown handler.
202
+ const MOUSE = ['MouseEvent', 'HTMLElement']
203
+ const KEY = ['KeyboardEvent', 'HTMLInputElement']
204
+ const FOCUS = ['FocusEvent', 'HTMLInputElement']
205
+ const POINTER = ['PointerEvent', 'HTMLElement']
206
+ const DRAG = ['DragEvent', 'HTMLElement']
207
+ const TOUCH = ['TouchEvent', 'HTMLElement']
208
+ const EVENT_TYPES = {
209
+ click: MOUSE,
210
+ dblclick: MOUSE,
211
+ auxclick: MOUSE,
212
+ contextmenu: MOUSE,
213
+ mousedown: MOUSE,
214
+ mouseup: MOUSE,
215
+ mousemove: MOUSE,
216
+ mouseenter: MOUSE,
217
+ mouseleave: MOUSE,
218
+ mouseover: MOUSE,
219
+ mouseout: MOUSE,
220
+ keydown: KEY,
221
+ keyup: KEY,
222
+ keypress: KEY,
223
+ input: ['InputEvent', 'HTMLInputElement'],
224
+ change: ['Event', 'HTMLInputElement'],
225
+ submit: ['SubmitEvent', 'HTMLFormElement'],
226
+ reset: ['Event', 'HTMLFormElement'],
227
+ focus: FOCUS,
228
+ blur: FOCUS,
229
+ focusin: FOCUS,
230
+ focusout: FOCUS,
231
+ scroll: ['Event', 'HTMLElement'],
232
+ wheel: ['WheelEvent', 'HTMLElement'],
233
+ pointerdown: POINTER,
234
+ pointerup: POINTER,
235
+ pointermove: POINTER,
236
+ pointerenter: POINTER,
237
+ pointerleave: POINTER,
238
+ pointercancel: POINTER,
239
+ drag: DRAG,
240
+ dragstart: DRAG,
241
+ dragend: DRAG,
242
+ dragenter: DRAG,
243
+ dragleave: DRAG,
244
+ dragover: DRAG,
245
+ drop: DRAG,
246
+ touchstart: TOUCH,
247
+ touchmove: TOUCH,
248
+ touchend: TOUCH,
249
+ touchcancel: TOUCH,
250
+ }
251
+
252
+ function eventTypesFor(eventName) {
253
+ return Object.hasOwn(EVENT_TYPES, eventName.toLowerCase())
254
+ ? EVENT_TYPES[eventName.toLowerCase()]
255
+ : ['Event', 'HTMLElement']
129
256
  }
130
257
 
131
258
  // Walks a parsed template AST (from parseTemplate) collecting every
132
259
  // bindable expression as a tree of check entries, ready for
133
260
  // buildVirtualPageTs to emit into a synthetic __render() method.
134
261
  // Entries come in two kinds:
135
- // { kind: 'check', expr, line, eventType } -- a single expression
136
- // to typecheck (interpolation, #if condition, dynamic attribute)
137
- // { kind: 'each', itemName, iterableExpr, line, children } -- an
138
- // #each block; children is itself a list of these same entries
262
+ // { kind: 'check', expr, line, eventType, eventBase } -- a single
263
+ // expression to typecheck (interpolation, #if condition, dynamic
264
+ // attribute). eventType/eventBase are set for event handlers.
265
+ // { kind: 'each', itemName, indexName, iterableExpr, line, children }
266
+ // -- an #each block; children is itself a list of these same entries
139
267
  // The 'each' kind exists so the emitted TS can wrap its children in
140
268
  // a real `for (const f of ...)` -- without an actual declaration for
141
269
  // the loop variable, TS has no way to resolve identifiers like `f`
142
270
  // inside the block, regardless of what our own scope-tracking says.
271
+ // {{#else}} branches are collected as ordinary entries after their
272
+ // block, in the OUTER scope (an each-else has no loop variable).
143
273
  export function collectTemplateChecks(nodes, scope, out) {
144
274
  for (const node of nodes) {
145
275
  if (node.type === 'Interpolation') {
@@ -148,6 +278,7 @@ export function collectTemplateChecks(nodes, scope, out) {
148
278
  expr: typedTemplateExpr(node.expression, scope),
149
279
  line: node.line,
150
280
  eventType: null,
281
+ eventBase: null,
151
282
  })
152
283
  } else if (node.type === 'If') {
153
284
  out.push({
@@ -155,23 +286,32 @@ export function collectTemplateChecks(nodes, scope, out) {
155
286
  expr: typedTemplateExpr(node.condition, scope),
156
287
  line: node.line,
157
288
  eventType: null,
289
+ eventBase: null,
158
290
  })
159
291
  collectTemplateChecks(node.children, scope, out)
292
+ if (node.elseChildren) {
293
+ collectTemplateChecks(node.elseChildren, scope, out)
294
+ }
160
295
  } else if (node.type === 'Each') {
161
296
  const iterableExpr = typedTemplateExpr(node.iterable, scope)
162
297
  const children = []
163
- collectTemplateChecks(
164
- node.children,
165
- new Set([...scope, node.itemName]),
166
- children,
167
- )
298
+ const innerScope = new Set([
299
+ ...scope,
300
+ ...paramNames([node.itemName]),
301
+ ...(node.indexName ? [node.indexName] : []),
302
+ ])
303
+ collectTemplateChecks(node.children, innerScope, children)
168
304
  out.push({
169
305
  kind: 'each',
170
306
  itemName: node.itemName,
307
+ indexName: node.indexName ?? null,
171
308
  iterableExpr,
172
309
  line: node.line,
173
310
  children,
174
311
  })
312
+ if (node.elseChildren) {
313
+ collectTemplateChecks(node.elseChildren, scope, out)
314
+ }
175
315
  } else if (node.type === 'Element') {
176
316
  for (const attr of node.attributes) {
177
317
  if (!attr.dynamic) continue
@@ -179,13 +319,15 @@ export function collectTemplateChecks(nodes, scope, out) {
179
319
  const attrScope = eventMatch
180
320
  ? new Set([...scope, '$event', 'event'])
181
321
  : scope
322
+ const [eventBase, eventType] = eventMatch
323
+ ? eventTypesFor(eventMatch[1])
324
+ : [null, null]
182
325
  out.push({
183
326
  kind: 'check',
184
327
  expr: typedTemplateExpr(attr.value, attrScope),
185
328
  line: attr.line,
186
- eventType: eventMatch
187
- ? (EVENT_TARGET_TYPES[eventMatch[1].toLowerCase()] ?? 'HTMLElement')
188
- : null,
329
+ eventType,
330
+ eventBase,
189
331
  })
190
332
  }
191
333
  collectTemplateChecks(node.children, scope, out)
@@ -2,6 +2,7 @@ import { parsePageFile } from './parser/parsePageFile.js'
2
2
  import { parseTemplate } from './parser/parseTemplate.js'
3
3
  import { Lexer } from './lexer/Lexer.js'
4
4
  import { Parser } from './parser/Parser.js'
5
+ import { normalizeLanguageOptions } from './parser/languageOptions.js'
5
6
  import {
6
7
  buildVirtualPageTs,
7
8
  mapVirtualLineToSource,
@@ -20,17 +21,40 @@ import { substituteCapabilityRefs } from './ast/substituteCapabilityRefs.js'
20
21
  // at all and floods the diagnostics list with dozens of
21
22
  // cascading-recovery errors, none of which point at anything wrong
22
23
  // in the actual .tyx source.
23
- export function typecheckPage(source, apiHelpersSource = '') {
24
+ //
25
+ // `source` must already have its import lines blanked out by
26
+ // extractImports() (which keeps line numbers intact), or any page with
27
+ // an `import` line fails to parse here.
28
+ //
29
+ // `languageOption` must be the same object passed to
30
+ // renderPageDocument ({ not: 'loose' } etc.): the typechecker has to
31
+ // parse the page the same way the real build does, or it would report
32
+ // on a different program than the one that runs.
33
+ export function typecheckPage(
34
+ source,
35
+ apiHelpersSource = '',
36
+ languageOption = {},
37
+ ) {
38
+ // createApp has a variable named `language` that holds
39
+ // 'typescript' | 'javascript'. Passing that here by mistake would
40
+ // silently fall back to defaults, so refuse it loudly.
41
+ if (languageOption !== null && typeof languageOption !== 'object') {
42
+ throw new Error(
43
+ `typecheckPage: the language options must be an object like { not: 'loose' }, got ${typeof languageOption} "${languageOption}"`,
44
+ )
45
+ }
46
+ const language = normalizeLanguageOptions(languageOption ?? {})
47
+
24
48
  const { pageName, script, template, scriptStartLine } = parsePageFile(source)
25
49
 
26
50
  const pageNode = substituteCapabilityRefs(
27
51
  script.trim().length > 0
28
- ? new Parser(new Lexer(script).tokenize()).parse()
52
+ ? new Parser(new Lexer(script).tokenize(), language).parse()
29
53
  : { props: [], state: [], computed: [], actions: [], onMount: null },
30
54
  )
31
55
 
32
56
  const templateNodes =
33
- template.trim().length > 0 ? parseTemplate(template) : null
57
+ template.trim().length > 0 ? parseTemplate(template, language) : null
34
58
 
35
59
  const { source: virtualSource, lineMap } = buildVirtualPageTs(
36
60
  pageNode,
@@ -43,4 +67,4 @@ export function typecheckPage(source, apiHelpersSource = '') {
43
67
  const scriptLine = mapVirtualLineToSource(lineMap, d.virtualLine)
44
68
  return { message: d.message, line: scriptLine + scriptStartLine - 1 }
45
69
  })
46
- }
70
+ }
@@ -1,13 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { generateExpression } from "./generateExpression.js";
4
- import { ArrayExpr, Literal } from "../ast/nodes.js";
5
-
6
- test("generates an empty array literal", () => {
7
- assert.equal(generateExpression(ArrayExpr([])), "[]");
8
- });
9
-
10
- test("generates an array literal with literal elements", () => {
11
- const node = ArrayExpr([Literal(1), Literal(2), Literal("x")]);
12
- assert.equal(generateExpression(node), '[1, 2, "x"]');
13
- });
@@ -1,19 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { generateExpression } from "./generateExpression.js";
4
- import { CallExpr, MemberExpr, Identifier, Literal } from "../ast/nodes.js";
5
-
6
- test("generates a call with no arguments", () => {
7
- const node = CallExpr(MemberExpr(Identifier("this"), "load"), []);
8
- assert.equal(generateExpression(node), "this.load()");
9
- });
10
-
11
- test("generates a call with multiple arguments", () => {
12
- const node = CallExpr(Identifier("remove"), [Literal(1), Literal("x")]);
13
- assert.equal(generateExpression(node), 'remove(1, "x")');
14
- });
15
-
16
- test("generates a call with a member-expression argument", () => {
17
- const node = CallExpr(Identifier("remove"), [MemberExpr(Identifier("post"), "id")]);
18
- assert.equal(generateExpression(node), "remove(post.id)");
19
- });
@@ -1,59 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { generateExpression } from "./generateExpression.js";
4
- import {
5
- Literal,
6
- Identifier,
7
- MemberExpr,
8
- BinaryExpr,
9
- AssignmentExpr,
10
- } from "../ast/nodes.js";
11
-
12
- test("generates a number literal", () => {
13
- assert.equal(generateExpression(Literal(42)), "42");
14
- });
15
-
16
- test("generates a string literal as a properly quoted JS string", () => {
17
- assert.equal(generateExpression(Literal("hello")), '"hello"');
18
- });
19
-
20
- test("generates an identifier", () => {
21
- assert.equal(generateExpression(Identifier("count")), "count");
22
- });
23
-
24
- test("generates a member expression", () => {
25
- const node = MemberExpr(Identifier("this"), "count");
26
- assert.equal(generateExpression(node), "this.count");
27
- });
28
-
29
- test("generates a chained member expression", () => {
30
- const node = MemberExpr(MemberExpr(Identifier("this"), "state"), "count");
31
- assert.equal(generateExpression(node), "this.state.count");
32
- });
33
-
34
- test("generates a binary expression wrapped in parens", () => {
35
- const node = BinaryExpr("+", Identifier("count"), Literal(1));
36
- assert.equal(generateExpression(node), "(count + 1)");
37
- });
38
-
39
- test("generates a nested binary expression", () => {
40
- const node = BinaryExpr("*", BinaryExpr("+", Identifier("a"), Identifier("b")), Literal(2));
41
- assert.equal(generateExpression(node), "((a + b) * 2)");
42
- });
43
-
44
- test("generates an assignment expression", () => {
45
- const node = AssignmentExpr(MemberExpr(Identifier("this"), "count"), Literal(0));
46
- assert.equal(generateExpression(node), "this.count = 0");
47
- });
48
-
49
- test("generates an assignment with a binary expression value", () => {
50
- const node = AssignmentExpr(
51
- MemberExpr(Identifier("this"), "count"),
52
- BinaryExpr("+", MemberExpr(Identifier("this"), "count"), Literal(1))
53
- );
54
- assert.equal(generateExpression(node), "this.count = (this.count + 1)");
55
- });
56
-
57
- test("throws on an unknown node type", () => {
58
- assert.throws(() => generateExpression({ type: "Bogus" }), /unknown node type "Bogus"/);
59
- });
@@ -1,37 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { generateMethod } from "./generateMethod.js";
4
- import { Parser } from "../parser/Parser.js";
5
- import { Lexer } from "../lexer/Lexer.js";
6
-
7
- test("generates a real async method that awaits a resolved promise", async () => {
8
- const source = `
9
- action
10
- async load() {
11
- const value = await this.fetchValue()
12
- this.result = value
13
- }`;
14
- const page = new Parser(new Lexer(source).tokenize()).parse();
15
- const methodSource = generateMethod(page.actions[0]);
16
-
17
- const classSource = `class Test {
18
- constructor() { this.result = null; }
19
- async fetchValue() { return 42; }
20
- ${methodSource}
21
- }`;
22
- const TestClass = new Function(`return ${classSource}`)();
23
- const instance = new TestClass();
24
- await instance.load();
25
- assert.equal(instance.result, 42);
26
- });
27
-
28
- test("generates an object literal argument correctly", () => {
29
- const source = `
30
- action
31
- async save() {
32
- await this.post({ method: "POST", id: 5 })
33
- }`;
34
- const page = new Parser(new Lexer(source).tokenize()).parse();
35
- const methodSource = generateMethod(page.actions[0]);
36
- assert.match(methodSource, /this\.post\(\{ "method": "POST", "id": 5 \}\)/);
37
- });
@@ -1,20 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { generateMethod } from "./generateMethod.js";
4
- import { Parser } from "../parser/Parser.js";
5
- import { Lexer } from "../lexer/Lexer.js";
6
-
7
- test("generates a real if/else branch that executes correctly", () => {
8
- const source = `action\ncheck(ok) {\n if (ok) {\n this.result = "yes"\n } else {\n this.result = "no"\n }\n}`;
9
- const page = new Parser(new Lexer(source).tokenize()).parse();
10
- const methodSource = generateMethod(page.actions[0]);
11
-
12
- const classSource = `class Test { constructor() { this.result = null; } ${methodSource} }`;
13
- const TestClass = new Function(`return ${classSource}`)();
14
- const instance = new TestClass();
15
-
16
- instance.check(true);
17
- assert.equal(instance.result, "yes");
18
- instance.check(false);
19
- assert.equal(instance.result, "no");
20
- });
@@ -1,81 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert/strict";
3
- import { generateMethod } from "./generateMethod.js";
4
- import {
5
- MethodNode,
6
- ReturnStatement,
7
- ExpressionStatement,
8
- AssignmentExpr,
9
- BinaryExpr,
10
- MemberExpr,
11
- Identifier,
12
- Literal,
13
- } from "../ast/nodes.js";
14
-
15
- test("generates a zero-parameter method with a single return statement", () => {
16
- const node = MethodNode(
17
- "doubled",
18
- [],
19
- [ReturnStatement(BinaryExpr("*", MemberExpr(Identifier("this"), "count"), Literal(2)))]
20
- );
21
-
22
- const code = generateMethod(node);
23
- assert.equal(code, " doubled() {\n return (this.count * 2);\n }");
24
- });
25
-
26
- test("generates a method with parameters", () => {
27
- // Params are { name, typeAnnotation } objects, the same shape the
28
- // parser produces.
29
- const node = MethodNode("setCount", [{ name: "value", typeAnnotation: null }], [
30
- ExpressionStatement(AssignmentExpr(MemberExpr(Identifier("this"), "count"), Identifier("value"))),
31
- ]);
32
-
33
- const code = generateMethod(node);
34
- assert.equal(code, " setCount(value) {\n this.count = value;\n }");
35
- });
36
-
37
- test("generates a method with multiple statements", () => {
38
- const node = MethodNode(
39
- "increment",
40
- [],
41
- [
42
- ExpressionStatement(
43
- AssignmentExpr(
44
- MemberExpr(Identifier("this"), "count"),
45
- BinaryExpr("+", MemberExpr(Identifier("this"), "count"), Literal(1))
46
- )
47
- ),
48
- ReturnStatement(MemberExpr(Identifier("this"), "count")),
49
- ]
50
- );
51
-
52
- const code = generateMethod(node);
53
- assert.equal(
54
- code,
55
- " increment() {\n this.count = (this.count + 1);\n return this.count;\n }"
56
- );
57
- });
58
-
59
- test("the generated method source is valid, executable JavaScript", () => {
60
- const node = MethodNode(
61
- "increment",
62
- [],
63
- [
64
- ExpressionStatement(
65
- AssignmentExpr(
66
- MemberExpr(Identifier("this"), "count"),
67
- BinaryExpr("+", MemberExpr(Identifier("this"), "count"), Literal(1))
68
- )
69
- ),
70
- ]
71
- );
72
-
73
- const methodSource = generateMethod(node);
74
- const classSource = `class Test { ${methodSource} }`;
75
- const TestClass = new Function(`return ${classSource}`)();
76
-
77
- const instance = new TestClass();
78
- instance.count = 5;
79
- instance.increment();
80
- assert.equal(instance.count, 6);
81
- });