@slim-lang/core 1.2.12 → 1.2.15

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 (48) hide show
  1. package/README.md +522 -14
  2. package/package.json +2 -6
  3. package/packages/slim/server/main.slim +433 -422
  4. package/run-dev-slim.js +10 -5
  5. package/run-slim.js +10 -20
  6. package/src/bin/api/github_get.js +7 -12
  7. package/src/bin/api/github_req.js +54 -241
  8. package/src/bin/api/lock.js +2 -1
  9. package/src/bin/api/spm.js +20 -91
  10. package/src/bin/cli.js +73 -102
  11. package/src/bin/config.default.json +11 -11
  12. package/src/bin/helpers.js +2 -7
  13. package/src/bin/spm.js +3 -7
  14. package/src/checker.js +1705 -388
  15. package/src/compile.js +131 -100
  16. package/src/external/classErrors.js +5 -6
  17. package/src/external/client.js +0 -2
  18. package/src/external/core.js +355 -237
  19. package/src/external/defaults.js +12 -4
  20. package/src/external/dom.js +663 -0
  21. package/src/external/helpers.js +87 -58
  22. package/src/external/reactive.js +601 -0
  23. package/src/external/router.js +117 -0
  24. package/src/external/slim-globals.d.ts +43 -4
  25. package/src/external/typeSyntax.js +258 -0
  26. package/src/external/types.js +1 -1
  27. package/src/format.js +183 -12
  28. package/src/handlers/errorHandler.js +9 -36
  29. package/src/jsdoc.js +36 -16
  30. package/src/modulePaths.js +15 -5
  31. package/src/reactivity.js +774 -0
  32. package/src/repl.js +1 -1
  33. package/src/suggest.js +60 -0
  34. package/src/syntax/babel.js +46 -0
  35. package/src/syntax/index.js +39 -0
  36. package/src/syntax/lower.js +666 -0
  37. package/src/syntax/markup.js +195 -0
  38. package/src/syntax/plugin.js +903 -0
  39. package/src/syntax/types.js +106 -0
  40. package/src/test-runner.js +5 -5
  41. package/src/transform.js +209 -244
  42. package/packages/slim/helpers/string.js +0 -43
  43. package/packages/slim/types/hash.js +0 -11
  44. package/src/handlers/parser/components.js +0 -316
  45. package/src/handlers/parserHandler.js +0 -789
  46. package/src/lexer.js +0 -174
  47. package/src/parser.js +0 -803
  48. package/src/sourcemap.js +0 -0
package/src/parser.js DELETED
@@ -1,803 +0,0 @@
1
- import {
2
- extractExpr,
3
- extractExprBackward,
4
- extractExprRaw,
5
- parseTypedArgs,
6
- isInsideString,
7
- parseTypesEdits,
8
- buildTypedArgsResult,
9
- readTypeAnnotation
10
- } from "./handlers/parserHandler.js"
11
- import { parseComponentsEdits } from "./handlers/parser/components.js"
12
- import { createMapped, applyEdits } from "./sourcemap.js"
13
- import { tokenize } from "./lexer.js"
14
-
15
- export function stripComments(code) {
16
- return tokenize(code).map(token => token.type === "comment" ? "" : token.value).join("")
17
- }
18
-
19
- function commentEdits(code) {
20
- const edits = []
21
- for (const token of tokenize(code)) {
22
- if (token.type === "comment") {
23
- edits.push({ start: token.start, end: token.end, replacement: "" })
24
- }
25
- }
26
- return edits
27
- }
28
-
29
- const EXPRESSION_ENDS = new Set([")", "]", "}", "`", "++", "--"])
30
-
31
- function endsExpression(token) {
32
- if (!token) return false
33
- if (token.type === "punct") return EXPRESSION_ENDS.has(token.value)
34
- return token.type === "name" || token.type === "number" ||
35
- token.type === "string" || token.type === "regex" || token.type === "template"
36
- }
37
-
38
- function wordOperatorEdits(code) {
39
- const replacements = { __proto__: null, or: "||", and: "&&" }
40
- const edits = []
41
- let prev = null
42
-
43
- for (const token of tokenize(code)) {
44
- if (token.type === "ws" || token.type === "newline" || token.type === "comment") continue
45
-
46
- const replacement = token.type === "name" ? replacements[token.value] : undefined
47
- if (replacement && endsExpression(prev)) {
48
- edits.push({ start: token.start, end: token.end, replacement })
49
- }
50
-
51
- prev = token
52
- }
53
- return edits
54
- }
55
-
56
- function operatorEdits(code, keyword, fn) {
57
- const edits = []
58
-
59
- for (const token of tokenize(code)) {
60
- if (token.type !== "name" || token.value !== keyword) continue
61
-
62
- let afterKeyword = token.end
63
- while (afterKeyword < code.length && /\s/.test(code[afterKeyword])) afterKeyword++
64
- if (afterKeyword === token.end) continue
65
-
66
- const expr = extractExpr(code, afterKeyword)
67
- if (!expr) continue
68
-
69
- edits.push({ start: token.start, end: afterKeyword + expr.length, replacement: `${fn}(${expr})` })
70
- }
71
-
72
- return edits
73
- }
74
-
75
- function applyBinaryOperator(mapped, token, fn) {
76
- let searchFrom = mapped.text.length
77
-
78
- while (searchFrom >= 0) {
79
- const text = mapped.text
80
- const idx = text.lastIndexOf(token, searchFrom)
81
- if (idx === -1) break
82
- searchFrom = idx - 1
83
-
84
- if (isInsideString(text, idx)) continue
85
-
86
- const { expr: left, start: leftStart } = extractExprBackward(text, idx)
87
- const { expr: right, end: rightEnd } = extractExprForwardLocal(text, idx + token.length)
88
-
89
- if (!left || !right) continue
90
-
91
- mapped = applyEdits(mapped, [{
92
- start: leftStart,
93
- end: rightEnd,
94
- replacement: `${fn}(${left}, ${right})`
95
- }])
96
- }
97
-
98
- return mapped
99
- }
100
-
101
- function extractExprForwardLocal(str, startPos) {
102
- let depth = 0
103
- let i = startPos
104
-
105
- while (i < str.length) {
106
- const ch = str[i]
107
-
108
- if (ch === '"' || ch === "'" || ch === "`") {
109
- const quote = ch
110
- i++
111
- while (i < str.length) {
112
- if (str[i] === "\\") { i += 2; continue }
113
- if (str[i] === quote) { i++; break }
114
- i++
115
- }
116
- continue
117
- }
118
-
119
- if (ch === "(" || ch === "[" || ch === "{") { depth++; i++; continue }
120
- if (ch === ")" || ch === "]" || ch === "}") {
121
- if (depth === 0) break
122
- depth--; i++; continue
123
- }
124
-
125
- if (depth === 0) {
126
- const two = str.slice(i, i + 2)
127
- if (["==", "!=", ">=", "<=", "&&", "||", "??"].includes(two)) break
128
- if (["+", "-", "*", "/", "%", "<", ">", "?", ":", ";", ",", "\n"].includes(ch)) break
129
- }
130
-
131
- i++
132
- }
133
-
134
- return { expr: str.slice(startPos, i).trim(), end: i }
135
- }
136
-
137
- function collectEdits(text, register) {
138
- const replacements = []
139
- const tokens = tokenize(text)
140
-
141
- const isCode = offset => {
142
- let lo = 0
143
- let hi = tokens.length - 1
144
- while (lo <= hi) {
145
- const mid = (lo + hi) >> 1
146
- const token = tokens[mid]
147
- if (offset < token.start) hi = mid - 1
148
- else if (offset >= token.end) lo = mid + 1
149
- else return token.type !== "string" && token.type !== "template" &&
150
- token.type !== "comment" && token.type !== "regex"
151
- }
152
- return true
153
- }
154
-
155
- // Handlers may preserve offsets for verbatim source slices.
156
- const edit = (start, end, produced) => {
157
- const body = typeof produced === "string" ? { replacement: produced } : produced
158
- replacements.push({ start, end, ...body })
159
- }
160
-
161
- function collect(pattern, handler) {
162
- const re = new RegExp(pattern.source,
163
- pattern.flags.includes("g") ? pattern.flags : pattern.flags + "g"
164
- )
165
- let match
166
- while ((match = re.exec(text)) !== null) {
167
- if (!isCode(match.index)) continue
168
- edit(match.index, match.index + match[0].length, handler(...match))
169
- }
170
- }
171
-
172
- function collectCustom(matcher, handler) {
173
- let i = 0
174
- while (i < text.length) {
175
- const result = matcher(text, i)
176
- if (!result) { i++; continue }
177
-
178
- if (isCode(result.start)) edit(result.start, result.end, handler(result))
179
- i = result.end
180
- }
181
- }
182
-
183
- register(collect, collectCustom)
184
- return replacements
185
- }
186
-
187
- const NOT_A_CALL = "(?!if\\b|else\\b|for\\b|while\\b|switch\\b|catch\\b|do\\b|with\\b|return\\b|function\\b|class\\b|try\\b|finally\\b|async\\b)"
188
- const OPENS_BODY = "\\s*\\{"
189
-
190
- function functionEdits(text) {
191
- return collectEdits(text, (collect, collectCustom) => {
192
- const signature = (head, handler, tail = OPENS_BODY) =>
193
- collectCustom(headMatcher(head, tail), handler)
194
-
195
- // Carry return contracts into the AST pass for function-local checks.
196
- const lower = ({ args, returns }, name, emit) => {
197
- const parsed = parseTypedArgs(args)
198
- const { signature: params, checks } = buildTypedArgsResult(parsed, name)
199
- const declaration = returns ? `__declare_return__("${returns}", "${name}")` : ""
200
- const prelude = [checks, declaration].filter(Boolean).join("\n ")
201
-
202
- return prelude ? emit(params, `\n ${prelude}\n`) : emit(params, "")
203
- }
204
-
205
- signature(
206
- "\\bstatic\\s+async\\s+(#?[\\w$]+)\\s*\\(",
207
- ({ groups: [name], args, returns }) =>
208
- lower({ args, returns }, name, (params, checks) => `static async ${name}(${params}) {${checks}`)
209
- )
210
-
211
- signature(
212
- "\\bstatic\\s+(?!async\\s)(#?[\\w$]+)\\s*\\(",
213
- ({ groups: [name], args, returns }) =>
214
- lower({ args, returns }, name, (params, checks) => `static ${name}(${params}) {${checks}`)
215
- )
216
-
217
- signature(
218
- "^([ \\t]*)async\\s+(#?[\\w$]+)\\s*\\(",
219
- ({ groups: [indent, name], args, returns }) => {
220
- const keyword = indent ? "async" : "async function"
221
- return lower({ args, returns }, name, (params, checks) =>
222
- `${indent}${keyword} ${name}(${params}) {${checks}`)
223
- }
224
- )
225
-
226
- signature(
227
- `^([ \\t]*)${NOT_A_CALL}([\\w$]+)\\s*\\(`,
228
- ({ groups: [indent, name], args, returns }) => {
229
- const keyword = indent ? "" : "function "
230
- return lower({ args, returns }, name, (params, checks) =>
231
- `${indent}${keyword}${name}(${params}) {${checks}`)
232
- }
233
- )
234
-
235
- signature(
236
- `(\\{[ \\t]*)(async\\s+)?${NOT_A_CALL}([\\w$]+)\\s*\\(`,
237
- ({ groups: [brace, asyncKw, name], args, returns }) => {
238
- const prefix = asyncKw ? "async " : ""
239
- return lower({ args, returns }, name, (params, checks) =>
240
- `${brace}${prefix}${name}(${params}) {${checks}`)
241
- }
242
- )
243
-
244
- signature(
245
- "\\b(let|const|var)\\s+([\\w$]+)\\s*=\\s*(async\\s*)?\\(",
246
- ({ groups: [keyword, name, asyncKw], args, returns }) =>
247
- lower({ args, returns }, name, (params, checks) =>
248
- `${keyword} ${name} = ${asyncKw ?? ""}(${params}) => {${checks}`),
249
- "\\s*=>\\s*\\{"
250
- )
251
-
252
- const arrowHead = headMatcher(
253
- "\\b(let|const|var)\\s+([\\w$]+)\\s*=\\s*(async\\s*)?\\(",
254
- "\\s*=>\\s*(?!\\{)"
255
- )
256
- collectCustom(
257
- (src, i) => {
258
- const head = arrowHead(src, i)
259
- if (!head) return null
260
- const { expr, end } = extractExprRaw(src, head.end)
261
- return { ...head, end, expr }
262
- },
263
- ({ groups: [keyword, name, asyncKw], args, returns, expr }) =>
264
- lower({ args, returns }, name, (params, checks) => {
265
- const head = `${keyword} ${name} = ${asyncKw ?? ""}(${params}) =>`
266
- if (!checks) return `${head} ${expr}`
267
- return `${head} {${checks} return ${expr}\n}`
268
- })
269
- )
270
-
271
- signature(
272
- "\\basync\\s+func\\s+([\\w$]+)\\s*\\(",
273
- ({ groups: [name], args, returns }) =>
274
- lower({ args, returns }, name, (params, checks) => `async function ${name}(${params}) {${checks}`)
275
- )
276
-
277
- signature(
278
- "\\bfunc\\s+([\\w$]+)\\s*\\(",
279
- ({ groups: [name], args, returns }) =>
280
- lower({ args, returns }, name, (params, checks) => `function ${name}(${params}) {${checks}`)
281
- )
282
-
283
- signature(
284
- "\\b(async\\s+)?function\\s+([\\w$]+)\\s*\\(",
285
- ({ groups: [asyncKw, name], args, returns }) =>
286
- lower({ args, returns }, name, (params, checks) =>
287
- `${asyncKw ?? ""}function ${name}(${params}) {${checks}`)
288
- )
289
- })
290
- }
291
-
292
- const tokenCache = new Map()
293
-
294
- function tokensFor(src) {
295
- const hit = tokenCache.get(src)
296
- if (hit) return hit
297
-
298
- const tokens = tokenize(src)
299
- const starts = new Map()
300
- for (let index = 0; index < tokens.length; index++) {
301
- starts.set(tokens[index].start, index)
302
- }
303
-
304
- if (tokenCache.size >= 8) tokenCache.delete(tokenCache.keys().next().value)
305
- const entry = { tokens, starts }
306
- tokenCache.set(src, entry)
307
- return entry
308
- }
309
-
310
- function readBalanced(src, pos, open = "{", close = "}") {
311
- const { tokens, starts } = tokensFor(src)
312
- let index = starts.get(pos)
313
- if (index === undefined) return -1
314
-
315
- let depth = 0
316
- for (; index < tokens.length; index++) {
317
- const token = tokens[index]
318
- if (token.type !== "punct") continue
319
-
320
- if (token.value === open || (open === "{" && token.value === "${")) depth++
321
- else if (token.value === close) {
322
- depth--
323
- if (depth === 0) return token.end
324
- }
325
- }
326
- return -1
327
- }
328
-
329
- const returnArrow = /\s*(?:->|:)\s*/y
330
-
331
- function headMatcher(head, tail) {
332
- const headRe = new RegExp(head, "ym")
333
- const tailRe = new RegExp(tail, "ym")
334
-
335
- return (src, i) => {
336
- headRe.lastIndex = i
337
- const start = headRe.exec(src)
338
- if (!start) return null
339
-
340
- const parenPos = i + start[0].length - 1
341
- const parenEnd = readBalanced(src, parenPos, "(", ")")
342
- if (parenEnd === -1) return null
343
-
344
- let cursor = parenEnd
345
- let returns = null
346
-
347
- returnArrow.lastIndex = cursor
348
- const arrow = returnArrow.exec(src)
349
- if (arrow) {
350
- const annotation = readTypeAnnotation(src, cursor + arrow[0].length)
351
- if (!annotation) return null
352
- returns = annotation.type
353
- cursor = annotation.end
354
- }
355
-
356
- tailRe.lastIndex = cursor
357
- const end = tailRe.exec(src)
358
- if (!end) return null
359
-
360
- return {
361
- start: i,
362
- end: cursor + end[0].length,
363
- groups: start.slice(1),
364
- args: src.slice(parenPos + 1, parenEnd - 1),
365
- returns
366
- }
367
- }
368
- }
369
-
370
- function splitTopLevel(str, separator) {
371
- const parts = []
372
- let depth = 0
373
- let current = ""
374
-
375
- for (let i = 0; i < str.length; i++) {
376
- const c = str[i]
377
- if (c === '"' || c === "'" || c === "`") {
378
- const quote = c
379
- current += c
380
- i++
381
- while (i < str.length) {
382
- current += str[i]
383
- if (str[i] === "\\") { i++; if (i < str.length) current += str[i]; i++; continue }
384
- if (str[i] === quote) break
385
- i++
386
- }
387
- continue
388
- }
389
- if (c === "(" || c === "[" || c === "{") depth++
390
- else if (c === ")" || c === "]" || c === "}") depth--
391
- else if (c === separator && depth === 0) { parts.push(current); current = ""; continue }
392
- current += c
393
- }
394
- if (current.trim()) parts.push(current)
395
- return parts
396
- }
397
-
398
- function topLevelArrow(str) {
399
- let depth = 0
400
- for (let i = 0; i < str.length - 1; i++) {
401
- const c = str[i]
402
- if (c === '"' || c === "'" || c === "`") {
403
- const quote = c
404
- i++
405
- while (i < str.length) { if (str[i] === "\\") { i += 2; continue } if (str[i] === quote) break; i++ }
406
- continue
407
- }
408
- if (c === "(" || c === "[" || c === "{") depth++
409
- else if (c === ")" || c === "]" || c === "}") depth--
410
- else if (depth === 0 && c === "=" && str[i + 1] === ">") return i
411
- }
412
- return -1
413
- }
414
-
415
- function matchMatcher(src, i) {
416
- if (i > 0 && /[\w$.]/.test(src[i - 1])) return null
417
-
418
- const re = /match\s*\(/y
419
- re.lastIndex = i
420
- const m = re.exec(src)
421
- if (!m || m.index !== i) return null
422
-
423
- const parenPos = i + m[0].length - 1
424
- const parenEnd = readBalanced(src, parenPos, "(", ")")
425
- if (parenEnd === -1) return null
426
-
427
- let j = parenEnd
428
- while (j < src.length && /\s/.test(src[j])) j++
429
- if (src[j] !== "{") return null
430
-
431
- const braceEnd = readBalanced(src, j)
432
- if (braceEnd === -1) return null
433
-
434
- return {
435
- start: i,
436
- end: braceEnd,
437
- scrutinee: src.slice(parenPos + 1, parenEnd - 1).trim(),
438
- body: src.slice(j + 1, braceEnd - 1)
439
- }
440
- }
441
-
442
- function topLevelWhen(str) {
443
- let depth = 0
444
- for (let i = 0; i < str.length; i++) {
445
- const c = str[i]
446
- if (c === '"' || c === "'" || c === "`") {
447
- const quote = c
448
- i++
449
- while (i < str.length) { if (str[i] === "\\") { i += 2; continue } if (str[i] === quote) break; i++ }
450
- continue
451
- }
452
- if (c === "(" || c === "[" || c === "{") depth++
453
- else if (c === ")" || c === "]" || c === "}") depth--
454
- else if (depth === 0 && str.startsWith("when", i) &&
455
- !/[\w$]/.test(str[i - 1] || "") && !/[\w$]/.test(str[i + 4] || "")) return i
456
- }
457
- return -1
458
- }
459
-
460
- function lowerMatches(str) {
461
- if (!str.includes("match")) return str
462
-
463
- const { tokens } = tokensFor(str)
464
- const edits = []
465
-
466
- for (let index = 0; index < tokens.length; index++) {
467
- const token = tokens[index]
468
- if (token.type !== "name" || token.value !== "match") continue
469
-
470
- const found = matchMatcher(str, token.start)
471
- if (!found) continue
472
-
473
- edits.push({ start: found.start, end: found.end, replacement: buildMatch(found) })
474
- while (index + 1 < tokens.length && tokens[index + 1].start < found.end) index++
475
- }
476
-
477
- if (edits.length === 0) return str
478
-
479
- let out = ""
480
- let cursor = 0
481
- for (const edit of edits) {
482
- out += str.slice(cursor, edit.start) + edit.replacement
483
- cursor = edit.end
484
- }
485
- return out + str.slice(cursor)
486
- }
487
-
488
- function buildMatch({ scrutinee, body }) {
489
- const statements = []
490
- let fallback = "return undefined"
491
-
492
- for (const rawCase of splitTopLevel(body, ",")) {
493
- const arrow = topLevelArrow(rawCase)
494
- if (arrow === -1) continue
495
-
496
- const head = rawCase.slice(0, arrow).trim()
497
- const result = lowerMatches(rawCase.slice(arrow + 2).trim())
498
- if (!head || !result) continue
499
-
500
- const when = topLevelWhen(head)
501
- if (when !== -1) {
502
- const binding = head.slice(0, when).trim()
503
- const guard = head.slice(when + 4).trim()
504
- const bind = binding && binding !== "_" ? `const ${binding} = __match; ` : ""
505
- statements.push(`{ ${bind}if (${guard}) return ${result} }`)
506
- } else if (head === "_") {
507
- fallback = `return ${result}`
508
- } else {
509
- statements.push(`if (__match_eq__(__match, ${head})) return ${result}`)
510
- }
511
- }
512
-
513
- return `((__match) => { ${[...statements, fallback].join("; ")} })(${lowerMatches(scrutinee)})`
514
- }
515
-
516
- function declMatcher(keyword) {
517
- return (src, i) => {
518
- const re = new RegExp(`(export\\s+)?${keyword}\\s+([A-Z][\\w$]*)(?:\\s+extends\\s+([A-Z][\\w$]*))?\\s*\\{`, "y")
519
- re.lastIndex = i
520
- const m = re.exec(src)
521
- if (!m) return null
522
-
523
- const bracePos = i + m[0].length - 1
524
- const end = readBalanced(src, bracePos)
525
- if (end === -1) return null
526
-
527
- return { start: i, end, exportKw: m[1], name: m[2], extendsName: m[3], body: src.slice(bracePos + 1, end - 1) }
528
- }
529
- }
530
-
531
- const declarationHead = /\b(let|const|var|static)\s+(#?[\w$]+|\{[^{}]*\}|\[[^\[\]]*\])\s*:\s*/y
532
-
533
- const structMethodHead = /([\w$]+)\s*\(/y
534
-
535
- function structMethod(body, i) {
536
- structMethodHead.lastIndex = i
537
- const head = structMethodHead.exec(body)
538
- if (!head) return null
539
-
540
- const parenPos = i + head[0].length - 1
541
- const parenEnd = readBalanced(body, parenPos, "(", ")")
542
- if (parenEnd === -1) return null
543
-
544
- let brace = parenEnd
545
- while (brace < body.length && /\s/.test(body[brace])) brace++
546
- if (body[brace] !== "{") return null
547
-
548
- const end = readBalanced(body, brace)
549
- if (end === -1) return null
550
-
551
- return {
552
- name: head[1],
553
- params: body.slice(parenPos + 1, parenEnd - 1),
554
- body: body.slice(brace + 1, end - 1),
555
- end
556
- }
557
- }
558
-
559
- function parseStructBody(body) {
560
- const fieldLines = []
561
- const methods = []
562
- let i = 0
563
-
564
- while (i < body.length) {
565
- while (i < body.length && /[\s,]/.test(body[i])) i++
566
- if (i >= body.length) break
567
-
568
- const method = structMethod(body, i)
569
- if (method) {
570
- methods.push(`"${method.name}": function(${method.params}) {${method.body}}`)
571
- i = method.end
572
- continue
573
- }
574
-
575
- const start = i
576
- while (i < body.length && body[i] !== "\n") i++
577
- fieldLines.push(body.slice(start, i))
578
- }
579
-
580
- return { fieldLines, methods }
581
- }
582
-
583
- function structuralEdits(text) {
584
- return collectEdits(text, (collect, collectCustom) => {
585
- collectCustom(matchMatcher, buildMatch)
586
-
587
- collect(
588
- /use\s+(\*\s+as\s+[\w$]+|\{[^}]+\}|[a-zA-Z_$][\w$]*\s+as\s+[\w$]+|[a-zA-Z_$][\w$]*)\s+from\s+["']([^"']+)["']\s*;?/g,
589
- (_, name, source) =>
590
- `__use__(${JSON.stringify(name.trim())}, ${JSON.stringify(source)})\n`
591
- )
592
- collect(
593
- /use\s+(\*\s+as\s+[\w$]+|\{[^}]+\}|[a-zA-Z_$][\w$]*\s+as\s+[\w$]+|[a-zA-Z_$][\w$]*)\s+from\s+(@[\w$\/.-]+)\s*;?/g,
594
- (_, name, source) =>
595
- `__use__(${JSON.stringify(name.trim())}, ${JSON.stringify(source)})\n`
596
- )
597
- collect(
598
- /use\s+(@[\w$\/.-]+)\s*;?/g,
599
- (_, source) => `__use_all__(${JSON.stringify(source)})\n`
600
- )
601
- collect(
602
- /use\s+["']([^"']+)["']\s*;?/g,
603
- (_, source) => `__use_all__(${JSON.stringify(source)})\n`
604
- )
605
-
606
- collectCustom(
607
- declMatcher("struct"),
608
- ({ exportKw, name, extendsName, body }) => {
609
- const { fieldLines, methods } = parseStructBody(body)
610
- const schema = []
611
- const defaults = []
612
-
613
- for (let line of fieldLines) {
614
- line = line.trim().replace(/,\s*$/, "").trim()
615
- if (!line) continue
616
-
617
- const idx = line.indexOf(":")
618
- if (idx === -1) continue
619
-
620
- let field = line.slice(0, idx).trim()
621
- let rest = line.slice(idx + 1).trim()
622
- if (!field) continue
623
-
624
- let optional = false
625
- if (field.startsWith("*")) { optional = true; field = field.slice(1).trim() }
626
- if (field.endsWith("?")) { optional = true; field = field.slice(0, -1).trim() }
627
- if (optional) field = "*" + field
628
-
629
- const eq = rest.indexOf("=")
630
- if (eq !== -1) {
631
- const value = rest.slice(eq + 1).trim()
632
- rest = rest.slice(0, eq).trim()
633
- if (value) defaults.push(`"${field.replace(/^\*/, "").trim()}": () => (${value})`)
634
- }
635
-
636
- if (!rest) continue
637
- schema.push(`"${field}": "${rest}"`)
638
- }
639
-
640
- const defaultsArg = defaults.length ? `{ ${defaults.join(", ")} }` : "{}"
641
- const args = [`"${name}"`, `{ ${schema.join(", ")} }`, "{}", defaultsArg]
642
- if (extendsName || methods.length) args.push(extendsName ? `"${extendsName}"` : "null")
643
- if (methods.length) args.push(`{ ${methods.join(", ")} }`)
644
-
645
- const decl = `const ${name} = __def_struct__(${args.join(", ")})`
646
- return exportKw ? `export ${decl}` : decl
647
- }
648
- )
649
- collectCustom(
650
- declMatcher("enum"),
651
- ({ exportKw, name, body }) => {
652
- const fields = body
653
- .split("\n")
654
- .map(line => line.replace(/,\s*$/, "").trim())
655
- .filter(Boolean)
656
- .map(line => {
657
- const idx = line.indexOf(":")
658
- if (idx === -1) {
659
- const field = line.trim()
660
- return `"${field}": "${field}"`
661
- }
662
- const field = line.slice(0, idx).trim()
663
- const value = line.slice(idx + 1).trim()
664
- if (!field || !value) return null
665
- return `"${field}": ${value}`
666
- })
667
- .filter(Boolean)
668
- .join(", ")
669
-
670
- const decl = `const ${name} = __def_enum__("${name}", { ${fields} })`
671
- return exportKw ? `export ${decl}` : decl
672
- }
673
- )
674
-
675
- collectCustom(
676
- (src, i) => {
677
- if (isInsideString(src, i)) return null
678
-
679
- declarationHead.lastIndex = i
680
- const head = declarationHead.exec(src)
681
- if (!head) return null
682
-
683
- const leadingDefault = src.slice(0, i).match(/export\s+default\s+$/)
684
- const start = leadingDefault ? i - leadingDefault[0].length : i
685
-
686
- const annotation = readTypeAnnotation(src, i + head[0].length)
687
- if (!annotation) return null
688
-
689
- let equals = annotation.end
690
- while (equals < src.length && /\s/.test(src[equals])) equals++
691
- if (src[equals] !== "=" || src[equals + 1] === "=" || src[equals + 1] === ">") return null
692
-
693
- const { expr, start: exprStart, end } = extractExprRaw(src, equals + 1)
694
- return {
695
- start, end, keyword: head[1], name: head[2], type: annotation.type,
696
- expr, exprStart, defaultExport: !!leadingDefault
697
- }
698
- },
699
- ({ keyword, name, type, expr, exprStart, defaultExport }) => {
700
- const pattern = name.startsWith("{") || name.startsWith("[")
701
- const prefix = defaultExport ? "export " : ""
702
- const head = pattern
703
- ? `${prefix}${keyword} ${name} = __typed_pattern__(`
704
- : `${prefix}${keyword} ${name} = __typed_variable__(`
705
- const tail = pattern ? `, "${type}")` : `, "${type}", "${name}")`
706
- const suffix = defaultExport ? `\nexport { ${name} as default }` : ""
707
-
708
- return {
709
- replacement: `${head}${expr}${tail}${suffix}`,
710
- spans: [{ at: head.length, from: exprStart, length: expr.length }]
711
- }
712
- }
713
- )
714
-
715
- collect(
716
- /(\w[\w$.]*(?:\[.*?\])?)\s*(?:=>\s*([\w$]+))?\s*\n((?:\s*\|(?!\|)[^\n]+\n?)+)/g,
717
- (match, source, alias, pipes) => {
718
- const steps = [...pipes.matchAll(/\|\s*([\w$]+)\(([^)]*)\)/g)]
719
- if (steps.length === 0) return match
720
-
721
- const callbackMethods = new Set([
722
- "map", "filter", "find", "findIndex",
723
- "some", "every", "flatMap", "forEach",
724
- "reduce", "reduceRight"
725
- ])
726
- const chain = steps.map(([, method, args]) => {
727
- if (alias) {
728
- if (args.includes("=>")) return `.${method}(${args.trim()})`
729
- if (callbackMethods.has(method)) return `.${method}(${alias} => ${args.trim()})`
730
- return `.${method}(${args.trim()})`
731
- }
732
- return `.${method}(${args.trim()})`
733
- }).join("")
734
- return `${source}${chain}`
735
- }
736
- )
737
-
738
- collectCustom(
739
- (code, i) => {
740
- if (i > 0 && /[\w$]/.test(code[i - 1])) return null
741
- const match = code.slice(i).match(/^lock\s+const\s+([\w$]+)\s*=\s*/)
742
- if (!match) return null
743
- const name = match[1]
744
- const afterEq = i + match[0].length
745
- const expr = extractExpr(code, afterEq)
746
- return { start: i, end: afterEq + expr.length, name, expr }
747
- },
748
- ({ name, expr }) => `const ${name} = __lock_object__(${expr})`
749
- )
750
-
751
- collectCustom(
752
- (code, i) => {
753
- if (i > 0 && /[\w$]/.test(code[i - 1])) return null
754
- const match = code.slice(i).match(/^lock\s+(?!const\s)/)
755
- if (!match) return null
756
- const afterKeyword = i + match[0].length
757
- const expr = extractExpr(code, afterKeyword)
758
- return { start: i, end: afterKeyword + expr.length, expr }
759
- },
760
- ({ expr }) => `__lock_object__(${expr})`
761
- )
762
-
763
- collect(
764
- /\}\s*elif\s*\(/g,
765
- match => match.replace("elif", "else if")
766
- )
767
-
768
- collect(
769
- /mode\s+["']([^"']+)["']/,
770
- (_, name) => {
771
- if(name == "strict") {
772
- return `"use strict"`
773
- }
774
- else {
775
- return ''
776
- }
777
- }
778
- )
779
- })
780
- }
781
-
782
- export function preprocess(code, sourceFile = "index.slim") {
783
- let mapped = createMapped(code)
784
-
785
- mapped = applyEdits(mapped, commentEdits(mapped.text))
786
- mapped = applyEdits(mapped, wordOperatorEdits(mapped.text))
787
-
788
- mapped = applyEdits(mapped, parseTypesEdits(mapped.text))
789
-
790
- mapped = applyEdits(mapped, operatorEdits(mapped.text, "sizeof", "__sizeof__"))
791
- mapped = applyEdits(mapped, operatorEdits(mapped.text, "kindof", "type"))
792
- mapped = applyEdits(mapped, operatorEdits(mapped.text, "empty", "__is_empty__"))
793
- mapped = applyEdits(mapped, operatorEdits(mapped.text, "copyof", "__copyof__"))
794
- mapped = applyBinaryOperator(mapped, "~/", "__intdiv__")
795
-
796
- mapped = applyEdits(mapped, parseComponentsEdits(mapped.text))
797
-
798
- mapped = applyEdits(mapped, functionEdits(mapped.text))
799
-
800
- mapped = applyEdits(mapped, structuralEdits(mapped.text))
801
-
802
- return { code: mapped.text, mapped, source: sourceFile }
803
- }