@slim-lang/core 1.2.11 → 1.2.13
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/README.md +522 -14
- package/package.json +2 -6
- package/packages/slim/server/main.slim +433 -422
- package/run-dev-slim.js +10 -5
- package/run-slim.js +10 -20
- package/src/bin/api/github_get.js +7 -12
- package/src/bin/api/github_req.js +54 -241
- package/src/bin/api/lock.js +2 -1
- package/src/bin/api/spm.js +20 -91
- package/src/bin/cli.js +73 -102
- package/src/bin/config.default.json +11 -11
- package/src/bin/helpers.js +2 -7
- package/src/bin/spm.js +3 -7
- package/src/checker.js +1705 -388
- package/src/compile.js +131 -100
- package/src/external/classErrors.js +5 -6
- package/src/external/client.js +0 -2
- package/src/external/core.js +355 -237
- package/src/external/defaults.js +12 -4
- package/src/external/dom.js +663 -0
- package/src/external/helpers.js +87 -58
- package/src/external/reactive.js +601 -0
- package/src/external/router.js +117 -0
- package/src/external/slim-globals.d.ts +43 -4
- package/src/external/typeSyntax.js +258 -0
- package/src/external/types.js +1 -1
- package/src/format.js +183 -12
- package/src/handlers/errorHandler.js +9 -36
- package/src/jsdoc.js +36 -16
- package/src/modulePaths.js +15 -5
- package/src/reactivity.js +774 -0
- package/src/repl.js +1 -1
- package/src/suggest.js +60 -0
- package/src/syntax/babel.js +46 -0
- package/src/syntax/index.js +39 -0
- package/src/syntax/lower.js +666 -0
- package/src/syntax/markup.js +195 -0
- package/src/syntax/plugin.js +903 -0
- package/src/syntax/types.js +106 -0
- package/src/test-runner.js +5 -5
- package/src/transform.js +209 -244
- package/packages/slim/helpers/string.js +0 -43
- package/packages/slim/types/hash.js +0 -11
- package/src/handlers/parser/components.js +0 -295
- package/src/handlers/parserHandler.js +0 -789
- package/src/lexer.js +0 -174
- package/src/parser.js +0 -803
- package/src/sourcemap.js +0 -0
|
@@ -0,0 +1,666 @@
|
|
|
1
|
+
import * as t from "@babel/types"
|
|
2
|
+
import _generate from "@babel/generator"
|
|
3
|
+
import { babel, slimSyntaxError } from "./plugin.js"
|
|
4
|
+
import { readConfig } from "../modulePaths.js"
|
|
5
|
+
import { typeFromAST } from "./types.js"
|
|
6
|
+
import { ANY, formatType, readType, substituteType } from "../external/typeSyntax.js"
|
|
7
|
+
|
|
8
|
+
const generate = _generate.default ?? _generate
|
|
9
|
+
|
|
10
|
+
const SKIP_KEYS = new Set([
|
|
11
|
+
"loc", "start", "end", "extra", "range", "leadingComments", "trailingComments", "innerComments",
|
|
12
|
+
"typeAnnotation", "returnType", "typeParameters", "typeArguments", "superTypeParameters"
|
|
13
|
+
])
|
|
14
|
+
|
|
15
|
+
const PREFIX_CALLS = {
|
|
16
|
+
sizeof: "__sizeof__",
|
|
17
|
+
kindof: "type",
|
|
18
|
+
empty: "__is_empty__",
|
|
19
|
+
copyof: "__copyof__",
|
|
20
|
+
lock: "__lock_object__"
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const NOT_STRUCTS = new Set(["any", "object"])
|
|
24
|
+
|
|
25
|
+
function returnsOf(node, found = []) {
|
|
26
|
+
if (!isNode(node) || /Function|ClassMethod|ObjectMethod/.test(node.type)) return found
|
|
27
|
+
if (node.type === "ReturnStatement" && node.argument) found.push(node)
|
|
28
|
+
for (const [key, value] of Object.entries(node)) {
|
|
29
|
+
if (SKIP_KEYS.has(key)) continue
|
|
30
|
+
if (Array.isArray(value)) value.forEach(child => returnsOf(child, found))
|
|
31
|
+
else if (isNode(value)) returnsOf(value, found)
|
|
32
|
+
}
|
|
33
|
+
return found
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function typeParamNames(node) {
|
|
37
|
+
const params = Array.isArray(node.typeParameters) ? node.typeParameters : node.typeParameters?.params ?? []
|
|
38
|
+
return params.map(param => typeof param.name === "string" ? param.name : param.name?.name).filter(Boolean)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const isNode = value => !!value && typeof value === "object" && typeof value.type === "string"
|
|
42
|
+
|
|
43
|
+
function withLoc(node, from) {
|
|
44
|
+
if (from && typeof from.start === "number") {
|
|
45
|
+
node.start = from.start
|
|
46
|
+
node.end = from.end
|
|
47
|
+
node.loc = from.loc
|
|
48
|
+
}
|
|
49
|
+
return node
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function forgetLoc(node) {
|
|
53
|
+
if (!node || typeof node !== "object") return
|
|
54
|
+
if (Array.isArray(node)) return node.forEach(forgetLoc)
|
|
55
|
+
delete node.start
|
|
56
|
+
delete node.end
|
|
57
|
+
delete node.loc
|
|
58
|
+
for (const [key, value] of Object.entries(node)) {
|
|
59
|
+
if (key !== "extra" && value && typeof value === "object") forgetLoc(value)
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const id = name => t.identifier(name)
|
|
64
|
+
const str = value => t.stringLiteral(value)
|
|
65
|
+
const call = (name, args) => t.callExpression(id(name), args)
|
|
66
|
+
|
|
67
|
+
function escapeTemplateText(text) {
|
|
68
|
+
return text.replace(/\\|`|\$\{/g, match => "\\" + match)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function escapeMarkupText(text) {
|
|
72
|
+
return text.replace(/\\[\s\S]|`/g, match => match === "`" ? "\\`" : match)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function keyName(key) {
|
|
76
|
+
if (!key) return null
|
|
77
|
+
if (key.type === "Identifier") return key.name
|
|
78
|
+
if (key.type === "StringLiteral") return key.value
|
|
79
|
+
if (key.type === "PrivateName") return `#${key.id.name}`
|
|
80
|
+
return null
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
class Lowering {
|
|
84
|
+
constructor(code, sourceFile) {
|
|
85
|
+
this.code = code
|
|
86
|
+
this.sourceFile = sourceFile
|
|
87
|
+
this.typeParams = []
|
|
88
|
+
this.stateDeclarations = []
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
fail(node, message) {
|
|
92
|
+
throw slimSyntaxError(this.code, node.start ?? 0, message)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
type(annotation, { keepTypeParams = false } = {}) {
|
|
96
|
+
const type = typeFromAST(annotation, (node, message) => this.fail(node, message))
|
|
97
|
+
if (keepTypeParams || this.typeParams.length === 0) return type
|
|
98
|
+
return substituteType(type, new Map(this.typeParams.map(name => [name, ANY])))
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
label(annotation, options) {
|
|
102
|
+
return formatType(this.type(annotation, options))
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
visit(node, parent) {
|
|
106
|
+
const typeParams = typeParamNames(node)
|
|
107
|
+
this.typeParams.push(...typeParams)
|
|
108
|
+
try {
|
|
109
|
+
return this.visitChildren(node, parent)
|
|
110
|
+
} finally {
|
|
111
|
+
this.typeParams.length -= typeParams.length
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
visitChildren(node, parent) {
|
|
116
|
+
for (const key of Object.keys(node)) {
|
|
117
|
+
if (SKIP_KEYS.has(key)) continue
|
|
118
|
+
const value = node[key]
|
|
119
|
+
if (Array.isArray(value)) {
|
|
120
|
+
node[key] = value.flatMap(child => {
|
|
121
|
+
if (!isNode(child)) return [child]
|
|
122
|
+
const lowered = this.visit(child, node)
|
|
123
|
+
return lowered === null ? [] : [lowered]
|
|
124
|
+
})
|
|
125
|
+
} else if (isNode(value)) {
|
|
126
|
+
node[key] = this.visit(value, node)
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const handler = this[node.type]
|
|
131
|
+
return typeof handler === "function" ? handler.call(this, node, parent) : node
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
SlimUnaryExpression(node) {
|
|
136
|
+
return withLoc(call(PREFIX_CALLS[node.operator], [node.argument]), node)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
SlimBinaryExpression(node) {
|
|
140
|
+
return withLoc(call("__intdiv__", [node.left, node.right]), node)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
SlimMarkup(node) {
|
|
144
|
+
const quasis = node.quasis.map((text, index) => {
|
|
145
|
+
const raw = escapeMarkupText(text)
|
|
146
|
+
return t.templateElement({ raw, cooked: raw }, index === node.quasis.length - 1)
|
|
147
|
+
})
|
|
148
|
+
const markup = t.taggedTemplateExpression(id("__html__"), t.templateLiteral(quasis, node.expressions))
|
|
149
|
+
markup._slimMarkup = true
|
|
150
|
+
markup._slimQuasis = node.quasis
|
|
151
|
+
return withLoc(markup, node)
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
SlimMatchExpression(node) {
|
|
155
|
+
const statements = []
|
|
156
|
+
let fallback = t.returnStatement(id("undefined"))
|
|
157
|
+
|
|
158
|
+
for (const arm of node.arms) {
|
|
159
|
+
if (arm.typeAnnotation) {
|
|
160
|
+
const label = this.label(arm.typeAnnotation)
|
|
161
|
+
const declarator = t.variableDeclarator(withLoc(id(arm.binding.name), arm.binding), id("__match"))
|
|
162
|
+
declarator._slimType = label
|
|
163
|
+
const result = t.returnStatement(arm.result)
|
|
164
|
+
const body = [t.variableDeclaration("const", [declarator]), arm.guard ? t.ifStatement(arm.guard, result) : result]
|
|
165
|
+
statements.push(t.ifStatement(call("__match_type__", [id("__match"), str(label)]), t.blockStatement(body)))
|
|
166
|
+
} else if (arm.guard) {
|
|
167
|
+
const body = []
|
|
168
|
+
if (arm.binding) body.push(t.variableDeclaration("const", [t.variableDeclarator(id(arm.binding.name), id("__match"))]))
|
|
169
|
+
body.push(t.ifStatement(arm.guard, t.returnStatement(arm.result)))
|
|
170
|
+
statements.push(t.blockStatement(body))
|
|
171
|
+
} else if (arm.wildcard) {
|
|
172
|
+
fallback = t.returnStatement(arm.result)
|
|
173
|
+
} else {
|
|
174
|
+
statements.push(t.ifStatement(call("__match_eq__", [id("__match"), arm.pattern]), t.returnStatement(arm.result)))
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const fn = t.arrowFunctionExpression([id("__match")], t.blockStatement([...statements, fallback]))
|
|
179
|
+
return withLoc(t.callExpression(fn, [node.discriminant]), node)
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
functionName(node, parent) {
|
|
184
|
+
if (node.id) return node.id.name
|
|
185
|
+
const own = keyName(node.key)
|
|
186
|
+
if (own) return own
|
|
187
|
+
if (!parent) return "function"
|
|
188
|
+
if (parent.type === "VariableDeclarator" && parent.id.type === "Identifier") return parent.id.name
|
|
189
|
+
if (parent.type === "ObjectProperty" || parent.type === "ClassProperty" || parent.type === "ClassPrivateProperty") {
|
|
190
|
+
return keyName(parent.key) ?? "function"
|
|
191
|
+
}
|
|
192
|
+
if (parent.type === "AssignmentExpression" && parent.left.type === "Identifier") return parent.left.name
|
|
193
|
+
return "function"
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
typedParameter(name, label, optional, index, fnName) {
|
|
197
|
+
const type = readType(label)
|
|
198
|
+
const expected = (type.kind === "union" ? type.types : [type]).map(formatType).join(" or ")
|
|
199
|
+
const message = optional
|
|
200
|
+
? `${fnName}: argument "${name}" expected ${expected}`
|
|
201
|
+
: `function "${fnName}": argument<${index}> "${name}" expected ${expected}`
|
|
202
|
+
const text = escapeTemplateText(`${message}, got `)
|
|
203
|
+
const template = t.templateLiteral(
|
|
204
|
+
[t.templateElement({ raw: text, cooked: `${message}, got ` }), t.templateElement({ raw: "", cooked: "" }, true)],
|
|
205
|
+
[call("type", [id(name)])]
|
|
206
|
+
)
|
|
207
|
+
return t.expressionStatement(call("__typed_parameter__", [id(name), str(label), str(name), t.booleanLiteral(optional), template]))
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
asStruct(value, label) {
|
|
211
|
+
const literal = value?.type === "ObjectExpression" ||
|
|
212
|
+
(value?.type === "ArrayExpression" && value.elements.some(element => element?.type === "ObjectExpression"))
|
|
213
|
+
if (!literal || NOT_STRUCTS.has(label)) return value
|
|
214
|
+
return withLoc(call("__as_struct__", [value, str(label)]), value)
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
lowerFunction(node, parent) {
|
|
218
|
+
const name = this.functionName(node, parent)
|
|
219
|
+
const checks = []
|
|
220
|
+
|
|
221
|
+
if (this.typeParams.length > 0) {
|
|
222
|
+
const keep = annotation => annotation ? this.label(annotation, { keepTypeParams: true }) : null
|
|
223
|
+
node._slimSignature = {
|
|
224
|
+
typeParams: typeParamNames(node),
|
|
225
|
+
params: node.params.map(param => {
|
|
226
|
+
const target = param.type === "AssignmentPattern" ? param.left : param.type === "RestElement" ? param.argument : param
|
|
227
|
+
return keep(param.typeAnnotation ?? target.typeAnnotation)
|
|
228
|
+
}),
|
|
229
|
+
optional: node.params.map(param => !!param.optional),
|
|
230
|
+
returns: keep(node.returnType)
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
node.params.forEach((param, index) => {
|
|
235
|
+
const target = param.type === "AssignmentPattern" ? param.left : param.type === "RestElement" ? param.argument : param
|
|
236
|
+
const annotation = param.typeAnnotation ?? target.typeAnnotation
|
|
237
|
+
if (!annotation || target.type !== "Identifier") return
|
|
238
|
+
|
|
239
|
+
const label = this.label(annotation)
|
|
240
|
+
if (label === "any") return
|
|
241
|
+
checks.push(this.typedParameter(target.name, label, !!target.optional, index, name))
|
|
242
|
+
})
|
|
243
|
+
|
|
244
|
+
if (node.returnType) {
|
|
245
|
+
const label = this.label(node.returnType)
|
|
246
|
+
checks.push(t.expressionStatement(call("__declare_return__", [str(label), str(name)])))
|
|
247
|
+
if (node.body.type === "BlockStatement") {
|
|
248
|
+
for (const statement of returnsOf(node.body)) statement.argument = this.asStruct(statement.argument, label)
|
|
249
|
+
} else {
|
|
250
|
+
node.body = this.asStruct(node.body, label)
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
if (checks.length === 0) return node
|
|
254
|
+
|
|
255
|
+
if (node.body.type === "BlockStatement") {
|
|
256
|
+
node.body.body.unshift(...checks)
|
|
257
|
+
} else {
|
|
258
|
+
node.body = t.blockStatement([...checks, t.returnStatement(node.body)])
|
|
259
|
+
node.expression = false
|
|
260
|
+
}
|
|
261
|
+
return node
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
FunctionDeclaration(node, parent) { return this.lowerFunction(node, parent) }
|
|
265
|
+
FunctionExpression(node, parent) { return this.lowerFunction(node, parent) }
|
|
266
|
+
ObjectMethod(node, parent) { return this.lowerFunction(node, parent) }
|
|
267
|
+
ClassMethod(node, parent) { return this.lowerFunction(node, parent) }
|
|
268
|
+
ClassPrivateMethod(node, parent) { return this.lowerFunction(node, parent) }
|
|
269
|
+
|
|
270
|
+
ArrowFunctionExpression(node, parent) {
|
|
271
|
+
return this.lowerFunction(node, parent)
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
VariableDeclaration(node) {
|
|
276
|
+
if (!node.slimState) return node
|
|
277
|
+
const [declarator] = node.declarations
|
|
278
|
+
if (node.declarations.length !== 1 || declarator.id.type !== "Identifier" || !declarator.init) {
|
|
279
|
+
this.fail(node, "A state needs a name and a starting value: state count = 0")
|
|
280
|
+
}
|
|
281
|
+
this.stateDeclarations.push(node)
|
|
282
|
+
return node
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
VariableDeclarator(node) {
|
|
286
|
+
const annotation = node.id.typeAnnotation
|
|
287
|
+
if (!annotation || !node.init) return node
|
|
288
|
+
|
|
289
|
+
const label = this.label(annotation)
|
|
290
|
+
node.init = this.asStruct(node.init, label)
|
|
291
|
+
node.init = node.id.type === "Identifier"
|
|
292
|
+
? withLoc(call("__typed_variable__", [node.init, str(label), str(node.id.name)]), node.init)
|
|
293
|
+
: withLoc(call("__typed_pattern__", [node.init, str(label)]), node.init)
|
|
294
|
+
return node
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
ClassProperty(node) {
|
|
298
|
+
if (!node.typeAnnotation || !node.value) return node
|
|
299
|
+
node.value = withLoc(call("__typed_variable__", [node.value, str(this.label(node.typeAnnotation)), str(keyName(node.key) ?? "field")]), node.value)
|
|
300
|
+
return node
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
ClassPrivateProperty(node) {
|
|
304
|
+
return this.ClassProperty(node)
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
declare(node, init) {
|
|
309
|
+
const declarator = t.variableDeclarator(withLoc(id(node.id.name), node.id), init)
|
|
310
|
+
return withLoc(t.variableDeclaration("const", [declarator]), node)
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
SlimStructDeclaration(node) {
|
|
314
|
+
const name = node.id.name
|
|
315
|
+
const schema = node.fields.map(field =>
|
|
316
|
+
t.objectProperty(str((field.optional ? "*" : "") + field.key.name), str(this.label(field.typeAnnotation, { keepTypeParams: true }))))
|
|
317
|
+
const defaults = node.fields
|
|
318
|
+
.filter(field => field.value)
|
|
319
|
+
.map(field => t.objectProperty(str(field.key.name), t.arrowFunctionExpression([], field.value)))
|
|
320
|
+
const methods = node.methods.map(method => {
|
|
321
|
+
const fn = withLoc(t.functionExpression(null, method.params, method.body, method.generator, method.async), method)
|
|
322
|
+
fn._slimSignature = method._slimSignature
|
|
323
|
+
return t.objectProperty(str(keyName(method.key)), fn)
|
|
324
|
+
})
|
|
325
|
+
const readonly = node.fields.filter(field => field.readonly).map(field => str(field.key.name))
|
|
326
|
+
|
|
327
|
+
const args = [
|
|
328
|
+
str(name),
|
|
329
|
+
t.objectExpression(schema),
|
|
330
|
+
t.objectExpression([]),
|
|
331
|
+
t.objectExpression(defaults),
|
|
332
|
+
node.superName ? str(node.superName.name) : t.nullLiteral(),
|
|
333
|
+
methods.length ? t.objectExpression(methods) : t.nullLiteral(),
|
|
334
|
+
node.typeParameters.length ? t.arrayExpression(node.typeParameters.map(param => str(param.name))) : t.nullLiteral(),
|
|
335
|
+
readonly.length ? t.arrayExpression(readonly) : t.nullLiteral()
|
|
336
|
+
]
|
|
337
|
+
while (args.length > 4 && t.isNullLiteral(args[args.length - 1])) args.pop()
|
|
338
|
+
|
|
339
|
+
return this.declare(node, withLoc(call("__def_struct__", args), node))
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
SlimEnumDeclaration(node) {
|
|
343
|
+
const members = node.members.map(member =>
|
|
344
|
+
t.objectProperty(str(member.key.name), member.value ?? str(member.key.name)))
|
|
345
|
+
return this.declare(node, withLoc(call("__def_enum__", [str(node.id.name), t.objectExpression(members)]), node))
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
typeDef(node, value, properties) {
|
|
349
|
+
const props = t.objectExpression(Object.entries(properties).map(([key, entry]) => t.objectProperty(str(key), str(entry))))
|
|
350
|
+
return this.declare(node, withLoc(call("__type_def__", [str(node.id.name), value, props]), node))
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
SlimTypeDeclaration(node) {
|
|
354
|
+
if (node.kind === "alias") return this.typeDef(node, str(this.label(node.typeAnnotation)), { type: "one-line-expr" })
|
|
355
|
+
if (node.kind === "typeof") return this.typeDef(node, node.expression, { type: "one-line-expr" })
|
|
356
|
+
if (node.kind === "extends") {
|
|
357
|
+
const label = this.label(node.typeAnnotation)
|
|
358
|
+
return this.typeDef(node, str(label), { type: "one-line-expr", extends: label })
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
const { validator } = node
|
|
362
|
+
const statements = validator.body.body
|
|
363
|
+
const empty = statements.length === 0 ||
|
|
364
|
+
(statements.length === 1 && t.isReturnStatement(statements[0]) && !statements[0].argument)
|
|
365
|
+
const body = empty ? t.blockStatement([t.returnStatement(t.booleanLiteral(true))]) : validator.body
|
|
366
|
+
const fn = withLoc(t.arrowFunctionExpression(validator.params, body), validator)
|
|
367
|
+
|
|
368
|
+
return this.typeDef(node, fn, node.superType ? { extends: this.label(node.superType) } : {})
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
TSTypeAliasDeclaration(node) {
|
|
372
|
+
return this.typeDef(node, str(this.label(node.typeAnnotation)), { type: "one-line-expr" })
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
SlimUseDeclaration(node) {
|
|
376
|
+
const expression = node.specifier === null
|
|
377
|
+
? call("__use_all__", [str(node.source)])
|
|
378
|
+
: call("__use__", [str(node.specifier), str(node.source)])
|
|
379
|
+
return withLoc(t.expressionStatement(expression), node)
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
SlimModeStatement() {
|
|
383
|
+
return null
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
SlimComponentDeclaration(node) {
|
|
387
|
+
const component = buildComponent(node, this)
|
|
388
|
+
component._slimComponentProps = componentProps(node, this)
|
|
389
|
+
return this.declare(node, component)
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
Program(node) {
|
|
394
|
+
node.body = node.body.flatMap(statement => {
|
|
395
|
+
if (statement.type !== "ExportDefaultDeclaration" || statement.declaration.type !== "VariableDeclaration") {
|
|
396
|
+
return [statement]
|
|
397
|
+
}
|
|
398
|
+
const declaration = statement.declaration
|
|
399
|
+
const [first] = declaration.declarations
|
|
400
|
+
if (declaration.declarations.length !== 1 || first.id.type !== "Identifier") {
|
|
401
|
+
this.fail(statement, "export default needs a single named declaration")
|
|
402
|
+
}
|
|
403
|
+
return [declaration, t.exportNamedDeclaration(null, [t.exportSpecifier(id(first.id.name), id("default"))])]
|
|
404
|
+
})
|
|
405
|
+
for (const statement of node.body) {
|
|
406
|
+
const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement
|
|
407
|
+
if (declaration?.slimState) declaration._slimStateOk = true
|
|
408
|
+
}
|
|
409
|
+
const stray = this.stateDeclarations.find(declaration => !declaration._slimStateOk)
|
|
410
|
+
if (stray) this.fail(stray, "state can only be declared at the top of a component body or a module")
|
|
411
|
+
return node
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
let bemCache = null
|
|
417
|
+
function useBEMClasses() {
|
|
418
|
+
if (bemCache !== null) return bemCache
|
|
419
|
+
bemCache = readConfig().components?.useBEMClasses === true
|
|
420
|
+
return bemCache
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
function kebabCase(name) {
|
|
424
|
+
return name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/[_\s]+/g, "-").toLowerCase()
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
function elementTag(node, lowering) {
|
|
428
|
+
if (!node.tag) return `slim-${kebabCase(node.id.name)}`
|
|
429
|
+
if (!node.tag.includes("-")) {
|
|
430
|
+
lowering.fail(node, `Component "${node.id.name}": a custom element tag must contain a hyphen, got "${node.tag}"`)
|
|
431
|
+
}
|
|
432
|
+
return node.tag
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
function parseTemplate(code) {
|
|
436
|
+
const program = babel.parse(code, { sourceType: "module", allowReturnOutsideFunction: true }).program
|
|
437
|
+
forgetLoc(program)
|
|
438
|
+
return program.body
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
function fill(node, slots) {
|
|
442
|
+
if (Array.isArray(node)) {
|
|
443
|
+
return node.flatMap(child => {
|
|
444
|
+
if (t.isExpressionStatement(child) && t.isIdentifier(child.expression) && child.expression.name in slots) {
|
|
445
|
+
return slots[child.expression.name]
|
|
446
|
+
}
|
|
447
|
+
return [fill(child, slots)]
|
|
448
|
+
})
|
|
449
|
+
}
|
|
450
|
+
if (!isNode(node)) return node
|
|
451
|
+
if (t.isIdentifier(node) && node.name in slots) return slots[node.name]
|
|
452
|
+
for (const [key, value] of Object.entries(node)) {
|
|
453
|
+
if (Array.isArray(value) || isNode(value)) node[key] = fill(value, slots)
|
|
454
|
+
}
|
|
455
|
+
return node
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
const HOOKS = `const __mounts__ = [];
|
|
459
|
+
const __connects__ = [];
|
|
460
|
+
const __unmounts__ = [];
|
|
461
|
+
const onMount = fn => __mounts__.push(fn);
|
|
462
|
+
const onConnect = fn => __connects__.push(fn);
|
|
463
|
+
const onUnmount = fn => __unmounts__.push(fn);`
|
|
464
|
+
|
|
465
|
+
function componentBinding(params) {
|
|
466
|
+
if (params.items.length === 0) return null
|
|
467
|
+
if (!params.pattern) return id(params.items[0].name.name)
|
|
468
|
+
|
|
469
|
+
return t.objectPattern(params.items.map(item => {
|
|
470
|
+
const value = item.value ? t.assignmentPattern(id(item.name.name), item.value) : id(item.name.name)
|
|
471
|
+
return t.objectProperty(id(item.name.name), value, false, true)
|
|
472
|
+
}))
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
function componentProps(node, lowering) {
|
|
476
|
+
const { items, pattern } = node.params
|
|
477
|
+
if (!pattern) {
|
|
478
|
+
const [item] = items
|
|
479
|
+
return item?.typeAnnotation ? { type: lowering.label(item.typeAnnotation) } : null
|
|
480
|
+
}
|
|
481
|
+
return {
|
|
482
|
+
fields: items.map(item => ({
|
|
483
|
+
name: item.name.name,
|
|
484
|
+
type: item.typeAnnotation ? lowering.label(item.typeAnnotation) : null,
|
|
485
|
+
optional: !!item.optional || !!item.value || !item.typeAnnotation
|
|
486
|
+
}))
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
function componentChecks(node, lowering) {
|
|
491
|
+
return node.params.items.flatMap((item, index) => {
|
|
492
|
+
if (!item.typeAnnotation) return []
|
|
493
|
+
const label = lowering.label(item.typeAnnotation)
|
|
494
|
+
if (label === "any") return []
|
|
495
|
+
return [lowering.typedParameter(item.name.name, label, item.optional, index, node.id.name)]
|
|
496
|
+
})
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
function elementExpression(markup, name) {
|
|
500
|
+
const vdom = call("htmlToVdom", [markup])
|
|
501
|
+
if (!useBEMClasses()) return t.callExpression(t.memberExpression(vdom, id("toElement")), [])
|
|
502
|
+
|
|
503
|
+
const [statement] = parseTemplate(`(() => {
|
|
504
|
+
const __v__ = __SLIM_VDOM__;
|
|
505
|
+
__resolve_bem__(__v__, ${JSON.stringify(kebabCase(name))});
|
|
506
|
+
return __v__.toElement();
|
|
507
|
+
})()`)
|
|
508
|
+
return fill(statement, { __SLIM_VDOM__: vdom }).expression
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
function componentFunction(node) {
|
|
512
|
+
if (!isNode(node)) return null
|
|
513
|
+
if (t.isArrowFunctionExpression(node) && t.isCallExpression(node.body) && t.isIdentifier(node.body.callee, { name: "__component__" })) {
|
|
514
|
+
return node
|
|
515
|
+
}
|
|
516
|
+
for (const value of Object.values(node)) {
|
|
517
|
+
const found = Array.isArray(value) ? value.map(componentFunction).find(Boolean) : componentFunction(value)
|
|
518
|
+
if (found) return found
|
|
519
|
+
}
|
|
520
|
+
return null
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
function buildComponent(node, lowering) {
|
|
524
|
+
const name = node.id.name
|
|
525
|
+
const statements = node.body.body
|
|
526
|
+
const returnIndex = statements.findIndex(statement => t.isReturnStatement(statement))
|
|
527
|
+
if (returnIndex === -1 || !statements[returnIndex].argument) lowering.fail(node, `Component "${name}" must contain return`)
|
|
528
|
+
|
|
529
|
+
for (const statement of statements) {
|
|
530
|
+
if (!statement.slimState) continue
|
|
531
|
+
if (node.modifier === "isolated") lowering.fail(statement, "An isolated component can't have state")
|
|
532
|
+
statement._slimStateOk = true
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
const before = statements.slice(0, returnIndex)
|
|
536
|
+
const returned = statements[returnIndex].argument
|
|
537
|
+
const markup = returned._slimMarkup
|
|
538
|
+
? returned
|
|
539
|
+
: t.taggedTemplateExpression(id("__html__"), t.templateLiteral(
|
|
540
|
+
[t.templateElement({ raw: "", cooked: "" }), t.templateElement({ raw: "", cooked: "" }, true)],
|
|
541
|
+
[returned]
|
|
542
|
+
))
|
|
543
|
+
if (!returned._slimMarkup) {
|
|
544
|
+
markup._slimMarkup = true
|
|
545
|
+
markup._slimQuasis = ["", ""]
|
|
546
|
+
}
|
|
547
|
+
const element = elementExpression(markup, name)
|
|
548
|
+
element._slimRoot = markup
|
|
549
|
+
const checks = componentChecks(node, lowering)
|
|
550
|
+
const binding = componentBinding(node.params)
|
|
551
|
+
const info = { name, bem: useBEMClasses() ? kebabCase(name) : null }
|
|
552
|
+
|
|
553
|
+
if (node.modifier === "isolated") {
|
|
554
|
+
const tail = fill(parseTemplate(`const __el__ = __SLIM_ELEMENT__;
|
|
555
|
+
for (const fn of __mounts__) fn(__el__);
|
|
556
|
+
__lifecycle__(__el__, __connects__, __unmounts__);
|
|
557
|
+
return __el__;`), { __SLIM_ELEMENT__: element })
|
|
558
|
+
const bodyCode = generate(t.program([...parseTemplate(HOOKS), ...before, ...tail]), { compact: true }).code
|
|
559
|
+
const bindingCode = binding ? generate(binding).code : ""
|
|
560
|
+
const guard = checks.length && binding
|
|
561
|
+
? [t.variableDeclaration("const", [t.variableDeclarator(binding, id("__props__"))]), ...checks]
|
|
562
|
+
: []
|
|
563
|
+
|
|
564
|
+
const [statement] = parseTemplate(`(() => {
|
|
565
|
+
const ${name} = (__props__ = {}) => {
|
|
566
|
+
__SLIM_GUARD__;
|
|
567
|
+
return new Function(${JSON.stringify(bindingCode)}, ${JSON.stringify(bodyCode)})(__props__);
|
|
568
|
+
};
|
|
569
|
+
${name}.__component__ = true;
|
|
570
|
+
return ${name};
|
|
571
|
+
})()`)
|
|
572
|
+
return fill(statement, { __SLIM_GUARD__: guard }).expression
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
const body = [...checks, ...before]
|
|
576
|
+
|
|
577
|
+
if (node.modifier === "element") {
|
|
578
|
+
const tag = JSON.stringify(elementTag(node, lowering))
|
|
579
|
+
const [statement] = parseTemplate(`(() => {
|
|
580
|
+
const ${name} = (__props__ = {}) => ${name}.__render__(__props__);
|
|
581
|
+
${name}.__component__ = true;
|
|
582
|
+
${name}.tag = ${tag};
|
|
583
|
+
${name}.__render__ = (__SLIM_PARAM__ = {}, __host__ = null) => __component__(() => {
|
|
584
|
+
const s = {};
|
|
585
|
+
${HOOKS}
|
|
586
|
+
__SLIM_BODY__;
|
|
587
|
+
const __el__ = __SLIM_ELEMENT__;
|
|
588
|
+
if (!__host__) {
|
|
589
|
+
for (const fn of __mounts__) fn(__el__);
|
|
590
|
+
__lifecycle__(__el__, __connects__, __unmounts__);
|
|
591
|
+
return __el__;
|
|
592
|
+
}
|
|
593
|
+
__adopt_into__(__host__, __el__);
|
|
594
|
+
for (const fn of __mounts__) fn(__host__);
|
|
595
|
+
return { connects: __connects__, unmounts: __unmounts__ };
|
|
596
|
+
});
|
|
597
|
+
__define_element__(${tag}, ${name}.__render__);
|
|
598
|
+
return ${name};
|
|
599
|
+
})()`)
|
|
600
|
+
const expression = fill(statement, {
|
|
601
|
+
__SLIM_PARAM__: binding ?? id("__unused__"),
|
|
602
|
+
__SLIM_BODY__: body,
|
|
603
|
+
__SLIM_ELEMENT__: element
|
|
604
|
+
}).expression
|
|
605
|
+
componentFunction(expression)._slimComponent = info
|
|
606
|
+
return expression
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
const [statement] = parseTemplate(`(() => {
|
|
610
|
+
const ${name} = (__SLIM_PARAM__ = {}) => __component__(() => {
|
|
611
|
+
const s = {};
|
|
612
|
+
${HOOKS}
|
|
613
|
+
__SLIM_BODY__;
|
|
614
|
+
const __el__ = __SLIM_ELEMENT__;
|
|
615
|
+
for (const fn of __mounts__) fn(__el__);
|
|
616
|
+
__lifecycle__(__el__, __connects__, __unmounts__);
|
|
617
|
+
return __el__;
|
|
618
|
+
});
|
|
619
|
+
${name}.__component__ = true;
|
|
620
|
+
return ${name};
|
|
621
|
+
})()`)
|
|
622
|
+
|
|
623
|
+
const expression = fill(statement, { __SLIM_BODY__: body, __SLIM_ELEMENT__: element }).expression
|
|
624
|
+
const inner = expression.callee.body.body[0].declarations[0].init
|
|
625
|
+
if (binding) inner.params[0].left = binding
|
|
626
|
+
else inner.params = []
|
|
627
|
+
inner._slimComponent = info
|
|
628
|
+
return expression
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
|
|
632
|
+
const UNWRAP = new Set(["TSAsExpression", "TSSatisfiesExpression", "TSNonNullExpression", "TSTypeAssertion", "TSInstantiationExpression"])
|
|
633
|
+
const UNSUPPORTED = new Set([
|
|
634
|
+
"TSInterfaceDeclaration", "TSEnumDeclaration", "TSModuleDeclaration", "TSDeclareFunction", "TSDeclareMethod",
|
|
635
|
+
"TSImportEqualsDeclaration", "TSExportAssignment", "TSNamespaceExportDeclaration", "TSAbstractMethodDefinition"
|
|
636
|
+
])
|
|
637
|
+
const TYPE_KEYS = ["typeAnnotation", "returnType", "typeParameters", "typeArguments", "superTypeParameters", "implements", "predicate"]
|
|
638
|
+
const MODIFIER_KEYS = ["definite", "declare", "accessibility", "abstract", "override"]
|
|
639
|
+
const PATTERNS = new Set(["Identifier", "ObjectPattern", "ArrayPattern", "RestElement", "AssignmentPattern"])
|
|
640
|
+
|
|
641
|
+
function stripTypes(node, lowering) {
|
|
642
|
+
if (Array.isArray(node)) return node.map(child => stripTypes(child, lowering))
|
|
643
|
+
if (!isNode(node)) return node
|
|
644
|
+
|
|
645
|
+
if (UNSUPPORTED.has(node.type)) lowering.fail(node, `TypeScript syntax (${node.type.slice(2)}) is not supported in Slim`)
|
|
646
|
+
if (UNWRAP.has(node.type)) return stripTypes(node.expression, lowering)
|
|
647
|
+
if (node.type === "TSParameterProperty") return stripTypes(node.parameter, lowering)
|
|
648
|
+
|
|
649
|
+
for (const key of TYPE_KEYS) delete node[key]
|
|
650
|
+
for (const key of MODIFIER_KEYS) delete node[key]
|
|
651
|
+
if (PATTERNS.has(node.type) || node.type === "ClassProperty" || node.type === "ClassMethod") delete node.optional
|
|
652
|
+
if (node.type === "ClassProperty" || node.type === "ClassPrivateProperty") delete node.readonly
|
|
653
|
+
|
|
654
|
+
for (const [key, value] of Object.entries(node)) {
|
|
655
|
+
if (key === "loc" || key === "extra") continue
|
|
656
|
+
if (Array.isArray(value) || isNode(value)) node[key] = stripTypes(value, lowering)
|
|
657
|
+
}
|
|
658
|
+
return node
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
export function lowerSlim(file, code, sourceFile) {
|
|
662
|
+
const lowering = new Lowering(code, sourceFile)
|
|
663
|
+
file.program = lowering.visit(file.program, file)
|
|
664
|
+
stripTypes(file.program, lowering)
|
|
665
|
+
return file
|
|
666
|
+
}
|