@tylix/compiler 0.5.2 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/package.json +30 -2
- package/src/ast/nodes.js +219 -16
- package/src/ast/substituteCapabilityRefs.js +185 -61
- package/src/codegen/emitStatementLines.js +98 -54
- package/src/codegen/generateExpression.js +339 -36
- package/src/codegen/generateMethod.js +5 -3
- package/src/codegen/generatePage.js +74 -44
- package/src/codegen/generateStatement.js +169 -20
- package/src/codegen/generateTemplate.js +183 -101
- package/src/codegen/generateTemplateExpression.js +102 -59
- package/src/codegen/jsGlobals.js +211 -0
- package/src/compileComponent.js +39 -8
- package/src/imports/extractImports.js +112 -26
- package/src/imports/resolveImports.js +186 -0
- package/src/index.js +3 -2
- package/src/lexer/Lexer.js +430 -235
- package/src/lexer/tokenTypes.js +32 -7
- package/src/parser/Parser.js +2176 -325
- package/src/parser/languageOptions.js +16 -0
- package/src/parser/parseExpressionString.js +23 -7
- package/src/parser/parsePageFile.js +139 -58
- package/src/parser/parseTemplate.js +350 -62
- package/src/renderPageDocument.js +338 -56
- package/src/runtime/capability.js +39 -17
- package/src/runtime/loadingIndicator.js +91 -29
- package/src/runtime/reactive.js +362 -64
- package/src/runtime/useApi.js +74 -13
- package/src/runtime/useChannel.js +27 -6
- package/src/typecheck/buildVirtualTs.js +23 -12
- package/src/typecheck/tylix-globals.d.ts +23 -4
- package/src/typecheck/typedTemplateExpr.js +195 -53
- package/src/typecheckPage.js +28 -4
- package/src/codegen/generateExpression.array.test.js +0 -13
- package/src/codegen/generateExpression.callexpr.test.js +0 -19
- package/src/codegen/generateExpression.test.js +0 -59
- package/src/codegen/generateMethod.asyncawait.test.js +0 -37
- package/src/codegen/generateMethod.ifstatement.test.js +0 -20
- package/src/codegen/generateMethod.test.js +0 -81
- package/src/codegen/generatePage.onmount.test.js +0 -46
- package/src/codegen/generatePage.test.js +0 -138
- package/src/codegen/generateStatement.test.js +0 -31
- package/src/codegen/generateTemplate.ifeach.test.js +0 -138
- package/src/codegen/generateTemplate.test.js +0 -149
- package/src/codegen/generateTemplateExpression.test.js +0 -34
- package/src/compileComponent.test.js +0 -121
- package/src/imports/resolvePackageComponents.js +0 -41
- package/src/lexer/Lexer.test.js +0 -151
- package/src/parser/Parser.array.test.js +0 -37
- package/src/parser/Parser.asyncawait.test.js +0 -33
- package/src/parser/Parser.ifstatement.test.js +0 -20
- package/src/parser/Parser.onmount.test.js +0 -18
- package/src/parser/Parser.test.js +0 -315
- package/src/parser/parseComponent.test.js +0 -53
- package/src/parser/parsePageFile.test.js +0 -101
- package/src/parser/parseTemplate.ifeach.test.js +0 -33
- package/src/parser/parseTemplate.pre.test.js +0 -39
- package/src/parser/parseTemplate.test.js +0 -112
- package/src/renderPageDocument.test.js +0 -125
- package/src/runtime/reactive.test.js +0 -106
- package/test/dashboard-syntax.test.js +0 -116
|
@@ -1,16 +1,216 @@
|
|
|
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
|
|
5
|
-
// circular import is safe in ES
|
|
6
|
-
//
|
|
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.
|
|
7
8
|
|
|
8
|
-
// Word operators (typeof) need a space before their
|
|
9
|
-
// symbolic ones (!,
|
|
9
|
+
// Word operators (typeof, delete, void) need a space before their
|
|
10
|
+
// operand; symbolic ones (!, ~, -, +) must not get one.
|
|
10
11
|
function unaryPrefix(operator) {
|
|
11
12
|
return /^[a-z]/i.test(operator) ? `${operator} ` : operator
|
|
12
13
|
}
|
|
13
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
|
+
|
|
74
|
+
/**
|
|
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).
|
|
80
|
+
*/
|
|
81
|
+
export function generateParams(params, typed = false) {
|
|
82
|
+
return params
|
|
83
|
+
.map((p) => {
|
|
84
|
+
const rest = p.rest ? '...' : ''
|
|
85
|
+
const optional = typed && p.optional && !p.defaultValue ? '?' : ''
|
|
86
|
+
const type = typed
|
|
87
|
+
? `${optional}: ${p.typeAnnotation ?? (p.rest ? 'any[]' : 'any')}`
|
|
88
|
+
: ''
|
|
89
|
+
const def = p.defaultValue
|
|
90
|
+
? ` = ${generateExpression(p.defaultValue, typed)}`
|
|
91
|
+
: ''
|
|
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}`
|
|
99
|
+
})
|
|
100
|
+
.join(', ')
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function statementsInline(body, typed) {
|
|
104
|
+
return body.map((s) => generateStatement(s, typed)).join(' ')
|
|
105
|
+
}
|
|
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
|
+
|
|
14
214
|
/**
|
|
15
215
|
* Compiles a single expression AST node into a JS (or, when
|
|
16
216
|
* typed=true, TypeScript) source string. Used both for method-body
|
|
@@ -18,9 +218,13 @@ function unaryPrefix(operator) {
|
|
|
18
218
|
* and the virtual .ts file handed to the TypeScript compiler API
|
|
19
219
|
* (typed=true) -- one source of truth for expression -> source
|
|
20
220
|
* translation, so the two outputs can never structurally drift from
|
|
21
|
-
* each other. `typed` only changes
|
|
22
|
-
*
|
|
23
|
-
* identically either way.
|
|
221
|
+
* each other. `typed` only changes whether parameters get `: Type`
|
|
222
|
+
* annotations and whether `as` / `!` / generics are kept. Everything
|
|
223
|
+
* else emits identically either way.
|
|
224
|
+
*
|
|
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.
|
|
24
228
|
*/
|
|
25
229
|
export function generateExpression(node, typed = false) {
|
|
26
230
|
switch (node.type) {
|
|
@@ -34,16 +238,17 @@ export function generateExpression(node, typed = false) {
|
|
|
34
238
|
|
|
35
239
|
case 'MemberExpression':
|
|
36
240
|
if (node.computed) {
|
|
37
|
-
return `${
|
|
241
|
+
return `${memberObjectSource(node.object, typed)}${node.optional ? '?.' : ''}[${generateExpression(node.property, typed)}]`
|
|
38
242
|
}
|
|
39
|
-
return `${
|
|
243
|
+
return `${memberObjectSource(node.object, typed)}${node.optional ? '?.' : '.'}${node.property}`
|
|
40
244
|
|
|
41
245
|
case 'NullishCoalescingExpression':
|
|
42
246
|
return `(${generateExpression(node.left, typed)} ?? ${generateExpression(node.right, typed)})`
|
|
43
247
|
|
|
44
248
|
case 'NewExpression': {
|
|
45
249
|
const args = node.args.map((a) => generateExpression(a, typed)).join(', ')
|
|
46
|
-
|
|
250
|
+
const typeArgs = typed && node.typeArgs ? `<${node.typeArgs}>` : ''
|
|
251
|
+
return `new ${generateExpression(node.callee, typed)}${typeArgs}(${args})`
|
|
47
252
|
}
|
|
48
253
|
|
|
49
254
|
case 'BinaryExpression':
|
|
@@ -52,40 +257,90 @@ export function generateExpression(node, typed = false) {
|
|
|
52
257
|
case 'UnaryExpression':
|
|
53
258
|
return `(${unaryPrefix(node.operator)}${generateExpression(node.argument, typed)})`
|
|
54
259
|
|
|
260
|
+
case 'UpdateExpression': {
|
|
261
|
+
const arg = generateExpression(node.argument, typed)
|
|
262
|
+
return node.prefix ? `(${node.operator}${arg})` : `(${arg}${node.operator})`
|
|
263
|
+
}
|
|
264
|
+
|
|
55
265
|
case 'TernaryExpression':
|
|
56
266
|
return `(${generateExpression(node.condition, typed)} ? ${generateExpression(node.consequent, typed)} : ${generateExpression(node.alternate, typed)})`
|
|
57
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
|
+
|
|
58
285
|
case 'ArrowFunctionExpression': {
|
|
59
286
|
// paramTypes is a parallel array of type strings or null,
|
|
60
|
-
// populated by
|
|
287
|
+
// populated by tryParseSyncArrow when a dev writes
|
|
61
288
|
// `f: Post => ...`; absent/null entries mean "no annotation
|
|
62
289
|
// was written" -- in typed mode those fall back to `any`
|
|
63
|
-
// rather than being left bare,
|
|
64
|
-
// .ts arrow function has no
|
|
65
|
-
// real JS does.
|
|
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).
|
|
66
295
|
const paramTypes = node.paramTypes ?? node.params.map(() => null)
|
|
296
|
+
const paramDefaults = node.paramDefaults ?? node.params.map(() => null)
|
|
297
|
+
const paramOptional = node.paramOptional ?? node.params.map(() => false)
|
|
67
298
|
const params = node.params
|
|
68
299
|
.map((name, i) => {
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
300
|
+
let out = name
|
|
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
|
+
}
|
|
306
|
+
if (paramDefaults[i]) {
|
|
307
|
+
out += ` = ${generateExpression(paramDefaults[i], typed)}`
|
|
308
|
+
}
|
|
309
|
+
return out
|
|
72
310
|
})
|
|
73
311
|
.join(', ')
|
|
74
312
|
const asyncPrefix = node.isAsync ? 'async ' : ''
|
|
313
|
+
const generics = typed ? (node.typeParams ?? '') : ''
|
|
314
|
+
const returnType =
|
|
315
|
+
typed && node.returnType ? `: ${node.returnType}` : ''
|
|
75
316
|
|
|
76
317
|
// Block body: `x => { stmt stmt }`. Statements are emitted on
|
|
77
318
|
// one line separated by spaces; multi-line statements (if,
|
|
78
319
|
// for, try) keep their own newlines, which is still valid JS.
|
|
79
320
|
if (node.body.type === 'BlockStatement') {
|
|
80
|
-
|
|
81
|
-
.map((s) => generateStatement(s, typed))
|
|
82
|
-
.join(' ')
|
|
83
|
-
return `${asyncPrefix}(${params}) => { ${stmts} }`
|
|
321
|
+
return `${asyncPrefix}${generics}(${params})${returnType} => { ${statementsInline(node.body.body, typed)} }`
|
|
84
322
|
}
|
|
85
323
|
|
|
86
324
|
// Expression body is always parenthesized so an object literal
|
|
87
325
|
// body (`x => ({ ...x })`) is never parsed as a block.
|
|
88
|
-
return `${asyncPrefix}(${params}) => (${generateExpression(node.body, typed)})`
|
|
326
|
+
return `${asyncPrefix}${generics}(${params})${returnType} => (${generateExpression(node.body, typed)})`
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
case 'FunctionExpression': {
|
|
330
|
+
const { generics, ret } = functionSignature(node, typed)
|
|
331
|
+
const asyncPrefix = node.isAsync ? 'async ' : ''
|
|
332
|
+
const star = node.isGenerator ? '*' : ''
|
|
333
|
+
const name = node.name ? ` ${node.name}` : ''
|
|
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})`
|
|
89
344
|
}
|
|
90
345
|
|
|
91
346
|
case 'TemplateLiteralExpression': {
|
|
@@ -99,18 +354,46 @@ export function generateExpression(node, typed = false) {
|
|
|
99
354
|
return `\`${inner}\``
|
|
100
355
|
}
|
|
101
356
|
|
|
102
|
-
|
|
103
|
-
|
|
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
|
+
}
|
|
104
379
|
|
|
105
380
|
case 'CallExpression': {
|
|
106
381
|
const args = node.args
|
|
107
382
|
.map((a) => generateExpression(a, typed))
|
|
108
383
|
.join(', ')
|
|
109
|
-
|
|
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})`
|
|
110
393
|
}
|
|
111
394
|
|
|
112
395
|
case 'AwaitExpression':
|
|
113
|
-
return `await ${generateExpression(node.argument, typed)}`
|
|
396
|
+
return `(await ${generateExpression(node.argument, typed)})`
|
|
114
397
|
|
|
115
398
|
case 'SpreadElement':
|
|
116
399
|
return `...${generateExpression(node.argument, typed)}`
|
|
@@ -118,21 +401,41 @@ export function generateExpression(node, typed = false) {
|
|
|
118
401
|
case 'ObjectExpression': {
|
|
119
402
|
// Spread entries have key === null and spread === true (see
|
|
120
403
|
// Parser.parseObjectLiteral), so check p.spread before p.key.
|
|
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'.
|
|
121
407
|
const props = node.properties
|
|
122
|
-
.map((p) =>
|
|
123
|
-
p.spread
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
408
|
+
.map((p) => {
|
|
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
|
+
}
|
|
415
|
+
const keySrc = p.keyExpr
|
|
416
|
+
? `[${generateExpression(p.keyExpr, typed)}]`
|
|
417
|
+
: JSON.stringify(p.key)
|
|
418
|
+
if (p.method) {
|
|
419
|
+
const f = p.value
|
|
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} }`
|
|
426
|
+
}
|
|
427
|
+
return `${keySrc}: ${generateExpression(p.value, typed)}`
|
|
428
|
+
})
|
|
127
429
|
.join(', ')
|
|
128
430
|
return `{ ${props} }`
|
|
129
431
|
}
|
|
130
432
|
|
|
433
|
+
// Holes (`null` elements) become empty slots: [1, , 3]
|
|
131
434
|
case 'ArrayExpression': {
|
|
132
|
-
const
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
return `[${
|
|
435
|
+
const parts = node.elements.map((e) =>
|
|
436
|
+
e === null ? '' : generateExpression(e, typed),
|
|
437
|
+
)
|
|
438
|
+
return `[${joinArrayElements(parts)}]`
|
|
136
439
|
}
|
|
137
440
|
|
|
138
441
|
default:
|
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
import { generateStatement } from './generateStatement.js'
|
|
2
|
+
import { generateParams } from './generateExpression.js'
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* Compiles a MethodNode (used for both `computed` and `action` entries)
|
|
5
6
|
* into a JS class method source string, indented for readability in
|
|
6
|
-
* generated output.
|
|
7
|
+
* generated output. Parameters may have defaults (`page = 1`) and rest
|
|
8
|
+
* (`...args`).
|
|
7
9
|
*/
|
|
8
10
|
export function generateMethod(node) {
|
|
9
|
-
const params = node.params
|
|
11
|
+
const params = generateParams(node.params)
|
|
10
12
|
const body = node.body
|
|
11
13
|
.map((stmt) => ` ${generateStatement(stmt)}`)
|
|
12
14
|
.join('\n')
|
|
13
15
|
const asyncPrefix = node.isAsync ? 'async ' : ''
|
|
14
16
|
return ` ${asyncPrefix}${node.name}(${params}) {\n${body}\n }`
|
|
15
|
-
}
|
|
17
|
+
}
|
|
@@ -1,8 +1,36 @@
|
|
|
1
1
|
import { generateMethod } from './generateMethod.js'
|
|
2
2
|
import { generateExpression } from './generateExpression.js'
|
|
3
|
+
import { generateStatement } from './generateStatement.js'
|
|
4
|
+
|
|
5
|
+
function statementSource(stmt) {
|
|
6
|
+
return generateStatement(stmt)
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
// A prop, state field, computed, action or capability that share a
|
|
10
|
+
// name all become members of the same class, so the later definition
|
|
11
|
+
// silently wins (or the constructor throws). Catch it at compile time.
|
|
12
|
+
function assertUniqueMembers(pageNode, className, capabilityNames) {
|
|
13
|
+
const seen = new Map()
|
|
14
|
+
const claim = (name, kind) => {
|
|
15
|
+
if (seen.has(name)) {
|
|
16
|
+
throw new Error(
|
|
17
|
+
`${className}: "${name}" is declared as both ${seen.get(name)} and ${kind}; names must be unique within a page`,
|
|
18
|
+
)
|
|
19
|
+
}
|
|
20
|
+
seen.set(name, kind)
|
|
21
|
+
}
|
|
22
|
+
for (const p of pageNode.props ?? []) claim(p.name, 'a prop')
|
|
23
|
+
for (const s of pageNode.state ?? []) claim(s.name, 'a state field')
|
|
24
|
+
for (const c of pageNode.computed ?? []) claim(c.name, 'a computed')
|
|
25
|
+
for (const a of pageNode.actions ?? []) claim(a.name, 'an action')
|
|
26
|
+
for (const n of capabilityNames) claim(n, 'a capability')
|
|
27
|
+
}
|
|
3
28
|
|
|
4
29
|
/**
|
|
5
30
|
* Compiles a full PageNode into JS source defining a component class.
|
|
31
|
+
* - props are lazy getters over `this.__props`, so a parent that
|
|
32
|
+
* passes `{ get value() { return count } }` stays live. Assigning
|
|
33
|
+
* to a prop stores a local (reactive) override.
|
|
6
34
|
* - state entries become reactive-backed getter/setter pairs, so
|
|
7
35
|
* `this.count` reads/writes go through the reactive() proxy and
|
|
8
36
|
* correctly trigger dependent effects (template re-renders, computed
|
|
@@ -20,9 +48,43 @@ import { generateExpression } from './generateExpression.js'
|
|
|
20
48
|
* @tylix/compiler's runtime).
|
|
21
49
|
*/
|
|
22
50
|
export function generatePage(pageNode, className = 'Page', target = 'client') {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
51
|
+
// pageNode.uses/needs/background may each name capabilities the page
|
|
52
|
+
// reads from directly (Auth.user, Theme.mode, etc.) --
|
|
53
|
+
// substituteCapabilityRefs already treats all three as the same
|
|
54
|
+
// "capability name" pool when rewriting bare references to
|
|
55
|
+
// `this.<Name>`, so the getters generated here must cover the same
|
|
56
|
+
// pool, not just `uses` alone.
|
|
57
|
+
const capabilityRefs = [
|
|
58
|
+
...(pageNode.uses ?? []),
|
|
59
|
+
...(pageNode.needs ?? []),
|
|
60
|
+
...(pageNode.background ?? []),
|
|
61
|
+
]
|
|
62
|
+
const seenCapabilities = new Set()
|
|
63
|
+
const uniqueCapabilityRefs = capabilityRefs.filter((c) => {
|
|
64
|
+
if (seenCapabilities.has(c.name)) return false
|
|
65
|
+
seenCapabilities.add(c.name)
|
|
66
|
+
return true
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
assertUniqueMembers(pageNode, className, seenCapabilities)
|
|
70
|
+
|
|
71
|
+
const hasProps = pageNode.props.length > 0
|
|
72
|
+
const propInit = hasProps
|
|
73
|
+
? ` this.__props = props;\n this.__propOverrides = reactive({});\n`
|
|
74
|
+
: ''
|
|
75
|
+
|
|
76
|
+
const propAccessors = pageNode.props
|
|
77
|
+
.map(
|
|
78
|
+
(p) => ` get ${p.name}() {
|
|
79
|
+
const overrides = this.__propOverrides;
|
|
80
|
+
const local = overrides.${p.name};
|
|
81
|
+
return Object.prototype.hasOwnProperty.call(overrides, ${JSON.stringify(p.name)}) ? local : this.__props.${p.name};
|
|
82
|
+
}
|
|
83
|
+
set ${p.name}(value) {
|
|
84
|
+
this.__propOverrides.${p.name} = value;
|
|
85
|
+
}`,
|
|
86
|
+
)
|
|
87
|
+
.join('\n\n')
|
|
26
88
|
|
|
27
89
|
const stateInit = pageNode.state
|
|
28
90
|
.map((s) => ` ${s.name}: ${generateExpression(s.value)},`)
|
|
@@ -39,28 +101,6 @@ export function generatePage(pageNode, className = 'Page', target = 'client') {
|
|
|
39
101
|
)
|
|
40
102
|
.join('\n\n')
|
|
41
103
|
|
|
42
|
-
// pageNode.uses may be absent on older/pre-capability ASTs (e.g.
|
|
43
|
-
// anything compiled before this field existed), so default to []
|
|
44
|
-
// rather than assuming every caller has been updated.
|
|
45
|
-
// pageNode.uses/needs/background may each name capabilities the page
|
|
46
|
-
// reads from directly (Auth.user, Theme.mode, etc.) -- substituteCapabilityRefs
|
|
47
|
-
// already treats all three as the same "capability name" pool when
|
|
48
|
-
// rewriting bare references to `this.<Name>`, so the getters generated
|
|
49
|
-
// here must cover the same pool, not just `uses` alone, or a
|
|
50
|
-
// needs-only or background-only capability resolves to undefined at
|
|
51
|
-
// runtime with no compile-time signal that anything's wrong.
|
|
52
|
-
const capabilityRefs = [
|
|
53
|
-
...(pageNode.uses ?? []),
|
|
54
|
-
...(pageNode.needs ?? []),
|
|
55
|
-
...(pageNode.background ?? []),
|
|
56
|
-
]
|
|
57
|
-
const seenCapabilities = new Set()
|
|
58
|
-
const uniqueCapabilityRefs = capabilityRefs.filter((c) => {
|
|
59
|
-
if (seenCapabilities.has(c.name)) return false
|
|
60
|
-
seenCapabilities.add(c.name)
|
|
61
|
-
return true
|
|
62
|
-
})
|
|
63
|
-
|
|
64
104
|
const usesAccessors = uniqueCapabilityRefs
|
|
65
105
|
.map(
|
|
66
106
|
(u) => ` get ${u.name}() {
|
|
@@ -112,14 +152,12 @@ export function generatePage(pageNode, className = 'Page', target = 'client') {
|
|
|
112
152
|
// contains the onMount call OR its method body -- there's no
|
|
113
153
|
// runtime guard to rely on, because the code simply isn't there.
|
|
114
154
|
//
|
|
115
|
-
//
|
|
116
|
-
//
|
|
117
|
-
//
|
|
118
|
-
//
|
|
119
|
-
//
|
|
120
|
-
//
|
|
121
|
-
// is responsible for awaiting __ready() and then calling __onMount()
|
|
122
|
-
// explicitly, in that order.
|
|
155
|
+
// onMount is not invoked from inside the constructor: pages that
|
|
156
|
+
// declare `needs` capabilities must have those capabilities' async
|
|
157
|
+
// init() fully resolved (via __ready()) before onMount runs. The
|
|
158
|
+
// caller (renderPageDocument.js) awaits __ready() and then calls
|
|
159
|
+
// __onMount() explicitly, in that order -- for pages, layouts and
|
|
160
|
+
// child components alike.
|
|
123
161
|
const onMountMethod =
|
|
124
162
|
pageNode.onMount && target === 'client'
|
|
125
163
|
? (() => {
|
|
@@ -133,19 +171,11 @@ export function generatePage(pageNode, className = 'Page', target = 'client') {
|
|
|
133
171
|
|
|
134
172
|
return `class ${className} {
|
|
135
173
|
constructor(props = {}) {
|
|
136
|
-
${
|
|
174
|
+
${propInit} this.__state = reactive({
|
|
137
175
|
${stateInit}
|
|
138
176
|
});
|
|
139
177
|
${backgroundResolution ? backgroundResolution + '\n' : ''} }
|
|
140
178
|
|
|
141
|
-
${[stateAccessors, usesAccessors, computedGetters, actionMethods, readyMethod, onMountMethod].filter(Boolean).join('\n\n')}
|
|
179
|
+
${[propAccessors, stateAccessors, usesAccessors, computedGetters, actionMethods, readyMethod, onMountMethod].filter(Boolean).join('\n\n')}
|
|
142
180
|
}`
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
// Local import kept separate from generateMethod's own statement
|
|
146
|
-
// formatting so computed getters and state accessors can share the
|
|
147
|
-
// same statement codegen without generateMethod's parameter handling.
|
|
148
|
-
import { generateStatement } from './generateStatement.js'
|
|
149
|
-
function statementSource(stmt) {
|
|
150
|
-
return generateStatement(stmt)
|
|
151
|
-
}
|
|
181
|
+
}
|